You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by cc...@apache.org on 2017/12/14 21:57:13 UTC
[48/57] [abbrv] [partial] groovy git commit: Move Java source set
into `src/main/java`
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
new file mode 100644
index 0000000..dcfe314
--- /dev/null
+++ b/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.transform
+
+import groovy.transform.CompilationUnitAware
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.AnnotationNode
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.expr.ClosureExpression
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.stmt.Statement
+import org.codehaus.groovy.control.CompilationUnit
+import org.codehaus.groovy.control.CompilePhase
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.ErrorCollector
+import org.codehaus.groovy.control.Janitor
+import org.codehaus.groovy.control.ProcessingUnit
+import org.codehaus.groovy.control.SourceUnit
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.codehaus.groovy.control.io.ReaderSource
+import org.codehaus.groovy.runtime.MethodClosure
+import org.codehaus.groovy.syntax.SyntaxException
+import org.codehaus.groovy.tools.Utilities
+
+import static org.codehaus.groovy.ast.tools.GeneralUtils.classX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.propX
+
+@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
+class ASTTestTransformation extends AbstractASTTransformation implements CompilationUnitAware {
+ private CompilationUnit compilationUnit
+
+ void visit(final ASTNode[] nodes, final SourceUnit source) {
+ AnnotationNode annotationNode = nodes[0]
+ def member = annotationNode.getMember('phase')
+ def phase = null
+ if (member) {
+ if (member instanceof VariableExpression) {
+ phase = CompilePhase.valueOf(member.text)
+ } else if (member instanceof PropertyExpression) {
+ phase = CompilePhase.valueOf(member.propertyAsString)
+ }
+ annotationNode.setMember('phase', propX(classX(ClassHelper.make(CompilePhase)), phase.toString()))
+ }
+ member = annotationNode.getMember('value')
+ if (member && !(member instanceof ClosureExpression)) {
+ throw new SyntaxException("ASTTest value must be a closure", member.getLineNumber(), member.getColumnNumber())
+ }
+ if (!member && !annotationNode.getNodeMetaData(ASTTestTransformation)) {
+ throw new SyntaxException("Missing test expression", annotationNode.getLineNumber(), annotationNode.getColumnNumber())
+ }
+ // convert value into node metadata so that the expression doesn't mix up with other AST xforms like type checking
+ annotationNode.putNodeMetaData(ASTTestTransformation, member)
+ annotationNode.getMembers().remove('value')
+
+ def pcallback = compilationUnit.progressCallback
+ def callback = new CompilationUnit.ProgressCallback() {
+ Binding binding = new Binding([:].withDefault {null})
+
+ @Override
+ void call(final ProcessingUnit context, final int phaseRef) {
+ if (phase==null || phaseRef == phase.phaseNumber) {
+ ClosureExpression testClosure = nodes[0].getNodeMetaData(ASTTestTransformation)
+ StringBuilder sb = new StringBuilder()
+ for (int i = testClosure.lineNumber; i <= testClosure.lastLineNumber; i++) {
+ sb.append(source.source.getLine(i, new Janitor())).append('\n')
+ }
+ def testSource = sb.substring(testClosure.columnNumber + 1, sb.length())
+ testSource = testSource.substring(0, testSource.lastIndexOf('}'))
+ CompilerConfiguration config = new CompilerConfiguration()
+ def customizer = new ImportCustomizer()
+ config.addCompilationCustomizers(customizer)
+ binding['sourceUnit'] = source
+ binding['node'] = nodes[1]
+ binding['lookup'] = new MethodClosure(LabelFinder, "lookup").curry(nodes[1])
+ binding['compilationUnit'] = compilationUnit
+ binding['compilePhase'] = CompilePhase.fromPhaseNumber(phaseRef)
+
+ GroovyShell shell = new GroovyShell(binding, config)
+
+ source.AST.imports.each {
+ customizer.addImport(it.alias, it.type.name)
+ }
+ source.AST.starImports.each {
+ customizer.addStarImports(it.packageName)
+ }
+ source.AST.staticImports.each {
+ customizer.addStaticImport(it.value.alias, it.value.type.name, it.value.fieldName)
+ }
+ source.AST.staticStarImports.each {
+ customizer.addStaticStars(it.value.className)
+ }
+ shell.evaluate(testSource)
+ }
+ }
+ }
+
+ if (pcallback!=null) {
+ if (pcallback instanceof ProgressCallbackChain) {
+ pcallback.addCallback(callback)
+ } else {
+ pcallback = new ProgressCallbackChain(pcallback, callback)
+ }
+ callback = pcallback
+ }
+
+ compilationUnit.setProgressCallback(callback)
+
+ }
+
+ void setCompilationUnit(final CompilationUnit unit) {
+ this.compilationUnit = unit
+ }
+
+ private static class AssertionSourceDelegatingSourceUnit extends SourceUnit {
+ private final ReaderSource delegate
+
+ AssertionSourceDelegatingSourceUnit(final String name, final ReaderSource source, final CompilerConfiguration flags, final GroovyClassLoader loader, final ErrorCollector er) {
+ super(name, '', flags, loader, er)
+ delegate = source
+ }
+
+ @Override
+ String getSample(final int line, final int column, final Janitor janitor) {
+ String sample = null;
+ String text = delegate.getLine(line, janitor);
+
+ if (text != null) {
+ if (column > 0) {
+ String marker = Utilities.repeatString(" ", column - 1) + "^";
+
+ if (column > 40) {
+ int start = column - 30 - 1;
+ int end = (column + 10 > text.length() ? text.length() : column + 10 - 1);
+ sample = " " + text.substring(start, end) + Utilities.eol() + " " +
+ marker.substring(start, marker.length());
+ } else {
+ sample = " " + text + Utilities.eol() + " " + marker;
+ }
+ } else {
+ sample = text;
+ }
+ }
+
+ return sample;
+
+ }
+
+ }
+
+ private static class ProgressCallbackChain extends CompilationUnit.ProgressCallback {
+
+ private final List<CompilationUnit.ProgressCallback> chain = new LinkedList<CompilationUnit.ProgressCallback>()
+
+ ProgressCallbackChain(CompilationUnit.ProgressCallback... callbacks) {
+ if (callbacks!=null) {
+ callbacks.each { addCallback(it) }
+ }
+ }
+
+ public void addCallback(CompilationUnit.ProgressCallback callback) {
+ chain << callback
+ }
+
+ @Override
+ void call(final ProcessingUnit context, final int phase) {
+ chain*.call(context, phase)
+ }
+ }
+
+ public static class LabelFinder extends ClassCodeVisitorSupport {
+
+ public static List<Statement> lookup(MethodNode node, String label) {
+ LabelFinder finder = new LabelFinder(label, null)
+ node.code.visit(finder)
+
+ finder.targets
+ }
+
+ public static List<Statement> lookup(ClassNode node, String label) {
+ LabelFinder finder = new LabelFinder(label, null)
+ node.methods*.code*.visit(finder)
+ node.declaredConstructors*.code*.visit(finder)
+
+ finder.targets
+ }
+
+ private final String label
+ private final SourceUnit unit
+
+ private final List<Statement> targets = new LinkedList<Statement>();
+
+ LabelFinder(final String label, final SourceUnit unit) {
+ this.label = label
+ this.unit = unit;
+ }
+
+ @Override
+ protected SourceUnit getSourceUnit() {
+ unit
+ }
+
+ @Override
+ protected void visitStatement(final Statement statement) {
+ super.visitStatement(statement)
+ if (statement.statementLabel==label) targets << statement
+ }
+
+ List<Statement> getTargets() {
+ return Collections.unmodifiableList(targets)
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/groovy/org/codehaus/groovy/transform/ConditionalInterruptibleASTTransformation.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/org/codehaus/groovy/transform/ConditionalInterruptibleASTTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/ConditionalInterruptibleASTTransformation.groovy
new file mode 100644
index 0000000..2cda121
--- /dev/null
+++ b/src/main/groovy/org/codehaus/groovy/transform/ConditionalInterruptibleASTTransformation.groovy
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.transform
+
+import groovy.transform.ConditionalInterrupt
+import org.codehaus.groovy.ast.AnnotatedNode
+import org.codehaus.groovy.ast.AnnotationNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.FieldNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.PropertyNode
+import org.codehaus.groovy.ast.expr.ArgumentListExpression
+import org.codehaus.groovy.ast.expr.ClosureExpression
+import org.codehaus.groovy.ast.expr.Expression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.tools.ClosureUtils
+import org.codehaus.groovy.control.CompilePhase
+
+/**
+ * Allows "interrupt-safe" executions of scripts by adding a custom conditional
+ * check on loops (for, while, do) and first statement of closures. By default, also adds an interrupt check
+ * statement on the beginning of method calls.
+ *
+ * @see groovy.transform.ConditionalInterrupt
+ * @author Cedric Champeau
+ * @author Hamlet D'Arcy
+ * @author Paul King
+ * @since 1.8.0
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class ConditionalInterruptibleASTTransformation extends AbstractInterruptibleASTTransformation {
+
+ private static final ClassNode MY_TYPE = ClassHelper.make(ConditionalInterrupt)
+
+ private ClosureExpression conditionNode
+ private String conditionMethod
+ private MethodCallExpression conditionCallExpression
+ private ClassNode currentClass
+
+ protected ClassNode type() {
+ return MY_TYPE
+ }
+
+ protected void setupTransform(AnnotationNode node) {
+ super.setupTransform(node)
+ def member = node.getMember("value")
+ if (!member || !(member instanceof ClosureExpression)) internalError("Expected closure value for annotation parameter 'value'. Found $member")
+ conditionNode = member;
+ conditionMethod = 'conditionalTransform' + node.hashCode() + '$condition'
+ conditionCallExpression = new MethodCallExpression(new VariableExpression('this'), conditionMethod, new ArgumentListExpression())
+ }
+
+ protected String getErrorMessage() {
+ 'Execution interrupted. The following condition failed: ' + convertClosureToSource(conditionNode)
+ }
+
+ void visitClass(ClassNode type) {
+ currentClass = type
+ def method = type.addMethod(conditionMethod, ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, conditionNode.code)
+ method.synthetic = true
+ if (applyToAllMembers) {
+ super.visitClass(type)
+ }
+ }
+
+ protected Expression createCondition() {
+ conditionCallExpression
+ }
+
+ @Override
+ void visitAnnotations(AnnotatedNode node) {
+ // this transformation does not apply on annotation nodes
+ // visiting could lead to stack overflows
+ }
+
+ @Override
+ void visitField(FieldNode node) {
+ if (!node.isStatic() && !node.isSynthetic()) {
+ super.visitField node
+ }
+ }
+
+ @Override
+ void visitProperty(PropertyNode node) {
+ if (!node.isStatic() && !node.isSynthetic()) {
+ super.visitProperty node
+ }
+ }
+
+ @Override
+ void visitClosureExpression(ClosureExpression closureExpr) {
+ if (closureExpr == conditionNode) return // do not visit the closure from the annotation itself
+ def code = closureExpr.code
+ closureExpr.code = wrapBlock(code)
+ super.visitClosureExpression closureExpr
+ }
+
+ @Override
+ void visitMethod(MethodNode node) {
+ if (node.name == conditionMethod && !node.isSynthetic()) return // do not visit the generated method
+ if (node.name == 'run' && currentClass.isScript() && node.parameters.length == 0) {
+ // the run() method should not have the statement added, otherwise the script binding won't be set before
+ // the condition is actually tested
+ super.visitMethod(node)
+ } else {
+ if (checkOnMethodStart && !node.isSynthetic() && !node.isStatic() && !node.isAbstract()) {
+ def code = node.code
+ node.code = wrapBlock(code);
+ }
+ if (!node.isSynthetic() && !node.isStatic()) super.visitMethod(node)
+ }
+ }
+
+ /**
+ * Converts a ClosureExpression into the String source.
+ * @param expression a closure
+ * @return the source the closure was created from
+ */
+ private String convertClosureToSource(ClosureExpression expression) {
+ try {
+ return ClosureUtils.convertClosureToSource(this.source.source, expression);
+ } catch(Exception e) {
+ return e.message
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/groovy/org/codehaus/groovy/transform/ThreadInterruptibleASTTransformation.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/org/codehaus/groovy/transform/ThreadInterruptibleASTTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/ThreadInterruptibleASTTransformation.groovy
new file mode 100644
index 0000000..a4fb4c3
--- /dev/null
+++ b/src/main/groovy/org/codehaus/groovy/transform/ThreadInterruptibleASTTransformation.groovy
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.transform
+
+import groovy.transform.CompileStatic
+import groovy.transform.ThreadInterrupt
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.expr.ArgumentListExpression
+import org.codehaus.groovy.ast.expr.ClassExpression
+import org.codehaus.groovy.ast.expr.ClosureExpression
+import org.codehaus.groovy.ast.expr.Expression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.control.CompilePhase
+
+/**
+ * Allows "interrupt-safe" executions of scripts by adding Thread.currentThread().isInterrupted()
+ * checks on loops (for, while, do) and first statement of closures. By default, also adds an interrupt check
+ * statement on the beginning of method calls.
+ *
+ * @see groovy.transform.ThreadInterrupt
+ *
+ * @author Cedric Champeau
+ * @author Hamlet D'Arcy
+ *
+ * @since 1.8.0
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+@CompileStatic
+public class ThreadInterruptibleASTTransformation extends AbstractInterruptibleASTTransformation {
+
+ private static final ClassNode MY_TYPE = ClassHelper.make(ThreadInterrupt)
+ private static final ClassNode THREAD_TYPE = ClassHelper.make(Thread)
+ private static final MethodNode CURRENTTHREAD_METHOD
+ private static final MethodNode ISINTERRUPTED_METHOD
+
+ static {
+ CURRENTTHREAD_METHOD = THREAD_TYPE.getMethod('currentThread', Parameter.EMPTY_ARRAY)
+ ISINTERRUPTED_METHOD = THREAD_TYPE.getMethod('isInterrupted', Parameter.EMPTY_ARRAY)
+ }
+
+ protected ClassNode type() {
+ return MY_TYPE;
+ }
+
+ protected String getErrorMessage() {
+ 'Execution interrupted. The current thread has been interrupted.'
+ }
+
+ protected Expression createCondition() {
+ def currentThread = new MethodCallExpression(new ClassExpression(THREAD_TYPE),
+ 'currentThread',
+ ArgumentListExpression.EMPTY_ARGUMENTS)
+ currentThread.methodTarget = CURRENTTHREAD_METHOD
+ def isInterrupted = new MethodCallExpression(
+ currentThread,
+ 'isInterrupted', ArgumentListExpression.EMPTY_ARGUMENTS)
+ isInterrupted.methodTarget = ISINTERRUPTED_METHOD
+ [currentThread, isInterrupted]*.implicitThis = false
+
+ isInterrupted
+ }
+
+
+ @Override
+ public void visitClosureExpression(ClosureExpression closureExpr) {
+ def code = closureExpr.code
+ closureExpr.code = wrapBlock(code)
+ super.visitClosureExpression closureExpr
+ }
+
+ @Override
+ public void visitMethod(MethodNode node) {
+ if (checkOnMethodStart && !node.isSynthetic() && !node.isAbstract()) {
+ def code = node.code
+ node.code = wrapBlock(code);
+ }
+ super.visitMethod(node)
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
new file mode 100644
index 0000000..fbc923b
--- /dev/null
+++ b/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.transform
+
+import groovy.transform.TimedInterrupt
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.AnnotatedNode
+import org.codehaus.groovy.ast.AnnotationNode
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.FieldNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.PropertyNode
+import org.codehaus.groovy.ast.expr.ClosureExpression
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.expr.DeclarationExpression
+import org.codehaus.groovy.ast.expr.Expression
+import org.codehaus.groovy.ast.stmt.BlockStatement
+import org.codehaus.groovy.ast.stmt.DoWhileStatement
+import org.codehaus.groovy.ast.stmt.ForStatement
+import org.codehaus.groovy.ast.stmt.WhileStatement
+import org.codehaus.groovy.control.CompilePhase
+import org.codehaus.groovy.control.SourceUnit
+
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.TimeoutException
+
+import static org.codehaus.groovy.ast.ClassHelper.make
+import static org.codehaus.groovy.ast.tools.GeneralUtils.args
+import static org.codehaus.groovy.ast.tools.GeneralUtils.callX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.classX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.constX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ifS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ltX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.plusX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.propX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.throwS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.varX
+
+/**
+ * Allows "interrupt-safe" executions of scripts by adding timer expiration
+ * checks on loops (for, while, do) and first statement of closures. By default,
+ * also adds an interrupt check statement on the beginning of method calls.
+ *
+ * @author Cedric Champeau
+ * @author Hamlet D'Arcy
+ * @author Paul King
+ * @see groovy.transform.ThreadInterrupt
+ * @since 1.8.0
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class TimedInterruptibleASTTransformation extends AbstractASTTransformation {
+
+ private static final ClassNode MY_TYPE = make(TimedInterrupt)
+ private static final String CHECK_METHOD_START_MEMBER = 'checkOnMethodStart'
+ private static final String APPLY_TO_ALL_CLASSES = 'applyToAllClasses'
+ private static final String APPLY_TO_ALL_MEMBERS = 'applyToAllMembers'
+ private static final String THROWN_EXCEPTION_TYPE = "thrown"
+
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ init(nodes, source);
+ AnnotationNode node = nodes[0]
+ AnnotatedNode annotatedNode = nodes[1]
+ if (!MY_TYPE.equals(node.getClassNode())) {
+ internalError("Transformation called from wrong annotation: $node.classNode.name")
+ }
+
+ def checkOnMethodStart = getConstantAnnotationParameter(node, CHECK_METHOD_START_MEMBER, Boolean.TYPE, true)
+ def applyToAllMembers = getConstantAnnotationParameter(node, APPLY_TO_ALL_MEMBERS, Boolean.TYPE, true)
+ def applyToAllClasses = applyToAllMembers ? getConstantAnnotationParameter(node, APPLY_TO_ALL_CLASSES, Boolean.TYPE, true) : false
+ def maximum = getConstantAnnotationParameter(node, 'value', Long.TYPE, Long.MAX_VALUE)
+ def thrown = AbstractInterruptibleASTTransformation.getClassAnnotationParameter(node, THROWN_EXCEPTION_TYPE, make(TimeoutException))
+
+ Expression unit = node.getMember('unit') ?: propX(classX(TimeUnit), "SECONDS")
+
+ // should be limited to the current SourceUnit or propagated to the whole CompilationUnit
+ // DO NOT inline visitor creation in code below. It has state that must not persist between calls
+ if (applyToAllClasses) {
+ // guard every class and method defined in this script
+ source.getAST()?.classes?.each { ClassNode it ->
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitClass(it)
+ }
+ } else if (annotatedNode instanceof ClassNode) {
+ // only guard this particular class
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitClass annotatedNode
+ } else if (!applyToAllMembers && annotatedNode instanceof MethodNode) {
+ // only guard this particular method (plus initCode for class)
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitMethod annotatedNode
+ visitor.visitClass annotatedNode.declaringClass
+ } else if (!applyToAllMembers && annotatedNode instanceof FieldNode) {
+ // only guard this particular field (plus initCode for class)
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitField annotatedNode
+ visitor.visitClass annotatedNode.declaringClass
+ } else if (!applyToAllMembers && annotatedNode instanceof DeclarationExpression) {
+ // only guard this particular declaration (plus initCode for class)
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitDeclarationExpression annotatedNode
+ visitor.visitClass annotatedNode.declaringClass
+ } else {
+ // only guard the script class
+ source.getAST()?.classes?.each { ClassNode it ->
+ if (it.isScript()) {
+ def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
+ visitor.visitClass(it)
+ }
+ }
+ }
+ }
+
+ static def getConstantAnnotationParameter(AnnotationNode node, String parameterName, Class type, defaultValue) {
+ def member = node.getMember(parameterName)
+ if (member) {
+ if (member instanceof ConstantExpression) {
+ // TODO not sure this try offers value - testing Groovy annotation type handing - throw GroovyBugError or remove?
+ try {
+ return member.value.asType(type)
+ } catch (ignore) {
+ internalError("Expecting boolean value for ${parameterName} annotation parameter. Found $member")
+ }
+ } else {
+ internalError("Expecting boolean value for ${parameterName} annotation parameter. Found $member")
+ }
+ }
+ return defaultValue
+ }
+
+ private static void internalError(String message) {
+ throw new RuntimeException("Internal error: $message")
+ }
+
+ private static class TimedInterruptionVisitor extends ClassCodeVisitorSupport {
+ final private SourceUnit source
+ final private boolean checkOnMethodStart
+ final private boolean applyToAllClasses
+ final private boolean applyToAllMembers
+ private FieldNode expireTimeField = null
+ private FieldNode startTimeField = null
+ private final Expression unit
+ private final maximum
+ private final ClassNode thrown
+ private final String basename
+
+ TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, hash) {
+ this.source = source
+ this.checkOnMethodStart = checkOnMethodStart
+ this.applyToAllClasses = applyToAllClasses
+ this.applyToAllMembers = applyToAllMembers
+ this.unit = unit
+ this.maximum = maximum
+ this.thrown = thrown
+ this.basename = 'timedInterrupt' + hash
+ }
+
+ /**
+ * @return Returns the interruption check statement.
+ */
+ final createInterruptStatement() {
+ ifS(
+
+ ltX(
+ propX(varX("this"), basename + '$expireTime'),
+ callX(make(System), 'nanoTime')
+ ),
+ throwS(
+ ctorX(thrown,
+ args(
+ plusX(
+ plusX(
+ constX('Execution timed out after ' + maximum + ' '),
+ callX(callX(unit, 'name'), 'toLowerCase', propX(classX(Locale), 'US'))
+ ),
+ plusX(
+ constX('. Start time: '),
+ propX(varX("this"), basename + '$startTime')
+ )
+ )
+
+ )
+ )
+ )
+ )
+ }
+
+ /**
+ * Takes a statement and wraps it into a block statement which first element is the interruption check statement.
+ * @param statement the statement to be wrapped
+ * @return a {@link BlockStatement block statement} which first element is for checking interruption, and the
+ * second one the statement to be wrapped.
+ */
+ private wrapBlock(statement) {
+ def stmt = new BlockStatement();
+ stmt.addStatement(createInterruptStatement());
+ stmt.addStatement(statement);
+ stmt
+ }
+
+ @Override
+ void visitClass(ClassNode node) {
+ if (node.getDeclaredField(basename + '$expireTime')) {
+ return
+ }
+ expireTimeField = node.addField(basename + '$expireTime',
+ ACC_FINAL | ACC_PRIVATE,
+ ClassHelper.long_TYPE,
+ plusX(
+ callX(make(System), 'nanoTime'),
+ callX(
+ propX(classX(TimeUnit), 'NANOSECONDS'),
+ 'convert',
+ args(constX(maximum, true), unit)
+ )
+ )
+ );
+ expireTimeField.synthetic = true
+ startTimeField = node.addField(basename + '$startTime',
+ ACC_FINAL | ACC_PRIVATE,
+ make(Date),
+ ctorX(make(Date))
+ )
+ startTimeField.synthetic = true
+
+ // force these fields to be initialized first
+ node.fields.remove(expireTimeField)
+ node.fields.remove(startTimeField)
+ node.fields.add(0, startTimeField)
+ node.fields.add(0, expireTimeField)
+ if (applyToAllMembers) {
+ super.visitClass node
+ }
+ }
+
+ @Override
+ void visitClosureExpression(ClosureExpression closureExpr) {
+ def code = closureExpr.code
+ if (code instanceof BlockStatement) {
+ code.statements.add(0, createInterruptStatement())
+ } else {
+ closureExpr.code = wrapBlock(code)
+ }
+ super.visitClosureExpression closureExpr
+ }
+
+ @Override
+ void visitField(FieldNode node) {
+ if (!node.isStatic() && !node.isSynthetic()) {
+ super.visitField node
+ }
+ }
+
+ @Override
+ void visitProperty(PropertyNode node) {
+ if (!node.isStatic() && !node.isSynthetic()) {
+ super.visitProperty node
+ }
+ }
+
+ /**
+ * Shortcut method which avoids duplicating code for every type of loop.
+ * Actually wraps the loopBlock of different types of loop statements.
+ */
+ private visitLoop(loopStatement) {
+ def statement = loopStatement.loopBlock
+ loopStatement.loopBlock = wrapBlock(statement)
+ }
+
+ @Override
+ void visitForLoop(ForStatement forStatement) {
+ visitLoop(forStatement)
+ super.visitForLoop(forStatement)
+ }
+
+ @Override
+ void visitDoWhileLoop(final DoWhileStatement doWhileStatement) {
+ visitLoop(doWhileStatement)
+ super.visitDoWhileLoop(doWhileStatement)
+ }
+
+ @Override
+ void visitWhileLoop(final WhileStatement whileStatement) {
+ visitLoop(whileStatement)
+ super.visitWhileLoop(whileStatement)
+ }
+
+ @Override
+ void visitMethod(MethodNode node) {
+ if (checkOnMethodStart && !node.isSynthetic() && !node.isStatic() && !node.isAbstract()) {
+ def code = node.code
+ node.code = wrapBlock(code);
+ }
+ if (!node.isSynthetic() && !node.isStatic()) {
+ super.visitMethod(node)
+ }
+ }
+
+ protected SourceUnit getSourceUnit() {
+ return source;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java b/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java
new file mode 100644
index 0000000..98e0fe2
--- /dev/null
+++ b/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.ast.tools;
+
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.SpreadExpression;
+import org.codehaus.groovy.ast.expr.TupleExpression;
+
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.codehaus.groovy.ast.ClassHelper.boolean_TYPE;
+
+/**
+ * Utility class for working with ClassNodes
+ */
+public class ClassNodeUtils {
+ /**
+ * Formats a type name into a human readable version. For arrays, appends "[]" to the formatted
+ * type name of the component. For unit class nodes, uses the class node name.
+ *
+ * @param cNode the type to format
+ * @return a human readable version of the type name (java.lang.String[] for example)
+ */
+ public static String formatTypeName(ClassNode cNode) {
+ if (cNode.isArray()) {
+ ClassNode it = cNode;
+ int dim = 0;
+ while (it.isArray()) {
+ dim++;
+ it = it.getComponentType();
+ }
+ StringBuilder sb = new StringBuilder(it.getName().length() + 2 * dim);
+ sb.append(it.getName());
+ for (int i = 0; i < dim; i++) {
+ sb.append("[]");
+ }
+ return sb.toString();
+ }
+ return cNode.getName();
+ }
+
+ /**
+ * Add methods from the super class.
+ *
+ * @param cNode The ClassNode
+ * @return A map of methods
+ */
+ public static Map<String, MethodNode> getDeclaredMethodsFromSuper(ClassNode cNode) {
+ ClassNode parent = cNode.getSuperClass();
+ if (parent == null) {
+ return new HashMap<String, MethodNode>();
+ }
+ return parent.getDeclaredMethodsMap();
+ }
+
+ /**
+ * Add in methods from all interfaces. Existing entries in the methods map take precedence.
+ * Methods from interfaces visited early take precedence over later ones.
+ *
+ * @param cNode The ClassNode
+ * @param methodsMap A map of existing methods to alter
+ */
+ public static void addDeclaredMethodsFromInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) {
+ // add in unimplemented abstract methods from the interfaces
+ for (ClassNode iface : cNode.getInterfaces()) {
+ Map<String, MethodNode> ifaceMethodsMap = iface.getDeclaredMethodsMap();
+ for (Map.Entry<String, MethodNode> entry : ifaceMethodsMap.entrySet()) {
+ String methSig = entry.getKey();
+ if (!methodsMap.containsKey(methSig)) {
+ methodsMap.put(methSig, entry.getValue());
+ }
+ }
+ }
+ }
+
+ /**
+ * Get methods from all interfaces.
+ * Methods from interfaces visited early will be overwritten by later ones.
+ *
+ * @param cNode The ClassNode
+ * @return A map of methods
+ */
+ public static Map<String, MethodNode> getDeclaredMethodsFromInterfaces(ClassNode cNode) {
+ Map<String, MethodNode> result = new HashMap<String, MethodNode>();
+ ClassNode[] interfaces = cNode.getInterfaces();
+ for (ClassNode iface : interfaces) {
+ result.putAll(iface.getDeclaredMethodsMap());
+ }
+ return result;
+ }
+
+ /**
+ * Adds methods from interfaces and parent interfaces. Existing entries in the methods map take precedence.
+ * Methods from interfaces visited early take precedence over later ones.
+ *
+ * @param cNode The ClassNode
+ * @param methodsMap A map of existing methods to alter
+ */
+ public static void addDeclaredMethodsFromAllInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) {
+ List cnInterfaces = Arrays.asList(cNode.getInterfaces());
+ ClassNode parent = cNode.getSuperClass();
+ while (parent != null && !parent.equals(ClassHelper.OBJECT_TYPE)) {
+ ClassNode[] interfaces = parent.getInterfaces();
+ for (ClassNode iface : interfaces) {
+ if (!cnInterfaces.contains(iface)) {
+ methodsMap.putAll(iface.getDeclaredMethodsMap());
+ }
+ }
+ parent = parent.getSuperClass();
+ }
+ }
+
+ /**
+ * Returns true if the given method has a possibly matching static method with the given name and arguments.
+ * Handles default arguments and optionally spread expressions.
+ *
+ * @param cNode the ClassNode of interest
+ * @param name the name of the method of interest
+ * @param arguments the arguments to match against
+ * @param trySpread whether to try to account for SpreadExpressions within the arguments
+ * @return true if a matching method was found
+ */
+ public static boolean hasPossibleStaticMethod(ClassNode cNode, String name, Expression arguments, boolean trySpread) {
+ int count = 0;
+ boolean foundSpread = false;
+
+ if (arguments instanceof TupleExpression) {
+ TupleExpression tuple = (TupleExpression) arguments;
+ for (Expression arg : tuple.getExpressions()) {
+ if (arg instanceof SpreadExpression) {
+ foundSpread = true;
+ } else {
+ count++;
+ }
+ }
+ } else if (arguments instanceof MapExpression) {
+ count = 1;
+ }
+
+ for (MethodNode method : cNode.getMethods(name)) {
+ if (method.isStatic()) {
+ Parameter[] parameters = method.getParameters();
+ // do fuzzy match for spread case: count will be number of non-spread args
+ if (trySpread && foundSpread && parameters.length >= count) return true;
+
+ if (parameters.length == count) return true;
+
+ // handle varargs case
+ if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) {
+ if (count >= parameters.length - 1) return true;
+ // fuzzy match any spread to a varargs
+ if (trySpread && foundSpread) return true;
+ }
+
+ // handle parameters with default values
+ int nonDefaultParameters = 0;
+ for (Parameter parameter : parameters) {
+ if (!parameter.hasInitialExpression()) {
+ nonDefaultParameters++;
+ }
+ }
+
+ if (count < parameters.length && nonDefaultParameters <= count) {
+ return true;
+ }
+ // TODO handle spread with nonDefaultParams?
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return true if we have a static accessor
+ */
+ public static boolean hasPossibleStaticProperty(ClassNode cNode, String methodName) {
+ // assume explicit static method call checked first so we can assume a simple check here
+ if (!methodName.startsWith("get") && !methodName.startsWith("is")) {
+ return false;
+ }
+ String propName = getPropNameForAccessor(methodName);
+ PropertyNode pNode = getStaticProperty(cNode, propName);
+ return pNode != null && (methodName.startsWith("get") || boolean_TYPE.equals(pNode.getType()));
+ }
+
+ /**
+ * Returns the property name, e.g. age, given an accessor name, e.g. getAge.
+ * Returns the original if a valid prefix cannot be removed.
+ *
+ * @param accessorName the accessor name of interest, e.g. getAge
+ * @return the property name, e.g. age, or original if not a valid property accessor name
+ */
+ public static String getPropNameForAccessor(String accessorName) {
+ if (!isValidAccessorName(accessorName)) return accessorName;
+ int prefixLength = accessorName.startsWith("is") ? 2 : 3;
+ return String.valueOf(accessorName.charAt(prefixLength)).toLowerCase() + accessorName.substring(prefixLength + 1);
+ }
+
+ /**
+ * Detect whether the given accessor name starts with "get", "set" or "is" followed by at least one character.
+ *
+ * @param accessorName the accessor name of interest, e.g. getAge
+ * @return true if a valid prefix is found
+ */
+ public static boolean isValidAccessorName(String accessorName) {
+ if (accessorName.startsWith("get") || accessorName.startsWith("is") || accessorName.startsWith("set")) {
+ int prefixLength = accessorName.startsWith("is") ? 2 : 3;
+ return accessorName.length() > prefixLength;
+ };
+ return false;
+ }
+
+ public static boolean hasStaticProperty(ClassNode cNode, String propName) {
+ return getStaticProperty(cNode, propName) != null;
+ }
+
+ /**
+ * Detect whether a static property with the given name is within the class
+ * or a super class.
+ *
+ * @param cNode the ClassNode of interest
+ * @param propName the property name
+ * @return the static property if found or else null
+ */
+ public static PropertyNode getStaticProperty(ClassNode cNode, String propName) {
+ ClassNode classNode = cNode;
+ while (classNode != null) {
+ for (PropertyNode pn : classNode.getProperties()) {
+ if (pn.getName().equals(propName) && pn.isStatic()) return pn;
+ }
+ classNode = classNode.getSuperClass();
+ }
+ return null;
+ }
+
+ /**
+ * Detect whether a given ClassNode is a inner class (non-static).
+ *
+ * @param cNode the ClassNode of interest
+ * @return true if the given node is a (non-static) inner class, else false
+ */
+ public static boolean isInnerClass(ClassNode cNode) {
+ return cNode.redirect().getOuterClass() != null
+ && !Modifier.isStatic(cNode.getModifiers());
+ }
+
+ private ClassNodeUtils() { }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/ast/tools/MethodNodeUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/ast/tools/MethodNodeUtils.java b/src/main/java/org/apache/groovy/ast/tools/MethodNodeUtils.java
new file mode 100644
index 0000000..94427f0
--- /dev/null
+++ b/src/main/java/org/apache/groovy/ast/tools/MethodNodeUtils.java
@@ -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 org.apache.groovy.ast.tools;
+
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+
+/**
+ * Utility class for working with MethodNodes
+ */
+public class MethodNodeUtils {
+ /**
+ * Return the method node's descriptor including its
+ * name and parameter types without generics.
+ *
+ * @param mNode the method node
+ * @return the method node's abbreviated descriptor excluding the return type
+ */
+ public static String methodDescriptorWithoutReturnType(MethodNode mNode) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(mNode.getName()).append(':');
+ for (Parameter p : mNode.getParameters()) {
+ sb.append(ClassNodeUtils.formatTypeName(p.getType())).append(',');
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Return the method node's descriptor which includes its return type,
+ * name and parameter types without generics.
+ *
+ * @param mNode the method node
+ * @return the method node's descriptor
+ */
+ public static String methodDescriptor(MethodNode mNode) {
+ StringBuilder sb = new StringBuilder(mNode.getName().length() + mNode.getParameters().length * 10);
+ sb.append(mNode.getReturnType().getName());
+ sb.append(' ');
+ sb.append(mNode.getName());
+ sb.append('(');
+ for (int i = 0; i < mNode.getParameters().length; i++) {
+ if (i > 0) {
+ sb.append(", ");
+ }
+ Parameter p = mNode.getParameters()[i];
+ sb.append(ClassNodeUtils.formatTypeName(p.getType()));
+ }
+ sb.append(')');
+ return sb.toString();
+ }
+
+ private MethodNodeUtils() { }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/internal/metaclass/MetaClassConstant.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/internal/metaclass/MetaClassConstant.java b/src/main/java/org/apache/groovy/internal/metaclass/MetaClassConstant.java
new file mode 100644
index 0000000..df5a7ec
--- /dev/null
+++ b/src/main/java/org/apache/groovy/internal/metaclass/MetaClassConstant.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.internal.metaclass;
+
+import groovy.lang.MetaClassImpl;
+import groovy.lang.MetaMethod;
+import org.apache.groovy.lang.annotation.Incubating;
+
+import java.lang.invoke.SwitchPoint;
+
+/**
+ * The one and only implementation of a meta class.
+ * INTERNAL USE ONLY.
+ */
+@Incubating
+public final class MetaClassConstant<T> {
+ private final SwitchPoint switchPoint = new SwitchPoint();
+ //TODO Joche: replace with real implementation
+ private final MetaClassImpl impl;
+
+ public MetaClassConstant(Class<T> clazz) {
+ impl = new MetaClassImpl(clazz);
+ }
+
+ public SwitchPoint getSwitchPoint() {
+ return switchPoint;
+ }
+
+ // TODO Jochen: replace with new MetaMethod
+ public MetaMethod getMethod(String name, Class[] parameters) {
+ return impl.pickMethod(name, parameters);
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/internal/util/Function.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/internal/util/Function.java b/src/main/java/org/apache/groovy/internal/util/Function.java
new file mode 100644
index 0000000..3a4fea5
--- /dev/null
+++ b/src/main/java/org/apache/groovy/internal/util/Function.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.internal.util;
+
+import org.apache.groovy.lang.annotation.Incubating;
+
+/**
+ * Backport of Java8 Function.
+ * INTERNAL USE ONLY.
+ */
+@Incubating
+public interface Function<T, R> {
+ R apply(T t);
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/internal/util/ReevaluatingReference.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/internal/util/ReevaluatingReference.java b/src/main/java/org/apache/groovy/internal/util/ReevaluatingReference.java
new file mode 100644
index 0000000..feeeea8
--- /dev/null
+++ b/src/main/java/org/apache/groovy/internal/util/ReevaluatingReference.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.internal.util;
+
+import org.apache.groovy.lang.annotation.Incubating;
+import org.codehaus.groovy.GroovyBugError;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.invoke.SwitchPoint;
+import java.lang.ref.WeakReference;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * This class represents a reference to the most actual incarnation of a Metaclass.
+ * INTERNAL USE ONLY.
+ */
+@Incubating
+public class ReevaluatingReference<T> {
+ private static final MethodHandle FALLBACK_HANDLE;
+ static {
+ try {
+ //TODO Jochen: move the findSpecial to a central place together with others to easy security configuration
+ FALLBACK_HANDLE = AccessController.doPrivileged(new PrivilegedExceptionAction<MethodHandle>() {
+ @Override
+ public MethodHandle run() throws Exception {
+ return MethodHandles.lookup().findSpecial(
+ ReevaluatingReference.class, "replacePayLoad",
+ MethodType.methodType(Object.class),
+ ReevaluatingReference.class);
+ }
+ });
+ } catch (PrivilegedActionException e) {
+ throw new GroovyBugError(e);
+ }
+ }
+
+ private final Supplier<T> valueSupplier;
+ private final Function<T, SwitchPoint> validationSupplier;
+ private final WeakReference<Class<T>> clazzRef;
+ private MethodHandle returnRef;
+
+
+ public ReevaluatingReference(Class clazz, Supplier<T> valueSupplier, Function<T, SwitchPoint> validationSupplier) {
+ this.valueSupplier = valueSupplier;
+ this.validationSupplier = validationSupplier;
+ clazzRef = new WeakReference<Class<T>>(clazz);
+ replacePayLoad();
+ }
+
+ private T replacePayLoad() {
+ T payload = valueSupplier.get();
+ MethodHandle ref = MethodHandles.constant(clazzRef.get(), payload);
+ SwitchPoint sp = validationSupplier.apply(payload);
+ returnRef = sp.guardWithTest(ref, FALLBACK_HANDLE);
+ return payload;
+ }
+
+ public T getPayload() {
+ T ref = null;
+ try {
+ ref = (T) returnRef.invokeExact();
+ } catch (Throwable throwable) {
+ UncheckedThrow.rethrow(throwable);
+ }
+ return ref;
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/internal/util/Supplier.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/internal/util/Supplier.java b/src/main/java/org/apache/groovy/internal/util/Supplier.java
new file mode 100644
index 0000000..3a01785
--- /dev/null
+++ b/src/main/java/org/apache/groovy/internal/util/Supplier.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.internal.util;
+
+import org.apache.groovy.lang.annotation.Incubating;
+
+/**
+ * Backport of Java8 Supplier.
+ * INTERNAL USE ONLY.
+ */
+@Incubating
+public interface Supplier<T> {
+ T get();
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/internal/util/UncheckedThrow.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/internal/util/UncheckedThrow.java b/src/main/java/org/apache/groovy/internal/util/UncheckedThrow.java
new file mode 100644
index 0000000..7f6cc8a
--- /dev/null
+++ b/src/main/java/org/apache/groovy/internal/util/UncheckedThrow.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.internal.util;
+
+import org.apache.groovy.lang.annotation.Incubating;
+
+/**
+ * Allows to throw a checked exception unchecked.
+ * INTERNAL USE ONLY.
+ */
+@Incubating
+public class UncheckedThrow {
+ public static void rethrow( final Throwable checkedException ) {
+ UncheckedThrow.<RuntimeException>thrownInsteadOf( checkedException );
+ }
+ @SuppressWarnings("unchecked")
+ private static <T extends Throwable> void thrownInsteadOf(Throwable t) throws T {
+ throw (T) t;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/lang/annotation/Incubating.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/lang/annotation/Incubating.java b/src/main/java/org/apache/groovy/lang/annotation/Incubating.java
new file mode 100644
index 0000000..d6964f8
--- /dev/null
+++ b/src/main/java/org/apache/groovy/lang/annotation/Incubating.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.lang.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Annotation to indicate experimental and still to be refined API, which may change at any time
+ */
+@Incubating
+@Documented
+@Retention(value=RUNTIME)
+@Target(value={TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, ANNOTATION_TYPE, PACKAGE})
+public @interface Incubating {
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/metaclass/MetaClass.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/metaclass/MetaClass.java b/src/main/java/org/apache/groovy/metaclass/MetaClass.java
new file mode 100644
index 0000000..6ebe4fc
--- /dev/null
+++ b/src/main/java/org/apache/groovy/metaclass/MetaClass.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.metaclass;
+
+import groovy.lang.MetaMethod;
+import org.apache.groovy.internal.metaclass.MetaClassConstant;
+import org.apache.groovy.internal.util.ReevaluatingReference;
+import org.apache.groovy.lang.annotation.Incubating;
+
+/**
+ * A MetaClass within Groovy defines the behaviour of any given Groovy or Java class
+ */
+@Incubating
+public final class MetaClass<T> {
+ private final ReevaluatingReference<MetaClassConstant<T>> implRef;
+
+ MetaClass(ReevaluatingReference<MetaClassConstant<T>> implRef) {
+ this.implRef = implRef;
+ }
+
+ public MetaMethod getMethod(String name, Class[] parameters) {
+ return implRef.getPayload().getMethod(name, parameters);
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/metaclass/Realm.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/metaclass/Realm.java b/src/main/java/org/apache/groovy/metaclass/Realm.java
new file mode 100644
index 0000000..a652dab
--- /dev/null
+++ b/src/main/java/org/apache/groovy/metaclass/Realm.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.groovy.metaclass;
+
+import org.apache.groovy.internal.metaclass.MetaClassConstant;
+import org.apache.groovy.internal.util.Function;
+import org.apache.groovy.internal.util.ReevaluatingReference;
+import org.apache.groovy.internal.util.Supplier;
+import org.apache.groovy.lang.annotation.Incubating;
+
+import java.lang.invoke.SwitchPoint;
+import java.util.Objects;
+
+/**
+ * A Realm is the representation of a metaclass layer in a tree of realm objects.
+ */
+@Incubating
+public final class Realm {
+ private static final Realm ROOT = new Realm("ROOT", null);
+
+ private final String name;
+ private final Realm parent;
+ private final ClassValue<MetaClassConstant<?>> cv = new ClassValue<MetaClassConstant<?>>() {
+ @Override
+ @SuppressWarnings("unchecked")
+ protected MetaClassConstant<?> computeValue(Class<?> type) {
+ return new MetaClassConstant(type);
+ }
+ };
+
+ private Realm(String name, Realm parent) {
+ this.name = name;
+ this.parent = parent;
+ }
+
+ public static Realm newRealm(String name, Realm parent) {
+ Objects.requireNonNull(name, "missing realm name");
+ if (parent == null) {
+ return new Realm(name, ROOT);
+ } else {
+ return new Realm(name, parent);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "Realm{" +
+ "name='" + name + '\'' +
+ ", parent=" + parent +
+ '}';
+ }
+
+ public <T> MetaClass<T> getMetaClass(final Class<T> theClass) {
+ Supplier<MetaClassConstant<T>> valueSupplier = new Supplier<MetaClassConstant<T>>() {
+ @Override
+ @SuppressWarnings("unchecked")
+ public MetaClassConstant<T> get() {
+ return (MetaClassConstant<T>) cv.get(theClass);
+ }
+ };
+ Function<MetaClassConstant<T>, SwitchPoint> validationSupplier = new Function<MetaClassConstant<T>, SwitchPoint>() {
+ @Override
+ public SwitchPoint apply(MetaClassConstant<T> metaClassImpl) {
+ return metaClassImpl.getSwitchPoint();
+ }
+ };
+ ReevaluatingReference<MetaClassConstant<T>> ref = new ReevaluatingReference<>(
+ MetaClassConstant.class,
+ valueSupplier,
+ validationSupplier
+ );
+ return new MetaClass<>(ref);
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/plugin/DefaultRunners.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/plugin/DefaultRunners.java b/src/main/java/org/apache/groovy/plugin/DefaultRunners.java
new file mode 100644
index 0000000..5f570eb
--- /dev/null
+++ b/src/main/java/org/apache/groovy/plugin/DefaultRunners.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.plugin;
+
+import groovy.lang.GroovyClassLoader;
+import groovy.lang.GroovyRuntimeException;
+import org.codehaus.groovy.runtime.InvokerHelper;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.List;
+
+/**
+ * Provides access to built-in {@link GroovyRunner} instances
+ * for the registry. These instances should be accessed via
+ * the registry and not used directly.
+ */
+final class DefaultRunners {
+
+ /*
+ * These runners were originally included directly in GroovyShell.
+ * Since they are part of core they are added directly to the
+ * GroovyRunnerRegistry rather than via a provider configuration
+ * file in META-INF/services. If any of these runners are moved
+ * out to a submodule then they should be registered using the
+ * provider configuration file (see groovy-testng).
+ *
+ * These are internal classes and not meant to be referenced
+ * outside of the GroovyRunnerRegistry.
+ */
+
+ private static final GroovyRunner JUNIT3_TEST = new Junit3TestRunner();
+ private static final GroovyRunner JUNIT3_SUITE = new Junit3SuiteRunner();
+ private static final GroovyRunner JUNIT4_TEST = new Junit4TestRunner();
+
+ private DefaultRunners() {
+ }
+
+ static GroovyRunner junit3TestRunner() {
+ return JUNIT3_TEST;
+ }
+
+ static GroovyRunner junit3SuiteRunner() {
+ return JUNIT3_SUITE;
+ }
+
+ static GroovyRunner junit4TestRunner() {
+ return JUNIT4_TEST;
+ }
+
+ private static class Junit3TestRunner implements GroovyRunner {
+ /**
+ * Utility method to check through reflection if the class appears to be a
+ * JUnit 3.8.x test, i.e. checks if it extends JUnit 3.8.x's TestCase.
+ *
+ * @param scriptClass the class we want to check
+ * @param loader the class loader
+ * @return true if the class appears to be a test
+ */
+ @Override
+ public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) {
+ try {
+ Class<?> testCaseClass = loader.loadClass("junit.framework.TestCase");
+ return testCaseClass.isAssignableFrom(scriptClass);
+ } catch (Throwable e) {
+ return false;
+ }
+ }
+
+ /**
+ * Run the specified class extending TestCase as a unit test.
+ * This is done through reflection, to avoid adding a dependency to the JUnit framework.
+ * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
+ * groovy scripts and classes would have to add another dependency on their classpath.
+ *
+ * @param scriptClass the class to be run as a unit test
+ * @param loader the class loader
+ */
+ @Override
+ public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
+ try {
+ Object testSuite = InvokerHelper.invokeConstructorOf("junit.framework.TestSuite", new Object[]{scriptClass});
+ return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite});
+ } catch (ClassNotFoundException e) {
+ throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e);
+ }
+ }
+ }
+
+ private static class Junit3SuiteRunner implements GroovyRunner {
+ /**
+ * Utility method to check through reflection if the class appears to be a
+ * JUnit 3.8.x test suite, i.e. checks if it extends JUnit 3.8.x's TestSuite.
+ *
+ * @param scriptClass the class we want to check
+ * @param loader the class loader
+ * @return true if the class appears to be a test
+ */
+ @Override
+ public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) {
+ try {
+ Class<?> testSuiteClass = loader.loadClass("junit.framework.TestSuite");
+ return testSuiteClass.isAssignableFrom(scriptClass);
+ } catch (Throwable e) {
+ return false;
+ }
+ }
+
+ /**
+ * Run the specified class extending TestSuite as a unit test.
+ * This is done through reflection, to avoid adding a dependency to the JUnit framework.
+ * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
+ * groovy scripts and classes would have to add another dependency on their classpath.
+ *
+ * @param scriptClass the class to be run as a unit test
+ * @param loader the class loader
+ */
+ @Override
+ public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
+ try {
+ Object testSuite = InvokerHelper.invokeStaticMethod(scriptClass, "suite", new Object[]{});
+ return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite});
+ } catch (ClassNotFoundException e) {
+ throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e);
+ }
+ }
+ }
+
+ private static class Junit4TestRunner implements GroovyRunner {
+ /**
+ * Utility method to check via reflection if the parsed class appears to be a JUnit4
+ * test, i.e. checks whether it appears to be using the relevant JUnit 4 annotations.
+ *
+ * @param scriptClass the class we want to check
+ * @param loader the class loader
+ * @return true if the class appears to be a test
+ */
+ @Override
+ public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) {
+ return hasRunWithAnnotation(scriptClass, loader)
+ || hasTestAnnotatedMethod(scriptClass, loader);
+ }
+
+ /**
+ * Run the specified class extending TestCase as a unit test.
+ * This is done through reflection, to avoid adding a dependency to the JUnit framework.
+ * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
+ * groovy scripts and classes would have to add another dependency on their classpath.
+ *
+ * @param scriptClass the class to be run as a unit test
+ * @param loader the class loader
+ */
+ @Override
+ public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
+ try {
+ Class<?> junitCoreClass = loader.loadClass("org.junit.runner.JUnitCore");
+ Object result = InvokerHelper.invokeStaticMethod(junitCoreClass,
+ "runClasses", new Object[]{scriptClass});
+ System.out.print("JUnit 4 Runner, Tests: " + InvokerHelper.getProperty(result, "runCount"));
+ System.out.print(", Failures: " + InvokerHelper.getProperty(result, "failureCount"));
+ System.out.println(", Time: " + InvokerHelper.getProperty(result, "runTime"));
+ List<?> failures = (List<?>) InvokerHelper.getProperty(result, "failures");
+ for (Object f : failures) {
+ System.out.println("Test Failure: " + InvokerHelper.getProperty(f, "description"));
+ System.out.println(InvokerHelper.getProperty(f, "trace"));
+ }
+ return result;
+ } catch (ClassNotFoundException e) {
+ throw new GroovyRuntimeException("Error running JUnit 4 test.", e);
+ }
+ }
+
+ private static boolean hasRunWithAnnotation(Class<?> scriptClass, ClassLoader loader) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<? extends Annotation> runWithAnnotationClass =
+ (Class<? extends Annotation>)loader.loadClass("org.junit.runner.RunWith");
+ return scriptClass.isAnnotationPresent(runWithAnnotationClass);
+ } catch (Throwable e) {
+ return false;
+ }
+ }
+
+ private static boolean hasTestAnnotatedMethod(Class<?> scriptClass, ClassLoader loader) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<? extends Annotation> testAnnotationClass =
+ (Class<? extends Annotation>) loader.loadClass("org.junit.Test");
+ Method[] methods = scriptClass.getMethods();
+ for (Method method : methods) {
+ if (method.isAnnotationPresent(testAnnotationClass)) {
+ return true;
+ }
+ }
+ } catch (Throwable e) {
+ // fall through
+ }
+ return false;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/b25d0e55/src/main/java/org/apache/groovy/plugin/GroovyRunner.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/plugin/GroovyRunner.java b/src/main/java/org/apache/groovy/plugin/GroovyRunner.java
new file mode 100644
index 0000000..283d092
--- /dev/null
+++ b/src/main/java/org/apache/groovy/plugin/GroovyRunner.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.plugin;
+
+import groovy.lang.GroovyClassLoader;
+
+/**
+ * Classes which can run scripts should implement this interface.
+ *
+ * @since 2.5.0
+ */
+public interface GroovyRunner {
+
+ /**
+ * Returns {@code true} if this runner is able to
+ * run the given class.
+ *
+ * @param scriptClass class to run
+ * @param loader used to locate classes and resources
+ * @return true if given class can be run, else false
+ */
+ boolean canRun(Class<?> scriptClass, GroovyClassLoader loader);
+
+ /**
+ * Runs the given class.
+ *
+ * @param scriptClass class to run
+ * @param loader used to locate classes and resources
+ * @return result of running the class
+ */
+ Object run(Class<?> scriptClass, GroovyClassLoader loader);
+
+}