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 2015/10/07 21:26:21 UTC

[01/37] incubator-groovy git commit: new groovy-macro subproject with code from MacroGroovy (initial contribution)

Repository: incubator-groovy
Updated Branches:
  refs/heads/master baba6dfdf -> c289ed419


new groovy-macro subproject with code from MacroGroovy (initial contribution)


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/0b5f0b03
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/0b5f0b03
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/0b5f0b03

Branch: refs/heads/master
Commit: 0b5f0b03d39c10bb7071dd0eedaacc2157cdd6c0
Parents: f069c18
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 00:46:13 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:31:50 2015 +0300

----------------------------------------------------------------------
 settings.gradle                                 |   3 +-
 subprojects/groovy-macro/build.gradle           |  11 +
 .../groovy/macro/runtime/MacroBuilder.java      |  97 ++++++++
 .../macro/runtime/MacroGroovyMethods.java       |  41 ++++
 .../macro/runtime/MacroSubstitutionKey.java     |  96 ++++++++
 .../macro/transform/MacroInvocationTrap.java    | 233 +++++++++++++++++++
 .../macro/transform/MacroTransformation.java    |  70 ++++++
 ....codehaus.groovy.transform.ASTTransformation |   2 +
 .../test/groovy/groovy/SimpleMacroTest.groovy   |  90 +++++++
 9 files changed, 642 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/settings.gradle
----------------------------------------------------------------------
diff --git a/settings.gradle b/settings.gradle
index eccf7e8..230d0ff 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -31,7 +31,8 @@ def subprojects = ['groovy-ant',
         'groovy-templates',
         'groovy-test',
         'groovy-testng',
-        'groovy-xml'
+        'groovy-xml',
+        'groovy-macro'
 ]
 
 if(JavaVersion.current().isJava7Compatible()) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/build.gradle
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/build.gradle b/subprojects/groovy-macro/build.gradle
new file mode 100644
index 0000000..2af7b10
--- /dev/null
+++ b/subprojects/groovy-macro/build.gradle
@@ -0,0 +1,11 @@
+dependencies {
+    compile rootProject
+    testCompile rootProject.sourceSets.test.runtimeClasspath
+    testCompile project(':groovy-test')
+}
+
+task moduleDescriptor(type: org.codehaus.groovy.gradle.WriteExtensionDescriptorTask) {
+    extensionClasses = 'org.codehaus.groovy.macro.runtime.MacroGroovyMethods'
+}
+
+compileJava.dependsOn moduleDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
new file mode 100644
index 0000000..2c66f3e
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import groovy.lang.Closure;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.builder.AstBuilder;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.macro.transform.MacroInvocationTrap;
+import org.codehaus.groovy.macro.transform.MacroTransformation;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public enum MacroBuilder {
+    INSTANCE;
+
+    @SuppressWarnings("unchecked")
+    public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
+        final String labelledSource = label + source;
+        final int linesOffset = 1;
+        final int columnsOffset = label.length() + 1; // +1 because of {
+        
+        List<ASTNode> nodes = (new AstBuilder()).buildFromString(CompilePhase.CONVERSION, true, labelledSource);
+
+        for(ASTNode node : nodes) {
+            if (node instanceof BlockStatement) {
+
+                BlockStatement closureBlock = (BlockStatement) ((BlockStatement)node).getStatements().get(0);
+
+                (new ClassCodeExpressionTransformer() {
+                    public Expression transform(Expression expression) {
+                        if(!(expression instanceof MethodCallExpression)) {
+                            return super.transform(expression);
+                        }
+
+                        MethodCallExpression call = (MethodCallExpression) expression;
+
+                        if(!MacroInvocationTrap.isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                            return super.transform(expression);
+                        }
+
+                        MacroSubstitutionKey key = new MacroSubstitutionKey(call, linesOffset, columnsOffset);
+                        
+                        return context.get(key).call();
+                    }
+
+                    @Override
+                    protected SourceUnit getSourceUnit() {
+                        // Could be null if there are no errors
+                        return null;
+                    }
+                }).visitBlockStatement(closureBlock);
+
+                return (T) getMacroValue(closureBlock, asIs);
+            }
+        }
+        return null;
+    }
+
+    public static ASTNode getMacroValue(BlockStatement closureBlock, boolean asIs) {
+        if(!asIs && closureBlock.getStatements().size() == 1) {
+            Statement result = closureBlock.getStatements().get(0);
+            if(result instanceof ExpressionStatement) {
+                return ((ExpressionStatement) result).getExpression();
+            } else {
+                return result;
+            }
+        }
+        return closureBlock;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
new file mode 100644
index 0000000..578a11f
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import groovy.lang.Closure;
+import groovy.lang.DelegatesTo;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroGroovyMethods {
+
+    public static class MacroValuePlaceholder {
+        public static Object $v(Closure cl) {
+            // replaced with AST transformations
+            return null; 
+        }
+    }
+
+    public static <T> T macro(Object self, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
new file mode 100644
index 0000000..e895867
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroSubstitutionKey {
+
+    private int startLine;
+    private int startColumn;
+    private int endLine;
+    private int endColumn;
+
+    public MacroSubstitutionKey(int startLine, int startColumn, int endLine, int endColumn) {
+        this.startLine = startLine;
+        this.startColumn = startColumn;
+        this.endLine = endLine;
+        this.endColumn = endColumn;
+    }
+    
+    public MacroSubstitutionKey(Expression expression, int linesOffset, int columnsOffset) {
+        this(
+                expression.getLineNumber() - linesOffset,
+                expression.getColumnNumber() - (expression.getLineNumber() == linesOffset ? columnsOffset : 0),
+                expression.getLastLineNumber() - linesOffset,
+                expression.getLastColumnNumber() - (expression.getLastLineNumber() == linesOffset ? columnsOffset : 0)
+        );
+    }
+    
+    public ConstructorCallExpression toConstructorCallExpression() {
+        return new ConstructorCallExpression(
+                ClassHelper.make(this.getClass()),
+                new ArgumentListExpression(new Expression[] {
+                        new ConstantExpression(startLine),
+                        new ConstantExpression(startColumn),
+                        new ConstantExpression(endLine),
+                        new ConstantExpression(endColumn)
+                })
+        );
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        MacroSubstitutionKey that = (MacroSubstitutionKey) o;
+
+        if (endColumn != that.endColumn) return false;
+        if (endLine != that.endLine) return false;
+        if (startColumn != that.startColumn) return false;
+        if (startLine != that.startLine) return false;
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = startLine;
+        result = 31 * result + startColumn;
+        result = 31 * result + endLine;
+        result = 31 * result + endColumn;
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "SubstitutionKey{" +
+                "startLine=" + startLine +
+                ", startColumn=" + startColumn +
+                ", endLine=" + endLine +
+                ", endColumn=" + endColumn +
+                '}';
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
new file mode 100644
index 0000000..7ac10df
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
+
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.CodeVisitorSupport;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.tools.ClosureUtils;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.control.io.ReaderSource;
+import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
+import org.codehaus.groovy.macro.runtime.MacroBuilder;
+import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
+import org.codehaus.groovy.syntax.SyntaxException;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroInvocationTrap {
+
+    private final ReaderSource source;
+    private final SourceUnit sourceUnit;
+
+    /**
+     * Creates the trap and captures all macro method calls.
+     *
+     * @param source         the reader source that contains source for the SourceUnit
+     * @param sourceUnit     the source unit being compiled. Used for error messages.
+     */
+    MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        if (source == null) throw new IllegalArgumentException("Null: source");
+        if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
+        this.source = source;
+        this.sourceUnit = sourceUnit;
+    }
+
+    /**
+     * Reports an error back to the source unit.
+     *
+     * @param msg  the error message
+     * @param expr the expression that caused the error message.
+     */
+    private void addError(String msg, ASTNode expr) {
+        sourceUnit.getErrorCollector().addErrorAndContinue(
+                new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
+        );
+    }
+
+    /**
+     * Attempts to find 'macro' invocations. When found, converts them into calls
+     * to the 'from string' approach.
+     *
+     * @param macroCall the method call expression that may or may not be a 'macro' invocation.
+     */
+    public void visitMethodCallExpression(final MethodCallExpression macroCall) {
+
+        if (!isBuildInvocation(macroCall, MacroTransformation.MACRO_METHOD)) {
+            return;
+        }
+
+        final ClosureExpression closureExpression = getClosureArgument(macroCall);
+        
+        if(closureExpression == null) {
+            return;
+        }
+
+        if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
+            addError("Macro closure arguments are not allowed", closureExpression);
+        }
+        
+        final MapExpression mapExpression = new MapExpression();
+        
+        (new CodeVisitorSupport() {
+            @Override
+            public void visitMethodCallExpression(MethodCallExpression call) {
+                super.visitMethodCallExpression(call);
+                
+                if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                    ClosureExpression substitutionClosureExpression = getClosureArgument(call);
+                    
+                    if(substitutionClosureExpression == null) {
+                        return;
+                    }
+
+                    MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
+                    
+                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
+                }
+            }
+        }).visitClosureExpression(closureExpression);
+        
+        String source = convertClosureToSource(this.source, closureExpression);
+
+        BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
+        
+        Boolean asIs = false;
+        
+        TupleExpression macroArguments = getMacroArguments(macroCall);
+        
+        if(macroArguments == null) {
+            return;
+        }
+
+        List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
+        
+        if(macroArgumentsExpressions.size() > 1) {
+            Expression firstArgument = macroArgumentsExpressions.get(0);
+            
+            if(!(firstArgument instanceof ConstantExpression)) {
+                addError("AsIs argument value should be constant(true or false)", firstArgument);
+                return;
+            }
+            
+            ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
+            
+            if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                addError("AsIs argument value should be boolean", asIsConstantExpression);
+                return;
+            }
+
+            asIs = (Boolean) asIsConstantExpression.getValue();
+        }
+
+        List<Expression> otherArgs = new ArrayList<Expression>();
+        otherArgs.add(new ConstantExpression(asIs));
+        otherArgs.add(new ConstantExpression(source));
+        otherArgs.add(mapExpression);
+        otherArgs.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
+
+        macroCall.setArguments(new ArgumentListExpression(otherArgs));
+        macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
+        macroCall.setSpreadSafe(false);
+        macroCall.setSafe(false);
+        macroCall.setImplicitThis(false);
+    }
+    
+    protected TupleExpression getMacroArguments(MethodCallExpression call) {
+        Expression macroCallArguments = call.getArguments();
+        if (macroCallArguments == null) {
+            addError("Call should have arguments", call);
+            return null;
+        }
+
+        if(!(macroCallArguments instanceof TupleExpression)) {
+            addError("Call should have TupleExpression as arguments", macroCallArguments);
+            return null;
+        }
+
+        TupleExpression tupleArguments = (TupleExpression) macroCallArguments;
+
+        if (tupleArguments.getExpressions() == null) {
+            addError("Call arguments should have expressions", tupleArguments);
+            return null;
+        }
+        
+        return tupleArguments;
+    }
+    
+    protected ClosureExpression getClosureArgument(MethodCallExpression call) {
+        TupleExpression tupleArguments = getMacroArguments(call);
+
+        if(tupleArguments.getExpressions().size() < 1) {
+            addError("Call arguments should have at least one argument", tupleArguments);
+            return null;
+        }
+
+        Expression result = tupleArguments.getExpression(tupleArguments.getExpressions().size() - 1);
+        if (!(result instanceof ClosureExpression)) {
+            addError("Last call argument should be a closure", result);
+            return null;
+        }
+
+        return (ClosureExpression) result;
+    }
+
+    /**
+     * Looks for 'macro' method calls.
+     *
+     * @param call the method call expression, may not be null
+     */
+    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
+        if (call == null) throw new IllegalArgumentException("Null: call");
+        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+        
+        if(!(call.getMethod() instanceof ConstantExpression)) {
+            return false;
+        }
+        
+        if(!(methodName.equals(call.getMethodAsString()))) {
+            return false;
+        }
+
+        // is method object correct type?
+        return call.getObjectExpression() == THIS_EXPRESSION;
+    }
+
+    /**
+     * Converts a ClosureExpression into the String source.
+     *
+     * @param expression a closure
+     * @return the source the closure was created from
+     */
+    private String convertClosureToSource(ReaderSource source, ClosureExpression expression) {
+
+        try {
+            return ClosureUtils.convertClosureToSource(source, expression);
+        } catch (Exception e) {
+            addError(e.getMessage(), expression);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
new file mode 100644
index 0000000..cdf0f07
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
+
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.ModuleNode;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
+public class MacroTransformation extends ClassCodeVisitorSupport implements ASTTransformation {
+
+    public static final String DOLLAR_VALUE = "$v";
+    public static final String MACRO_METHOD = "macro";
+
+    SourceUnit source;
+    
+    MacroInvocationTrap transformer;
+
+    public void visit(ASTNode[] nodes, SourceUnit source) {
+        this.source = source;
+
+        transformer = new MacroInvocationTrap(source.getSource(), source);
+
+        for(ASTNode node : nodes) {
+            if(node instanceof ClassNode) {
+                visitClass((ClassNode) node);
+            } else if(node instanceof ModuleNode) {
+                ModuleNode moduleNode = (ModuleNode) node;
+                for (ClassNode classNode : moduleNode.getClasses()) {
+                    visitClass(classNode);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void visitMethodCallExpression(MethodCallExpression call) {
+        transformer.visitMethodCallExpression(call);
+        super.visitMethodCallExpression(call);
+    }
+
+    @Override
+    protected SourceUnit getSourceUnit() {
+        return source;
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation b/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
new file mode 100644
index 0000000..09d8397
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
@@ -0,0 +1,2 @@
+#global transformation for macro support
+org.codehaus.groovy.macro.transform.MacroTransformation
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0b5f0b03/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
new file mode 100644
index 0000000..df46802
--- /dev/null
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2003-2013 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
+
+import groovy.transform.CompileStatic
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.VariableScope
+import org.codehaus.groovy.ast.builder.AstAssert
+import org.codehaus.groovy.ast.expr.*
+import org.codehaus.groovy.ast.stmt.*
+
+import static org.codehaus.groovy.ast.expr.VariableExpression.*;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+@CompileStatic
+class SimpleMacroTest extends GroovyShellTestCase {
+    public void testMethod() {
+
+        def someVariable = new VariableExpression("someVariable");
+
+        ReturnStatement result = macro {
+            return new NonExistingClass($v{someVariable});
+        }
+        
+        def expected = new ReturnStatement(new ConstructorCallExpression(ClassHelper.make("NonExistingClass"), new ArgumentListExpression(someVariable)));
+
+        assertSyntaxTree(expected, result);
+    }
+    
+    public void testAsIs() {
+        def expected = new BlockStatement([
+                new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
+        ] as List<Statement>, new VariableScope());
+
+        BlockStatement result = macro(true) {
+            println "foo"
+        }
+
+        assertSyntaxTree(expected, result);
+    }
+
+    public void testInception() {
+
+        ConstructorCallExpression result = macro {
+            new NonExistingClass($v{macro {someVariable}});
+        }
+
+        def expected = new ConstructorCallExpression(ClassHelper.make("NonExistingClass"), new ArgumentListExpression(new VariableExpression("someVariable")));
+
+        assertSyntaxTree(expected, result);
+    }
+
+    public void testBlock() {
+
+        def result = macro {
+            println "foo"
+            println "bar"
+        }
+
+        def expected = new BlockStatement(
+                [
+                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
+                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
+                ] as List<Statement>,
+                new VariableScope()
+        )
+
+        assertSyntaxTree(expected, result);
+    }
+    
+    protected void assertSyntaxTree(Object expected, Object result) {
+        AstAssert.assertSyntaxTree([expected], [result])
+    }
+}


[06/37] incubator-groovy git commit: fix wrong macro test case superclass

Posted by cc...@apache.org.
fix wrong macro test case superclass


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/0efac35d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/0efac35d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/0efac35d

Branch: refs/heads/master
Commit: 0efac35d23465158f4450051409063a10320405e
Parents: ff1d4a0
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:21:58 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:04 2015 +0300

----------------------------------------------------------------------
 .../groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/0efac35d/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index 64bb1bf..ad9b15b 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -29,7 +29,7 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.*;
  * @author Sergei Egorov <bs...@gmail.com>
  */
 @CompileStatic
-class SimpleMacroTest extends GroovyShellTestCase {
+class SimpleMacroTest extends GroovyTestCase {
     
     static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
     


[09/37] incubator-groovy git commit: First bits of work on a contextual class code visitor

Posted by cc...@apache.org.
First bits of work on a contextual class code visitor


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/a522e8ff
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/a522e8ff
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/a522e8ff

Branch: refs/heads/master
Commit: a522e8ff44f1c2e11154376ec600944f9787bd57
Parents: f080510
Author: Cedric Champeau <ce...@gmail.com>
Authored: Tue Oct 14 20:29:26 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:05 2015 +0300

----------------------------------------------------------------------
 .../groovy/ast/ContextualClassCodeVisitor.java  | 638 +++++++++++++++++++
 1 file changed, 638 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/a522e8ff/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java b/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
new file mode 100644
index 0000000..742cb72
--- /dev/null
+++ b/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
@@ -0,0 +1,638 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.ast;
+
+import groovy.lang.Closure;
+import groovy.lang.MapWithDefault;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.AssertStatement;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.BreakStatement;
+import org.codehaus.groovy.ast.stmt.CaseStatement;
+import org.codehaus.groovy.ast.stmt.CatchStatement;
+import org.codehaus.groovy.ast.stmt.ContinueStatement;
+import org.codehaus.groovy.ast.stmt.DoWhileStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ForStatement;
+import org.codehaus.groovy.ast.stmt.IfStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.SwitchStatement;
+import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
+import org.codehaus.groovy.ast.stmt.ThrowStatement;
+import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.ast.stmt.WhileStatement;
+import org.codehaus.groovy.classgen.BytecodeExpression;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A class code visitor which is capable of remembering the context of the current
+ * visit. This makes it easier for subclasses to perform context-dependent transformations,
+ * where for example it is necessary to check the parent nodes of an AST node before
+ * performing some operations.
+ *
+ * @author Cedric Champeau
+ * @since 2.4.0
+ */
+public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport {
+    private final Deque<TreeContext> treeContextStack = new ArrayDeque<TreeContext>();
+    private TreeContext lastContext;
+
+    public ContextualClassCodeVisitor() {
+        pushContext(new TreeContext(null, null));
+    }
+
+    public TreeContext getTreeContext() {
+        return treeContextStack.isEmpty()?null:treeContextStack.peek();
+    }
+
+    protected void pushContext(TreeContext ctx) {
+        treeContextStack.push(ctx);
+    }
+
+    protected TreeContext popContext() {
+        TreeContext treeContext = treeContextStack.pop();
+        List<TreeContextAction> actions = treeContext.getOnPopHandlers();
+        for (TreeContextAction contextAction : actions) {
+            contextAction.call(treeContext);
+        }
+        lastContext = treeContext;
+        return treeContext;
+    }
+
+    protected void pushContext(ASTNode node) {
+        pushContext(getTreeContext().fork(node));
+    }
+
+
+    // ----------------------- override visit methods to provide contextual information ---------------------------
+
+
+    @Override
+    public void visitClass(final ClassNode node) {
+        pushContext(node);
+        super.visitClass(node);
+        popContext();
+    }
+
+    @Override
+    public void visitPackage(final PackageNode node) {
+        if (node!=null) {
+            pushContext(node);
+        }
+        super.visitPackage(node);
+        if (node!=null) {
+            popContext();
+        }
+    }
+
+    @Override
+    public void visitImports(final ModuleNode node) {
+        pushContext(node);
+        super.visitImports(node);
+        popContext();
+    }
+
+    @Override
+    protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
+        pushContext(node);
+        super.visitConstructorOrMethod(node, isConstructor);
+        popContext();
+    }
+
+    @Override
+    public void visitField(final FieldNode node) {
+        pushContext(node);
+        super.visitField(node);
+        popContext();
+    }
+
+    @Override
+    public void visitProperty(final PropertyNode node) {
+        pushContext(node);
+        super.visitProperty(node);
+        popContext();
+    }
+
+    @Override
+    public void visitMethodCallExpression(final MethodCallExpression call) {
+        pushContext(call);
+        super.visitMethodCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
+        pushContext(call);
+        super.visitStaticMethodCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
+        pushContext(call);
+        super.visitConstructorCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitBinaryExpression(final BinaryExpression expression) {
+        pushContext(expression);
+        super.visitBinaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitTernaryExpression(final TernaryExpression expression) {
+        pushContext(expression);
+        super.visitTernaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
+        pushContext(expression);
+        super.visitShortTernaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPostfixExpression(final PostfixExpression expression) {
+        pushContext(expression);
+        super.visitPostfixExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPrefixExpression(final PrefixExpression expression) {
+        pushContext(expression);
+        super.visitPrefixExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitBooleanExpression(final BooleanExpression expression) {
+        pushContext(expression);
+        super.visitBooleanExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitNotExpression(final NotExpression expression) {
+        pushContext(expression);
+        super.visitNotExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClosureExpression(final ClosureExpression expression) {
+        pushContext(expression);
+        super.visitClosureExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitTupleExpression(final TupleExpression expression) {
+        pushContext(expression);
+        super.visitTupleExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitListExpression(final ListExpression expression) {
+        pushContext(expression);
+        super.visitListExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitArrayExpression(final ArrayExpression expression) {
+        pushContext(expression);
+        super.visitArrayExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMapExpression(final MapExpression expression) {
+        pushContext(expression);
+        super.visitMapExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMapEntryExpression(final MapEntryExpression expression) {
+        pushContext(expression);
+        super.visitMapEntryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitRangeExpression(final RangeExpression expression) {
+        pushContext(expression);
+        super.visitRangeExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitSpreadExpression(final SpreadExpression expression) {
+        pushContext(expression);
+        super.visitSpreadExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
+        pushContext(expression);
+        super.visitSpreadMapExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
+        pushContext(expression);
+        super.visitMethodPointerExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
+        pushContext(expression);
+        super.visitUnaryMinusExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
+        pushContext(expression);
+        super.visitUnaryPlusExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
+        pushContext(expression);
+        super.visitBitwiseNegationExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitCastExpression(final CastExpression expression) {
+        pushContext(expression);
+        super.visitCastExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitConstantExpression(final ConstantExpression expression) {
+        pushContext(expression);
+        super.visitConstantExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClassExpression(final ClassExpression expression) {
+        pushContext(expression);
+        super.visitClassExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitVariableExpression(final VariableExpression expression) {
+        pushContext(expression);
+        super.visitVariableExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPropertyExpression(final PropertyExpression expression) {
+        pushContext(expression);
+        super.visitPropertyExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitAttributeExpression(final AttributeExpression expression) {
+        pushContext(expression);
+        super.visitAttributeExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitFieldExpression(final FieldExpression expression) {
+        pushContext(expression);
+        super.visitFieldExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitGStringExpression(final GStringExpression expression) {
+        pushContext(expression);
+        super.visitGStringExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClosureListExpression(final ClosureListExpression cle) {
+        pushContext(cle);
+        super.visitClosureListExpression(cle);
+        popContext();
+    }
+
+    @Override
+    public void visitBytecodeExpression(final BytecodeExpression cle) {
+        pushContext(cle);
+        super.visitBytecodeExpression(cle);
+        popContext();
+    }
+
+    @Override
+    public void visitAssertStatement(final AssertStatement statement) {
+        pushContext(statement);
+        super.visitAssertStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitBlockStatement(final BlockStatement block) {
+        pushContext(block);
+        super.visitBlockStatement(block);
+        popContext();
+    }
+
+    @Override
+    public void visitBreakStatement(final BreakStatement statement) {
+        pushContext(statement);
+        super.visitBreakStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitCaseStatement(final CaseStatement statement) {
+        pushContext(statement);
+        super.visitCaseStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitCatchStatement(final CatchStatement statement) {
+        pushContext(statement);
+        super.visitCatchStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitContinueStatement(final ContinueStatement statement) {
+        pushContext(statement);
+        super.visitContinueStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitDoWhileLoop(final DoWhileStatement loop) {
+        pushContext(loop);
+        super.visitDoWhileLoop(loop);
+        popContext();
+    }
+
+    @Override
+    public void visitExpressionStatement(final ExpressionStatement statement) {
+        pushContext(statement);
+        super.visitExpressionStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitForLoop(final ForStatement forLoop) {
+        pushContext(forLoop);
+        super.visitForLoop(forLoop);
+        popContext();
+    }
+
+    @Override
+    public void visitIfElse(final IfStatement ifElse) {
+        pushContext(ifElse);
+        super.visitIfElse(ifElse);
+        popContext();
+    }
+
+    @Override
+    public void visitReturnStatement(final ReturnStatement statement) {
+        pushContext(statement);
+        super.visitReturnStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitSwitch(final SwitchStatement statement) {
+        pushContext(statement);
+        super.visitSwitch(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitSynchronizedStatement(final SynchronizedStatement statement) {
+        pushContext(statement);
+        super.visitSynchronizedStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitThrowStatement(final ThrowStatement statement) {
+        pushContext(statement);
+        super.visitThrowStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitTryCatchFinally(final TryCatchStatement statement) {
+        pushContext(statement);
+        super.visitTryCatchFinally(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitWhileLoop(final WhileStatement loop) {
+        pushContext(loop);
+        super.visitWhileLoop(loop);
+        popContext();
+    }
+
+    @Override
+    protected void visitEmptyStatement(final EmptyStatement statement) {
+        pushContext(statement);
+        super.visitEmptyStatement(statement);
+        popContext();
+    }
+
+    public List<TreeContext> getTreePath() {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        path.add(lastContext);
+        for (TreeContext treeContext : treeContextStack) {
+            path.add(treeContext);
+        }
+        return path;
+    }
+    public List<TreeContext> pathMatches(List<ASTNodePredicate> predicates) {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        TreeContext current = lastContext.parent;
+        for (ASTNodePredicate predicate : predicates) {
+            path.add(current);
+            if (current==null || !predicate.matches(current.node)) {
+                return Collections.emptyList();
+            }
+            current = current.parent;
+        }
+        if (!path.isEmpty()) {
+            path.add(0, lastContext);
+        }
+        return path;
+    }
+
+    public List<TreeContext> pathUpTo(ASTNodePredicate predicate) {
+        return pathUpTo(null, predicate);
+    }
+
+    public List<TreeContext> pathUpTo(Class<ASTNode> node) {
+        return pathUpTo(node, null);
+    }
+
+    public List<TreeContext> pathUpTo(Class<ASTNode> node, ASTNodePredicate predicate) {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        TreeContext current = lastContext;
+        boolean found = false;
+        while (current!=null && !found) {
+            path.add(current);
+            ASTNode currentNode = current.node;
+            if (node==null) {
+                if (predicate.matches(currentNode)) {
+                    found = true;
+                }
+            } else {
+                if (predicate==null) {
+                    if (currentNode==null || node==currentNode.getClass()) {
+                        found = true;
+                    }
+                } else {
+                    found = currentNode!=null && node==currentNode.getClass() && predicate.matches(currentNode);
+                }
+            }
+
+            current = current.parent;
+        }
+        if (found) {
+            return path;
+        }
+        return Collections.emptyList();
+    }
+
+    // ----------------------------- inner classes --------------------------------------
+
+    public static class TreeContext {
+        final TreeContext parent;
+        final ASTNode node;
+        final List<TreeContext> siblings = new LinkedList<TreeContext>();
+        final List<TreeContextAction> onPopHandlers = new LinkedList<TreeContextAction>();
+        final Map<?, List<?>> userdata = MapWithDefault.newInstance(
+                new HashMap<Object, List<?>>(),
+                new Closure(this) {
+                    public Object doCall(String key) {
+                        return new LinkedList<Object>();
+                    }
+                }
+        );
+
+        private TreeContext(final TreeContext parent, final ASTNode node) {
+            this.parent = parent;
+            this.node = node;
+            if (parent!=null) {
+                parent.siblings.add(this);
+            }
+        }
+
+        public Map<?, ?> getUserdata() {
+            return userdata;
+        }
+
+        public TreeContext getParent() { return parent; }
+        public ASTNode getNode() { return node; }
+
+        public TreeContext fork(ASTNode node) {
+            return new TreeContext(this, node);
+        }
+
+        public boolean matches(ASTNodePredicate predicate) {
+            return predicate.matches(node);
+        }
+
+        public List<TreeContext> getSiblings() {
+            return Collections.unmodifiableList(siblings);
+        }
+
+        public List<TreeContextAction> getOnPopHandlers() {
+            return Collections.unmodifiableList(onPopHandlers);
+        }
+
+        public void afterVisit(TreeContextAction action) {
+            onPopHandlers.add(action);
+        }
+
+        @Override
+        public String toString() {
+            final StringBuilder sb = new StringBuilder("TreeContext{");
+            sb.append("node=").append(node!=null?node.getClass().getSimpleName():"undefined");
+            //sb.append(", siblings=").append(siblings);
+            sb.append('}');
+            return sb.toString();
+        }
+    }
+
+    public static interface ASTNodePredicate {
+        boolean matches(ASTNode node);
+    }
+
+    public static interface TreeContextAction {
+        void call(TreeContext context);
+    }
+
+    public static List<ASTNodePredicate> matchByClass(Class<ASTNode>... classes) {
+        ArrayList<ASTNodePredicate> result = new ArrayList<ASTNodePredicate>(classes.length);
+        for (final Class<ASTNode> astNodeClass : classes) {
+            result.add(new MatchByClass(astNodeClass));
+        }
+        return result;
+    }
+
+    private static class MatchByClass implements ASTNodePredicate {
+        private final Class<ASTNode> astNodeClass;
+
+        public MatchByClass(final Class<ASTNode> astNodeClass) {
+            this.astNodeClass = astNodeClass;
+        }
+
+        @Override
+        public boolean matches(final ASTNode node) {
+            return astNodeClass ==node.getClass();
+        }
+    }
+}


[17/37] incubator-groovy git commit: ASTMatcher: Test cases for closure expression and boolean expression

Posted by cc...@apache.org.
ASTMatcher: Test cases for closure expression and boolean expression


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/3eba53cc
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/3eba53cc
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/3eba53cc

Branch: refs/heads/master
Commit: 3eba53cc62703929045ee353082f6432a88d061a
Parents: f736c6a
Author: Cedric Champeau <ce...@gmail.com>
Authored: Thu Oct 16 17:48:04 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 32 +++++++++++++++++++-
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 32 ++++++++++++++++++++
 2 files changed, 63 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3eba53cc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index cec1632..1bfc366 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -517,7 +517,37 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitClosureExpression(final ClosureExpression expression) {
-        super.visitClosureExpression(expression);
+        doWithNode(ClosureExpression, current) {
+            def code = expression.code
+            def cl = (ClosureExpression) current
+            doWithNode(code.class, cl.code) {
+                code.visit(this)
+                checkParameters(expression.parameters, cl.parameters)
+            }
+        }
+    }
+
+    private void checkParameters(Parameter[] nodeParams, Parameter[] curParams) {
+        if (nodeParams==null && curParams!=null || nodeParams!=null && curParams==null) {
+            match = false
+            return
+        }
+        if (nodeParams) {
+            if (curParams.length==nodeParams.length) {
+                for (int i = 0; i < nodeParams.length && match; i++) {
+                    def n = nodeParams[i]
+                    def c = curParams[i]
+                    doWithNode(n.class, c) {
+                        match = match &&
+                                (n.name == c.name) &&
+                                (n.originType == c.originType) &&
+                                (n.type == c.originType)
+                    }
+                }
+            } else {
+                match = false
+            }
+        }
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3eba53cc/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 6f42859..b473d66 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -171,4 +171,36 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast1, ast4)
         assert !ASTMatcher.matches(ast1, ast5)
     }
+
+    void testBooleanExpression() {
+        def ast1 = macro { a==1 }
+        def ast2 = macro { a==1 }
+        def ast3 = macro { 1==a }
+        def ast4 = macro { a==a }
+        def ast5 = macro { a==2 }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+    }
+
+    void testClosureExpression() {
+        def ast1 = macro { {-> a } }
+        def ast2 = macro { {-> a } }
+        def ast3 = macro { {-> b } }
+        def ast4 = macro { { a -> a } }
+        def ast5 = macro { { a -> a } }
+        def ast6 = macro { { a,b -> a } }
+        def ast7 = macro { { int a -> a } }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert ASTMatcher.matches(ast4, ast5)
+        assert !ASTMatcher.matches(ast5, ast6)
+        assert !ASTMatcher.matches(ast5, ast7)
+    }
 }


[05/37] incubator-groovy git commit: CompilePhase support in macro

Posted by cc...@apache.org.
CompilePhase support in macro


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/6d277a07
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/6d277a07
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/6d277a07

Branch: refs/heads/master
Commit: 6d277a078ef32378afb0d9d271b2e4cf4031cf45
Parents: 0efac35
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:57:35 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:04 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/runtime/MacroBuilder.java      | 16 +++++++--
 .../macro/runtime/MacroGroovyMethods.java       |  9 +++++
 .../macro/transform/MacroInvocationTrap.java    | 35 +++++++++-----------
 .../test/groovy/groovy/SimpleMacroTest.groovy   | 34 ++++++++++++++++++-
 4 files changed, 71 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/6d277a07/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index 2c66f3e..ae82081 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -39,14 +39,26 @@ import java.util.Map;
 public enum MacroBuilder {
     INSTANCE;
 
-    @SuppressWarnings("unchecked")
+    public <T> T macro(String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(false, source, context, resultClass);
+    }
+
     public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(CompilePhase.CONVERSION, asIs, source, context, resultClass);
+    }
+
+    public <T> T macro(CompilePhase compilePhase, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(compilePhase, false, source, context, resultClass);
+    }
+
+    @SuppressWarnings("unchecked")
+    public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
         final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
         final String labelledSource = label + source;
         final int linesOffset = 1;
         final int columnsOffset = label.length() + 1; // +1 because of {
         
-        List<ASTNode> nodes = (new AstBuilder()).buildFromString(CompilePhase.CONVERSION, true, labelledSource);
+        List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
 
         for(ASTNode node : nodes) {
             if (node instanceof BlockStatement) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/6d277a07/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
index 578a11f..5c41c04 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -17,6 +17,7 @@ package org.codehaus.groovy.macro.runtime;
 
 import groovy.lang.Closure;
 import groovy.lang.DelegatesTo;
+import org.codehaus.groovy.control.CompilePhase;
 
 /**
  *
@@ -38,4 +39,12 @@ public class MacroGroovyMethods {
     public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
         return null;
     }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/6d277a07/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index b082e8b..127fb4b 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -88,31 +88,26 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
 
-        if(macroArgumentsExpressions.size() > 1) {
-            Expression firstArgument = macroArgumentsExpressions.get(0);
-
-            if(!(firstArgument instanceof ConstantExpression)) {
-                addError("AsIs argument value should be constant(true or false)", firstArgument);
-                return true;
-            }
-
-            ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
+        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
+            Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
+            if((asIsArgumentExpression instanceof ConstantExpression)) {
+                ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
+
+                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                    addError("AsIs argument value should be boolean", asIsConstantExpression);
+                    return true;
+                }
 
-            if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
-                addError("AsIs argument value should be boolean", asIsConstantExpression);
-                return true;
+                asIs = (Boolean) asIsConstantExpression.getValue();
             }
-
-            asIs = (Boolean) asIsConstantExpression.getValue();
         }
 
-        List<Expression> otherArgs = new ArrayList<Expression>();
-        otherArgs.add(new ConstantExpression(asIs));
-        otherArgs.add(new ConstantExpression(source));
-        otherArgs.add(mapExpression);
-        otherArgs.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
+        macroArgumentsExpressions.remove(macroArgumentsExpressions.size() - 1);
+
+        macroArgumentsExpressions.add(new ConstantExpression(source));
+        macroArgumentsExpressions.add(mapExpression);
+        macroArgumentsExpressions.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
 
-        macroCall.setArguments(new ArgumentListExpression(otherArgs));
         macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/6d277a07/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index ad9b15b..9a29fc3 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -21,6 +21,7 @@ import org.codehaus.groovy.ast.VariableScope
 import org.codehaus.groovy.ast.builder.AstAssert
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.*
+import org.codehaus.groovy.control.CompilePhase
 
 import static org.codehaus.groovy.ast.expr.VariableExpression.*;
 
@@ -45,7 +46,7 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
-    
+
     public void testAsIs() {
         def expected = new BlockStatement([
                 new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
@@ -92,6 +93,37 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
+
+    public void testCompilePhase() {
+
+        def result = macro(CompilePhase.FINALIZATION) {
+            println "foo"
+            println "bar"
+        }
+
+        def expected = new BlockStatement(
+                [
+                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
+                        // In FINALIZATION phase last println will be return statement
+                        new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
+                ] as List<Statement>,
+                new VariableScope()
+        )
+
+        assertSyntaxTree(expected, result);
+    }
+
+    public void testAsIsWithCompilePhase() {
+        def expected = new BlockStatement([
+                new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
+        ] as List<Statement>, new VariableScope());
+
+        def result = macro(CompilePhase.FINALIZATION, true) {
+            println "foo"
+        }
+
+        assertSyntaxTree(expected, result);
+    }
     
     protected void assertSyntaxTree(Object expected, Object result) {
         AstAssert.assertSyntaxTree([expected], [result])


[18/37] incubator-groovy git commit: Fixed anonymous inner MacroClass being kept in the module as a class to be compiled even though it won't be used. Fixes the problem of the scoping of macro substitutions.

Posted by cc...@apache.org.
Fixed anonymous inner MacroClass being kept in the module as a class to be compiled even though it won't be used. Fixes the problem of the scoping of macro substitutions.


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/cae14620
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/cae14620
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/cae14620

Branch: refs/heads/master
Commit: cae1462040b42431872d8c645e94f890b6863c9c
Parents: 09758c3
Author: Cedric Champeau <ce...@gmail.com>
Authored: Thu Oct 16 14:50:38 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../macro/transform/MacroInvocationTrap.java    | 24 +++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/cae14620/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index 5a7c275..df13f38 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -15,6 +15,7 @@
  */
 package org.codehaus.groovy.macro.transform;
 
+import groovy.lang.Closure;
 import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
 import org.codehaus.groovy.ast.ClassHelper;
@@ -33,15 +34,18 @@ import org.codehaus.groovy.ast.expr.MethodCallExpression;
 import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.expr.TupleExpression;
 import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
 import org.codehaus.groovy.ast.tools.GeneralUtils;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
 import org.codehaus.groovy.macro.runtime.MacroBuilder;
 import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
 
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 
 import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
 
@@ -52,10 +56,12 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
     private final static ClassNode MACROCLASS_TYPE = ClassHelper.make(MacroClass.class);
     private final ReaderSource readerSource;
+    private final SourceUnit sourceUnit;
 
     public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
         super(source, sourceUnit);
         this.readerSource = source;
+        this.sourceUnit = sourceUnit;
     }
 
     @Override
@@ -82,6 +88,13 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
                     macroCall.setSafe(false);
                     macroCall.setImplicitThis(false);
                     call.putNodeMetaData(MacroTransformation.class, macroCall);
+                    List<ClassNode> classes = sourceUnit.getAST().getClasses();
+                    for (Iterator<ClassNode> iterator = classes.iterator(); iterator.hasNext(); ) {
+                        final ClassNode aClass = iterator.next();
+                        if (aClass==type || type==aClass.getOuterClass()) {
+                            iterator.remove();
+                        }
+                    }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
@@ -157,6 +170,7 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
     }
 
     private MapExpression buildSubstitutionMap(final ASTNode expr) {
+        final Map<MacroSubstitutionKey, ClosureExpression> map = new HashMap<MacroSubstitutionKey, ClosureExpression>();
         final MapExpression mapExpression = new MapExpression();
 
         ClassCodeVisitorSupport visitor = new ClassCodeVisitorSupport() {
@@ -186,9 +200,14 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
                         return;
                     }
 
+                    Statement code = substitutionClosureExpression.getCode();
+                    if (code instanceof BlockStatement) {
+                        ((BlockStatement) code).setVariableScope(null);
+                    }
+
                     MacroSubstitutionKey key = new MacroSubstitutionKey(call, expr.getLineNumber(), expr.getColumnNumber());
 
-                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
+                    map.put(key, substitutionClosureExpression);
                 }
             }
         };
@@ -197,6 +216,9 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
         } else {
             expr.visit(visitor);
         }
+        for (Map.Entry<MacroSubstitutionKey, ClosureExpression> entry : map.entrySet()) {
+            mapExpression.addMapEntryExpression(entry.getKey().toConstructorCallExpression(), entry.getValue());
+        }
         return mapExpression;
     }
 


[25/37] incubator-groovy git commit: ASTMatcher: Add support for if/else

Posted by cc...@apache.org.
ASTMatcher: Add support for if/else


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/8c1f2634
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/8c1f2634
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/8c1f2634

Branch: refs/heads/master
Commit: 8c1f263477e31f6a5339655b94734c0e5f98dd03
Parents: 817bbef
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 13:39:20 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:11 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 25 +++++++++++++++++++-
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 22 +++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/8c1f2634/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 7b5262c..d715737 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -20,7 +20,9 @@ import groovy.transform.TypeCheckingMode
 import org.codehaus.groovy.ast.*
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.BlockStatement
+import org.codehaus.groovy.ast.stmt.EmptyStatement
 import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.ast.stmt.Statement
 import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
@@ -391,8 +393,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     void visitExpressionStatement(final ExpressionStatement statement) {
-        visitStatement(statement)
         doWithNode(statement.expression.class, ((ExpressionStatement) current).expression) {
+            visitStatement(statement)
             statement.expression.visit(this)
         }
     }
@@ -835,4 +837,25 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitBytecodeExpression(final BytecodeExpression cle) {
         super.visitBytecodeExpression(cle);
     }
+
+    @Override
+    void visitIfElse(final IfStatement ifElse) {
+        doWithNode(IfStatement, current) {
+            visitStatement(ifElse)
+            def cur = (IfStatement) current
+            def bool = ifElse.booleanExpression
+            def ifBlock = ifElse.ifBlock
+            def elseBlock = ifElse.elseBlock
+            doWithNode(bool.class, cur.booleanExpression) {
+                bool.visit(this)
+            }
+            doWithNode(ifBlock.class, cur.ifBlock) {
+                ifBlock.visit(this)
+            }
+            failIfNot(elseBlock && cur.elseBlock || !elseBlock && !cur.elseBlock)
+            doWithNode(elseBlock.class, cur.elseBlock) {
+                elseBlock.visit(this)
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/8c1f2634/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index ef7c489..eec19b9 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -26,6 +26,7 @@ import org.codehaus.groovy.ast.expr.MethodPointerExpression
 import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
 import org.codehaus.groovy.ast.expr.UnaryMinusExpression
 import org.codehaus.groovy.ast.expr.UnaryPlusExpression
+import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.control.CompilePhase
 import org.codehaus.groovy.macro.transform.MacroClass
 
@@ -515,4 +516,25 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast8, ast9)
         assert !ASTMatcher.matches(ast1, ast10)
     }
+
+    void testIf() {
+        def ast1 = macro { if (a) b }
+        def ast2 = macro { if (a) b }
+        def ast3 = macro { if (a) c }
+        def ast4 = macro { if (b) b }
+        def ast5 = macro { if (a) { b } }
+        def ast6 = macro { if (a) { b } else { c }}
+        def ast7 = macro { if (a) { b } else { c }}
+        def ast8 = macro { if (a) { b } else { d }}
+        assert ast1 instanceof IfStatement
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+        assert ASTMatcher.matches(ast6, ast7)
+        assert !ASTMatcher.matches(ast7, ast8)
+    }
 }


[12/37] incubator-groovy git commit: CompilePhase support in macro

Posted by cc...@apache.org.
CompilePhase support in macro


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/f0805101
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/f0805101
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/f0805101

Branch: refs/heads/master
Commit: f0805101fdf844a03ba556281e6ea5bc89a5d637
Parents: b28460b
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:57:35 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:05 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/runtime/MacroBuilder.java      | 16 +++++++--
 .../macro/runtime/MacroGroovyMethods.java       |  9 +++++
 .../macro/transform/MacroInvocationTrap.java    | 35 +++++++++-----------
 .../test/groovy/groovy/SimpleMacroTest.groovy   | 34 ++++++++++++++++++-
 4 files changed, 71 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f0805101/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index 2c66f3e..ae82081 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -39,14 +39,26 @@ import java.util.Map;
 public enum MacroBuilder {
     INSTANCE;
 
-    @SuppressWarnings("unchecked")
+    public <T> T macro(String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(false, source, context, resultClass);
+    }
+
     public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(CompilePhase.CONVERSION, asIs, source, context, resultClass);
+    }
+
+    public <T> T macro(CompilePhase compilePhase, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(compilePhase, false, source, context, resultClass);
+    }
+
+    @SuppressWarnings("unchecked")
+    public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
         final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
         final String labelledSource = label + source;
         final int linesOffset = 1;
         final int columnsOffset = label.length() + 1; // +1 because of {
         
-        List<ASTNode> nodes = (new AstBuilder()).buildFromString(CompilePhase.CONVERSION, true, labelledSource);
+        List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
 
         for(ASTNode node : nodes) {
             if (node instanceof BlockStatement) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f0805101/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
index 578a11f..5c41c04 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -17,6 +17,7 @@ package org.codehaus.groovy.macro.runtime;
 
 import groovy.lang.Closure;
 import groovy.lang.DelegatesTo;
+import org.codehaus.groovy.control.CompilePhase;
 
 /**
  *
@@ -38,4 +39,12 @@ public class MacroGroovyMethods {
     public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
         return null;
     }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f0805101/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index b082e8b..127fb4b 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -88,31 +88,26 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
 
-        if(macroArgumentsExpressions.size() > 1) {
-            Expression firstArgument = macroArgumentsExpressions.get(0);
-
-            if(!(firstArgument instanceof ConstantExpression)) {
-                addError("AsIs argument value should be constant(true or false)", firstArgument);
-                return true;
-            }
-
-            ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
+        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
+            Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
+            if((asIsArgumentExpression instanceof ConstantExpression)) {
+                ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
+
+                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                    addError("AsIs argument value should be boolean", asIsConstantExpression);
+                    return true;
+                }
 
-            if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
-                addError("AsIs argument value should be boolean", asIsConstantExpression);
-                return true;
+                asIs = (Boolean) asIsConstantExpression.getValue();
             }
-
-            asIs = (Boolean) asIsConstantExpression.getValue();
         }
 
-        List<Expression> otherArgs = new ArrayList<Expression>();
-        otherArgs.add(new ConstantExpression(asIs));
-        otherArgs.add(new ConstantExpression(source));
-        otherArgs.add(mapExpression);
-        otherArgs.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
+        macroArgumentsExpressions.remove(macroArgumentsExpressions.size() - 1);
+
+        macroArgumentsExpressions.add(new ConstantExpression(source));
+        macroArgumentsExpressions.add(mapExpression);
+        macroArgumentsExpressions.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
 
-        macroCall.setArguments(new ArgumentListExpression(otherArgs));
         macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f0805101/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index ad9b15b..9a29fc3 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -21,6 +21,7 @@ import org.codehaus.groovy.ast.VariableScope
 import org.codehaus.groovy.ast.builder.AstAssert
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.*
+import org.codehaus.groovy.control.CompilePhase
 
 import static org.codehaus.groovy.ast.expr.VariableExpression.*;
 
@@ -45,7 +46,7 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
-    
+
     public void testAsIs() {
         def expected = new BlockStatement([
                 new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
@@ -92,6 +93,37 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
+
+    public void testCompilePhase() {
+
+        def result = macro(CompilePhase.FINALIZATION) {
+            println "foo"
+            println "bar"
+        }
+
+        def expected = new BlockStatement(
+                [
+                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
+                        // In FINALIZATION phase last println will be return statement
+                        new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
+                ] as List<Statement>,
+                new VariableScope()
+        )
+
+        assertSyntaxTree(expected, result);
+    }
+
+    public void testAsIsWithCompilePhase() {
+        def expected = new BlockStatement([
+                new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
+        ] as List<Statement>, new VariableScope());
+
+        def result = macro(CompilePhase.FINALIZATION, true) {
+            println "foo"
+        }
+
+        assertSyntaxTree(expected, result);
+    }
     
     protected void assertSyntaxTree(Object expected, Object result) {
         AstAssert.assertSyntaxTree([expected], [result])


[32/37] incubator-groovy git commit: ASTMatcher: Add "eventually"hook on binary expression (to be expanded to other nodes) to illustrate how to perform cross-context matching

Posted by cc...@apache.org.
ASTMatcher: Add "eventually"hook on binary expression (to be expanded to other nodes) to illustrate how to perform cross-context matching


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/053af2e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/053af2e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/053af2e4

Branch: refs/heads/master
Commit: 053af2e4eae6c66adc0e87a87e0acc740206b13e
Parents: 3d6d571
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Nov 12 17:57:10 2014 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:13 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      |  7 ++++++
 .../macro/matcher/MatchingConstraints.groovy    |  4 +++-
 .../groovy/macro/matcher/TreeContext.java       |  4 ++++
 .../internal/MatchingConstraintsBuilder.groovy  | 20 ++++++++++++++++-
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 23 ++++++++++++++++++++
 5 files changed, 56 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/053af2e4/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index e8d83f7..77bdb0d 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -544,6 +544,13 @@ class ASTMatcher extends ContextualClassCodeVisitor {
                     }
                 })
             }
+            failIfNot(ifConstraint(true) {
+                if (eventually) {
+                    eventually.apply(treeContext)
+                } else {
+                    true
+                }
+            })
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/053af2e4/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
index ed25d35..ef46b58 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
@@ -18,6 +18,7 @@ package org.codehaus.groovy.macro.matcher
 
 import groovy.transform.CompileStatic
 import groovy.transform.Immutable
+import org.codehaus.groovy.ast.ASTNode
 import org.codehaus.groovy.macro.matcher.internal.AnyTokenMatch
 import org.codehaus.groovy.macro.matcher.internal.ConstraintPredicate
 import org.codehaus.groovy.syntax.Token
@@ -29,11 +30,12 @@ import org.codehaus.groovy.syntax.Token
  * @since 2.4.0
  */
 @CompileStatic
-@Immutable(knownImmutables = ['tokenPredicate'])
+@Immutable(knownImmutableClasses = [ConstraintPredicate])
 class MatchingConstraints {
     public final static ConstraintPredicate<Token> ANY_TOKEN = AnyTokenMatch.INSTANCE
 
     final Set<String> placeholders
     final ConstraintPredicate<Token> tokenPredicate
+    final ConstraintPredicate<TreeContext> eventually
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/053af2e4/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
index 4644555..6c77d25 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
@@ -61,6 +61,10 @@ public class TreeContext {
         ((List)userdata.get(key)).add(value);
     }
 
+    public List<?> getUserdata(Object key) {
+        return getUserdata(key,true);
+    }
+
     public List<?> getUserdata(Object key, boolean searchParent) {
         if (userdata.containsKey(key)) {
             return userdata.get(key);

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/053af2e4/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
index 070013b..5060089 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
@@ -16,12 +16,15 @@
 
 package org.codehaus.groovy.macro.matcher.internal
 
+import org.codehaus.groovy.ast.ASTNode
 import org.codehaus.groovy.macro.matcher.MatchingConstraints
+import org.codehaus.groovy.macro.matcher.TreeContext
 import org.codehaus.groovy.syntax.Token
 
 class MatchingConstraintsBuilder {
     Set<String> placeholders = new LinkedHashSet<>()
     ConstraintPredicate<Token> tokenPredicate
+    ConstraintPredicate<TreeContext> eventually
 
 
     MatchingConstraints build(@DelegatesTo(value=MatchingConstraintsBuilder, strategy=Closure.DELEGATE_ONLY) Closure spec) {
@@ -32,7 +35,9 @@ class MatchingConstraintsBuilder {
 
         new MatchingConstraints(
                 placeholders: Collections.unmodifiableSet(placeholders),
-                tokenPredicate: tokenPredicate)
+                tokenPredicate: tokenPredicate,
+                eventually: eventually
+        )
     }
 
     def propertyMissing(String name) {
@@ -61,4 +66,17 @@ class MatchingConstraintsBuilder {
         }
         this
     }
+
+    MatchingConstraintsBuilder eventually(@DelegatesTo(value=TreeContext, strategy = Closure.DELEGATE_FIRST) Closure<Boolean> predicate) {
+        def clone = (Closure<Boolean>) predicate.clone()
+        clone.resolveStrategy = Closure.DELEGATE_FIRST
+        eventually = new ConstraintPredicate<TreeContext>() {
+            @Override
+            boolean apply(final TreeContext a) {
+                clone.delegate = a
+                clone.call(a)
+            }
+        }
+        this
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/053af2e4/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 8b5660e..172f457 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -746,4 +746,27 @@ class ASTMatcherTest extends GroovyTestCase {
             assert ast4.matches(pattern)
         }
     }
+
+    void testRelationshipMatching() {
+        use (ASTMatcher) {
+            def ast1 = macro { (a + b) + (a + b ) }
+            def ast2 = macro { (a + b) - (a + b ) }
+            def ast3 = macro { (a - b) + (a - b ) }
+            def ast4 = macro { (a + b) + (a - b ) }
+            def ast5 = macro { (a - b) + (a + b ) }
+            def lhs = macro { a + b }.withConstraints { anyToken() }
+            def rhs = macro { a + b }.withConstraints { anyToken() }
+            def pattern = macro { $v{lhs} + $v{rhs} }.withConstraints {
+                eventually {
+                    node.leftExpression.operation.type == node.rightExpression.operation.type
+                }
+            }
+            assert ast1.matches(pattern)
+            assert !ast2.matches(pattern)
+            assert ast3.matches(pattern)
+            assert !ast4.matches(pattern)
+            assert !ast5.matches(pattern)
+
+        }
+    }
 }


[37/37] incubator-groovy git commit: Merge branch 'macrogroovy'

Posted by cc...@apache.org.
Merge branch 'macrogroovy'


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/c289ed41
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/c289ed41
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/c289ed41

Branch: refs/heads/master
Commit: c289ed4194d6820af7e30e55296f0bd32fdb12fe
Parents: baba6df 9fee024
Author: Cedric Champeau <cc...@apache.org>
Authored: Wed Oct 7 21:25:46 2015 +0200
Committer: Cedric Champeau <cc...@apache.org>
Committed: Wed Oct 7 21:25:46 2015 +0200

----------------------------------------------------------------------
 settings.gradle                                 |    3 +-
 .../groovy/ast/ClassCodeVisitorSupport.java     |    5 -
 .../groovy/ast/MethodCallTransformation.java    |  113 ++
 .../groovy/ast/MethodInvocationTrap.java        |   94 ++
 .../ast/builder/AstBuilderTransformation.java   |  181 +---
 .../codehaus/groovy/ast/tools/ClosureUtils.java |   24 +-
 .../codehaus/groovy/ast/tools/GeneralUtils.java |   39 +
 subprojects/groovy-macro/build.gradle           |   29 +
 .../groovy/macro/matcher/ASTFinder.java         |  427 ++++++++
 .../groovy/macro/matcher/ASTMatcher.groovy      | 1008 ++++++++++++++++++
 .../groovy/macro/matcher/ASTNodePredicate.java  |   25 +
 .../matcher/ContextualClassCodeVisitor.java     |  607 +++++++++++
 .../groovy/macro/matcher/MatcherUtils.java      |   31 +
 .../macro/matcher/MatchingConstraints.groovy    |   43 +
 .../groovy/macro/matcher/NodeComparator.java    |   25 +
 .../groovy/macro/matcher/TreeContext.java       |  145 +++
 .../groovy/macro/matcher/TreeContextAction.java |   23 +
 .../macro/matcher/internal/AnyTokenMatch.groovy |   34 +
 .../matcher/internal/ConstraintPredicate.groovy |   26 +
 .../internal/MatchingConstraintsBuilder.groovy  |   84 ++
 .../groovy/macro/runtime/MacroBuilder.java      |  134 +++
 .../macro/runtime/MacroGroovyMethods.java       |   53 +
 .../macro/runtime/MacroSubstitutionKey.java     |   99 ++
 .../groovy/macro/transform/MacroClass.java      |   22 +
 .../macro/transform/MacroInvocationTrap.java    |  287 +++++
 .../macro/transform/MacroTransformation.java    |   59 +
 .../macro/transform/TransformingMacroTrap.java  |  343 ++++++
 ....codehaus.groovy.transform.ASTTransformation |   17 +
 .../org/codehaus/groovy/macro/MacroTest.groovy  |  189 ++++
 .../groovy/macro/matcher/ASTMatcherTest.groovy  |  774 ++++++++++++++
 30 files changed, 4761 insertions(+), 182 deletions(-)
----------------------------------------------------------------------



[24/37] incubator-groovy git commit: ASTMatcher: Fix matcher of class nodes not checking superclass

Posted by cc...@apache.org.
ASTMatcher: Fix matcher of class nodes not checking superclass


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/4b7db4c1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/4b7db4c1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/4b7db4c1

Branch: refs/heads/master
Commit: 4b7db4c1ea3f229800c2279b38b19b88db9dabeb
Parents: 5a01b99
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 15:27:11 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:11 2015 +0300

----------------------------------------------------------------------
 subprojects/groovy-macro/build.gradle                            | 2 +-
 .../groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy   | 2 ++
 .../org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy      | 4 ++++
 3 files changed, 7 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/4b7db4c1/subprojects/groovy-macro/build.gradle
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/build.gradle b/subprojects/groovy-macro/build.gradle
index 2af7b10..bc9c210 100644
--- a/subprojects/groovy-macro/build.gradle
+++ b/subprojects/groovy-macro/build.gradle
@@ -5,7 +5,7 @@ dependencies {
 }
 
 task moduleDescriptor(type: org.codehaus.groovy.gradle.WriteExtensionDescriptorTask) {
-    extensionClasses = 'org.codehaus.groovy.macro.runtime.MacroGroovyMethods'
+    extensionClasses = 'org.codehaus.groovy.macro.runtime.MacroGroovyMethods,org.codehaus.groovy.macro.matcher.ASTMatcher'
 }
 
 compileJava.dependsOn moduleDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/4b7db4c1/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 5deb80b..0020aeb 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -107,6 +107,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
 
             def cur = (ClassNode) current
+            failIfNot(cur.superClass==node.superClass)
+
             def intfs = node.interfaces
             def curIntfs = cur.interfaces
             failIfNot(intfs.length == curIntfs.length)

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/4b7db4c1/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 78ec60d..9c02e65 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -424,12 +424,16 @@ class ASTMatcherTest extends GroovyTestCase {
         def ast4 = new MacroClass() {
             class B {}
         }
+        def ast5 = new MacroClass() {
+            class A extends B {}
+        }
         assert ast1 instanceof ClassNode
         assert ASTMatcher.matches(ast1, ast1)
         assert ASTMatcher.matches(ast1, ast2)
         assert ASTMatcher.matches(ast2, ast1)
         assert !ASTMatcher.matches(ast1, ast3)
         assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
     }
 
     void testPropertyComparison() {


[34/37] incubator-groovy git commit: tests for MacroGroovy

Posted by cc...@apache.org.
tests for MacroGroovy


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/d486abd3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/d486abd3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/d486abd3

Branch: refs/heads/master
Commit: d486abd3e9778bdca0664b18348b779d8420ab62
Parents: 93a42aa
Author: Sergei Egorov <bs...@gmail.com>
Authored: Tue Mar 17 16:50:48 2015 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:13 2015 +0300

----------------------------------------------------------------------
 .../test/groovy/groovy/SimpleMacroTest.groovy   | 131 -------------
 .../org/codehaus/groovy/macro/MacroTest.groovy  | 187 +++++++++++++++++++
 2 files changed, 187 insertions(+), 131 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/d486abd3/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
deleted file mode 100644
index 9a29fc3..0000000
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2003-2013 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
-
-import groovy.transform.CompileStatic
-import org.codehaus.groovy.ast.ClassHelper
-import org.codehaus.groovy.ast.VariableScope
-import org.codehaus.groovy.ast.builder.AstAssert
-import org.codehaus.groovy.ast.expr.*
-import org.codehaus.groovy.ast.stmt.*
-import org.codehaus.groovy.control.CompilePhase
-
-import static org.codehaus.groovy.ast.expr.VariableExpression.*;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-@CompileStatic
-class SimpleMacroTest extends GroovyTestCase {
-    
-    static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
-    
-    public void testMethod() {
-
-        def someVariable = new VariableExpression("someVariable");
-
-        ReturnStatement result = macro {
-            return new NonExistingClass($v{someVariable});
-        }
-        
-        def expected = new ReturnStatement(new ConstructorCallExpression(ClassHelper.make("NonExistingClass"), new ArgumentListExpression(someVariable)));
-
-        assertSyntaxTree(expected, result);
-    }
-
-    public void testAsIs() {
-        def expected = new BlockStatement([
-                new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
-        ] as List<Statement>, new VariableScope());
-
-        BlockStatement result = macro(true) {
-            println "foo"
-        }
-
-        assertSyntaxTree(expected, result);
-    }
-
-    public void testInception() {
-
-        ConstructorCallExpression result = macro {
-            new NonExistingClass($v{macro {someVariable}});
-        }
-
-        def expected = new ConstructorCallExpression(ClassHelper.make("NonExistingClass"), new ArgumentListExpression(new VariableExpression("someVariable")));
-
-        assertSyntaxTree(expected, result);
-    }
-    
-    public void testMethodName() {
-        // Very useful when you don't want to hardcode method or variable names
-        assertEquals("toLowerCase", TO_LOWER_CASE_METHOD_NAME)
-        assertEquals("valueOf", macro { String.valueOf() }.getMethodAsString())
-    }
-
-    public void testBlock() {
-
-        def result = macro {
-            println "foo"
-            println "bar"
-        }
-
-        def expected = new BlockStatement(
-                [
-                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
-                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
-                ] as List<Statement>,
-                new VariableScope()
-        )
-
-        assertSyntaxTree(expected, result);
-    }
-
-    public void testCompilePhase() {
-
-        def result = macro(CompilePhase.FINALIZATION) {
-            println "foo"
-            println "bar"
-        }
-
-        def expected = new BlockStatement(
-                [
-                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
-                        // In FINALIZATION phase last println will be return statement
-                        new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
-                ] as List<Statement>,
-                new VariableScope()
-        )
-
-        assertSyntaxTree(expected, result);
-    }
-
-    public void testAsIsWithCompilePhase() {
-        def expected = new BlockStatement([
-                new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
-        ] as List<Statement>, new VariableScope());
-
-        def result = macro(CompilePhase.FINALIZATION, true) {
-            println "foo"
-        }
-
-        assertSyntaxTree(expected, result);
-    }
-    
-    protected void assertSyntaxTree(Object expected, Object result) {
-        AstAssert.assertSyntaxTree([expected], [result])
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/d486abd3/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
new file mode 100644
index 0000000..dfff23abb
--- /dev/null
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2003-2015 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 org.codehaus.groovy.macro
+
+import groovy.transform.CompileStatic;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+@CompileStatic
+class MacroTest extends GroovyTestCase {
+    
+    void testSimpleCase() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+        
+        def someVariable = new VariableExpression("someVariable");
+
+        ReturnStatement result = macro {
+            return new NonExistingClass($v{someVariable});
+        }
+        
+        def expected = returnS(ctorX(ClassHelper.make("NonExistingClass"), args(someVariable)))
+
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+    
+    void testAsIs() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+        
+        BlockStatement result = macro(true) {
+            println "foo"
+        }
+        
+        def expected = block(stmt(callThisX("println", args(constX("foo")))))
+
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+    
+    void testInception() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+        
+        ConstructorCallExpression result = macro {
+            new NonExistingClass($v{macro {someVariable}});
+        }
+
+        def expected = ctorX(ClassHelper.make("NonExistingClass"), args(varX("someVariable")))
+
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+
+    void testMethodNameFromCode() {
+        assertScript '''
+        // Very useful when you don't want to hardcode method or variable names
+        assert "toLowerCase" == macro { "".toLowerCase() }.getMethodAsString()
+        assert "valueOf" == macro { String.valueOf() }.getMethodAsString()
+'''
+    }
+    
+    void testBlock() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+        
+        def result = macro {
+            println "foo"
+            println "bar"
+        }
+
+        def expected = block(
+            stmt(callThisX("println", args(constX("foo")))),
+            stmt(callThisX("println", args(constX("bar")))),
+        )
+        
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+    
+    void testCompilePhase() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        import org.codehaus.groovy.control.CompilePhase;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+        
+
+        def result = macro(CompilePhase.FINALIZATION) {
+            println "foo"
+            println "bar"
+        }
+
+        def expected = block(
+            stmt(callThisX("println", args(constX("foo")))),
+            // In FINALIZATION phase last println will be ReturnStatement
+            returnS(callThisX("println", args(constX("bar")))),
+        )
+
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+    
+    void testAsIsWithCompilePhase() {
+        assertScript '''
+        import org.codehaus.groovy.ast.expr.*;
+        import org.codehaus.groovy.ast.stmt.*;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+        import org.codehaus.groovy.control.CompilePhase;
+        
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+
+        def result = macro(CompilePhase.FINALIZATION, true) {
+            println "foo"
+        }
+        
+        def expected = block(
+            returnS(callThisX("println", args(constX("foo"))))
+        )
+        
+        AstAssert.assertSyntaxTree([expected], [result]);
+'''
+    }
+    
+    void testCompileStatic() {
+        assertScript '''
+        import groovy.transform.CompileStatic
+        import org.codehaus.groovy.ast.stmt.ReturnStatement;
+        import org.codehaus.groovy.ast.ClassHelper;
+        import org.codehaus.groovy.ast.builder.AstAssert;
+
+        import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
+
+        @CompileStatic
+        ReturnStatement getReturnStatement() {
+            return macro {
+                return new NonExistingClass("foo");
+            }
+        }
+        
+        def expected = returnS(ctorX(ClassHelper.make("NonExistingClass"), args(constX("foo"))))
+
+        AstAssert.assertSyntaxTree([expected], [getReturnStatement()]);
+'''
+    }
+}


[30/37] incubator-groovy git commit: ASTMatcher: Add constraints to pattern matching * work in progress: add a MatchingConstraints class corresponding to the constraints being applied to the pattern * constraints are defined using a DSL called thro

Posted by cc...@apache.org.
ASTMatcher: Add constraints to pattern matching
   * work in progress: add a MatchingConstraints class corresponding to the constraints being applied to the pattern
   * constraints are defined using a DSL called through the ASTMatcher.withConstraints method
   * rename some parameters in ASTMatcher to improve readability of algorithms


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/bcd68a75
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/bcd68a75
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/bcd68a75

Branch: refs/heads/master
Commit: bcd68a75c6909820faf2f7a19b8068613f3e93de
Parents: cd39e26
Author: Cedric Champeau <ce...@gmail.com>
Authored: Sat Oct 18 10:40:54 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:12 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 101 +++++++++++++++----
 .../matcher/ContextualClassCodeVisitor.java     |   3 +-
 .../macro/matcher/MatchingConstraints.groovy    |  56 ++++++++++
 .../groovy/macro/matcher/TreeContext.java       |  23 ++++-
 .../groovy/macro/matcher/ASTMatcherTest.groovy  |  38 +++++++
 5 files changed, 199 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bcd68a75/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 5b5dc8e..727f39e 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -29,7 +29,7 @@ import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
 
 @CompileStatic
-class ASTMatcher extends ClassCodeVisitorSupport {
+class ASTMatcher extends ContextualClassCodeVisitor {
 
     public static final String WILDCARD = "_";
 
@@ -67,8 +67,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         match = match && value
     }
 
-    private static boolean matchByName(String potentialWildcard, String node) {
-        return node.equals(potentialWildcard) || WILDCARD.equals(potentialWildcard);
+    private static boolean matchByName(String patternText, String nodeText) {
+        return nodeText.equals(patternText) || WILDCARD.equals(patternText);
     }
 
     private static boolean isWildcardExpression(Object exp) {
@@ -91,21 +91,63 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         finder.matches
     }
 
-    private void doWithNode(Object search, Object next, Closure cl) {
-        Class expectedClass = search?search.class:Object
+    private void storeContraints(ASTNode src) {
+        def constraints = src.getNodeMetaData(MatchingConstraints)
+        if (constraints) {
+            treeContext.putUserdata(MatchingConstraints, constraints)
+        }
+    }
+
+    private String findPlaceholder(Object exp) {
+        def constraints = (List<MatchingConstraints>) treeContext.getUserdata(MatchingConstraints, true)
+        if (constraints) {
+            def placeholders = constraints[0].placeholders
+            if ((exp instanceof VariableExpression && placeholders.contains(exp.name))) {
+                return exp.name
+            }
+            if ((exp instanceof ConstantExpression && placeholders.contains(exp.value))) {
+                return exp.value
+            }
+        }
+        null
+    }
+
+    private void doWithNode(Object patternNode, Object foundNode, Closure cl) {
+        Class expectedClass = patternNode?patternNode.class:Object
         if (expectedClass == null) {
             expectedClass = Object
         }
-        if (isWildcardExpression(search)) {
-            return
+
+        boolean doPush = treeContext.node!=foundNode && foundNode instanceof ASTNode
+        if (doPush) {
+            if (patternNode instanceof ASTNode) {
+                storeContraints(patternNode)
+            }
+            pushContext((ASTNode)foundNode)
         }
-        if (match && (next == null || expectedClass.isAssignableFrom(next.class))) {
-            Object old = current
-            current = next
-            cl()
-            current = old
-        } else {
-            failIfNot(false)
+
+        if (!isWildcardExpression(patternNode)) {
+            String placeholder = findPlaceholder(patternNode)
+            if (placeholder) {
+                def alreadySeenAST = treeContext.getUserdata("placeholder_$placeholder", true)
+                if (!alreadySeenAST) {
+                    treeContext.parent.putUserdata("placeholder_$placeholder", foundNode)
+                } else {
+                    // during the tree inspection, placeholder already found
+                    // so we need to check that they are identical
+                    failIfNot(matches((ASTNode)alreadySeenAST[0], (ASTNode)foundNode))
+                }
+            } else if (match && (foundNode == null || expectedClass.isAssignableFrom(foundNode.class))) {
+                Object old = current
+                current = foundNode
+                cl()
+                current = old
+            } else {
+                failIfNot(false)
+            }
+        }
+        if (doPush) {
+            popContext()
         }
     }
 
@@ -461,10 +503,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitConstructorCallExpression(final ConstructorCallExpression call) {
-        def cur = (ConstructorCallExpression) current
-        doWithNode(call.arguments, cur.arguments) {
-            call.arguments.visit(this)
-            failIfNot(call.type == cur.type)
+        doWithNode(call, current) {
+            def cur = (ConstructorCallExpression) current
+            doWithNode(call.arguments, cur.arguments) {
+                call.arguments.visit(this)
+                failIfNot(call.type == cur.type)
+            }
         }
     }
 
@@ -913,4 +957,25 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
         }
     }
+
+    /**
+     * // todo: experimental!
+     *
+     * Annotates an AST node with matching contraints. This method should be called
+     * on an AST intended to be used as a pattern only. It will put node metadata on
+     * the AST node allowing customized behavior in pattern matching.
+     *
+     * @param pattern a pattern AST
+     * @param constraintsSpec a closure specification of matching constraints
+     * @return the same pattern, annotated with constraints
+     */
+    public static ASTNode withConstraints(
+            final ASTNode pattern,
+            final @DelegatesTo(value=MatchingConstraints.Builder, strategy=Closure.DELEGATE_ONLY) Closure constraintsSpec) {
+        def builder = new MatchingConstraints.Builder()
+        def constraints = builder.build(constraintsSpec)
+        pattern.putNodeMetaData(MatchingConstraints, constraints)
+
+        pattern
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bcd68a75/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
index babd3e3..a8f0e40 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
@@ -107,7 +107,8 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
                     return super.transform(exp);
                 }
             };
-            parentNode.visit(trn);
+            // todo: reliable way to call the transformer
+            //parentNode.visit(trn);
         }
         return treeContext;
     }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bcd68a75/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
new file mode 100644
index 0000000..82306c0
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
+
+import groovy.transform.CompileStatic
+import groovy.transform.PackageScope
+
+/**
+ * Represents constraints in AST pattern matching.
+ *
+ * @author Cedric Champeau
+ * @since 2.4.0
+ */
+@CompileStatic
+class MatchingConstraints {
+    final Set<String> placeholders = new LinkedHashSet<>()
+
+    @PackageScope static class Builder {
+        private final MatchingConstraints constraints = new MatchingConstraints()
+
+        MatchingConstraints build(@DelegatesTo(value=Builder, strategy=Closure.DELEGATE_ONLY) Closure spec) {
+            def clone = (Closure) spec.clone()
+            clone.delegate = this
+            clone.resolveStrategy = Closure.DELEGATE_ONLY
+            clone()
+
+            constraints
+        }
+
+        def getProperty(String name) {
+            if ('constraints'==name) {
+                return constraints
+            }
+            name
+        }
+
+        Builder placeholder(String... names) {
+            names.each { String it -> constraints.placeholders.add(it) }
+            this
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bcd68a75/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
index 6020592..4644555 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
@@ -53,10 +53,23 @@ public class TreeContext {
         }
     }
 
-    public Map<?, ?> getUserdata() {
+    public Map<?, List<?>> getUserdata() {
         return userdata;
     }
 
+    public void putUserdata(Object key, Object value) {
+        ((List)userdata.get(key)).add(value);
+    }
+
+    public List<?> getUserdata(Object key, boolean searchParent) {
+        if (userdata.containsKey(key)) {
+            return userdata.get(key);
+        } else if (parent!=null && searchParent) {
+            return parent.getUserdata(key, true);
+        }
+        return null;
+    }
+
     public TreeContext getParent() { return parent; }
     public ASTNode getNode() { return node; }
 
@@ -104,13 +117,13 @@ public class TreeContext {
     @Override
     public String toString() {
         final StringBuilder sb = new StringBuilder("TreeContext{");
-        sb.append("node=").append(node!=null?node.getClass().getSimpleName():"undefined");
+        sb.append("node=").append(dumpNode());
         TreeContext p = parent;
         if (p!=null) {
             sb.append(", path=");
         }
         while (p!=null) {
-            sb.append(p.node!=null?p.node.getClass().getSimpleName():"undefined");
+            sb.append(p.dumpNode());
             sb.append("<-");
             p = p.parent;
         }
@@ -118,4 +131,8 @@ public class TreeContext {
         sb.append('}');
         return sb.toString();
     }
+
+    private String dumpNode() {
+        return node!=null?node.getClass().getSimpleName():"undefined";
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bcd68a75/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 63d4a9a..9802a2a 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -616,4 +616,42 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast2, ast1)
         assert !ASTMatcher.matches(ast1, ast3)
     }
+
+    void testConstrainedMatcher() {
+        def ast = macro { a+foo(b) }
+        def pattern = macro {
+            a+b
+        }
+        ASTMatcher.withConstraints(pattern) {
+            placeholder a,b
+        }
+        assert ASTMatcher.matches(ast, pattern)
+    }
+
+    void testPlaceholdersMustMatch() {
+        def ast1 = macro { foo(a)+foo(a) }
+        def ast2 = macro { foo(a)+foo(b) }
+        def pattern = macro {
+            x+x
+        }
+        ASTMatcher.withConstraints(pattern) {
+            placeholder x
+        }
+        assert ASTMatcher.matches(ast1, pattern)
+        assert !ASTMatcher.matches(ast2, pattern)
+    }
+
+    void testPlaceholdersMustMatch2() {
+        use(ASTMatcher) {
+            def ast1 = macro { foo(a) + foo(a) }
+            def ast2 = macro { foo(a) + foo(foo(a)) }
+            def pattern = macro {
+                x + foo(x)
+            }.withConstraints {
+                placeholder x
+            }
+            assert !ast1.matches(pattern)
+            assert ast2.matches(pattern)
+        }
+    }
 }


[19/37] incubator-groovy git commit: ASTMatcher: Fix visitListExpression implentation

Posted by cc...@apache.org.
ASTMatcher: Fix visitListExpression implentation


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/817bbef3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/817bbef3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/817bbef3

Branch: refs/heads/master
Commit: 817bbef37672228eefe6c93fd557613b51686f27
Parents: bac61a1
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 13:10:44 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../codehaus/groovy/macro/matcher/ASTMatcher.groovy    | 13 ++-----------
 1 file changed, 2 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/817bbef3/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 9158c32..7b5262c 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -815,17 +815,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         def iter = currentExprs.iterator()
         for (Expression expression : list) {
             def next = iter.next()
-            if (expression instanceof SpreadExpression) {
-                doWithNode(SpreadExpression, next) {
-                    Expression spread = ((SpreadExpression) expression).getExpression()
-                    doWithNode(Expression, ((SpreadExpression) current).expression) {
-                        spread.visit(this)
-                    }
-                }
-            } else {
-                doWithNode(Expression, next) {
-                    expression.visit(this)
-                }
+            doWithNode(expression.class, next) {
+                expression.visit(this)
             }
         }
     }


[22/37] incubator-groovy git commit: ASTMatcher: Add support for for loop

Posted by cc...@apache.org.
ASTMatcher: Add support for for loop


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/199187e1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/199187e1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/199187e1

Branch: refs/heads/master
Commit: 199187e1cd539eed62f1a00f70b4f5650c053255
Parents: 8c1f263
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 13:47:25 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:11 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 24 +++++++++++++++++++-
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 18 +++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/199187e1/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index d715737..7c3b68f 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -22,6 +22,7 @@ import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.BlockStatement
 import org.codehaus.groovy.ast.stmt.EmptyStatement
 import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.ast.stmt.ForStatement
 import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.ast.stmt.Statement
 import org.codehaus.groovy.classgen.BytecodeExpression
@@ -830,7 +831,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitClosureListExpression(final ClosureListExpression cle) {
-        super.visitClosureListExpression(cle);
+        doWithNode(ClosureListExpression, current) {
+            def exprs = cle.expressions
+            doWithNode(exprs.class, ((ClosureListExpression)current).expressions) {
+                visitListOfExpressions(exprs)
+            }
+        }
     }
 
     @Override
@@ -858,4 +864,20 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
         }
     }
+
+    @Override
+    void visitForLoop(final ForStatement forLoop) {
+        doWithNode(ForStatement, current) {
+            visitStatement(forLoop)
+            def cur = (ForStatement) current
+            def col = forLoop.collectionExpression
+            def block = forLoop.loopBlock
+            doWithNode(col.class, cur.collectionExpression) {
+                col.visit(this)
+            }
+            doWithNode(block.class, cur.loopBlock) {
+                block.visit(this)
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/199187e1/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index eec19b9..75ca21c 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -26,6 +26,7 @@ import org.codehaus.groovy.ast.expr.MethodPointerExpression
 import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
 import org.codehaus.groovy.ast.expr.UnaryMinusExpression
 import org.codehaus.groovy.ast.expr.UnaryPlusExpression
+import org.codehaus.groovy.ast.stmt.ForStatement
 import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.control.CompilePhase
 import org.codehaus.groovy.macro.transform.MacroClass
@@ -537,4 +538,21 @@ class ASTMatcherTest extends GroovyTestCase {
         assert ASTMatcher.matches(ast6, ast7)
         assert !ASTMatcher.matches(ast7, ast8)
     }
+
+    void testForLoop() {
+        def ast1 = macro { for (;;) {} }
+        def ast2 = macro { for (;;) {} }
+        def ast3 = macro { for (int i=0;i<10;i++) {} }
+        def ast4 = macro { for (long i=0;i<10;i++) {} }
+        def ast5 = macro { for (int i=0;i<100;i++) {} }
+        def ast6 = macro { for (int i=0;i<10;i++) { a } }
+        assert ast1 instanceof ForStatement
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast3, ast4)
+        assert !ASTMatcher.matches(ast3, ast5)
+        assert !ASTMatcher.matches(ast3, ast6)
+    }
 }


[08/37] incubator-groovy git commit: Add some closure variants for nicer DSL

Posted by cc...@apache.org.
Add some closure variants for nicer DSL


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/7704cf90
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/7704cf90
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/7704cf90

Branch: refs/heads/master
Commit: 7704cf90379790d59db8917c4ed38b8052518cb6
Parents: a522e8f
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Oct 15 10:08:33 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:05 2015 +0300

----------------------------------------------------------------------
 .../groovy/ast/ContextualClassCodeVisitor.java  | 63 +++++++++++++++++++-
 1 file changed, 60 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/7704cf90/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java b/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
index 742cb72..360a91e 100644
--- a/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
+++ b/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
@@ -16,6 +16,7 @@
 package org.codehaus.groovy.ast;
 
 import groovy.lang.Closure;
+import groovy.lang.DelegatesTo;
 import groovy.lang.MapWithDefault;
 import org.codehaus.groovy.ast.expr.*;
 import org.codehaus.groovy.ast.stmt.AssertStatement;
@@ -36,6 +37,8 @@ import org.codehaus.groovy.ast.stmt.ThrowStatement;
 import org.codehaus.groovy.ast.stmt.TryCatchStatement;
 import org.codehaus.groovy.ast.stmt.WhileStatement;
 import org.codehaus.groovy.classgen.BytecodeExpression;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.runtime.DefaultGroovyMethods;
 
 import java.util.ArrayDeque;
 import java.util.ArrayList;
@@ -72,12 +75,33 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
     }
 
     protected TreeContext popContext() {
-        TreeContext treeContext = treeContextStack.pop();
+        final TreeContext treeContext = treeContextStack.pop();
         List<TreeContextAction> actions = treeContext.getOnPopHandlers();
         for (TreeContextAction contextAction : actions) {
             contextAction.call(treeContext);
         }
         lastContext = treeContext;
+        ASTNode parentNode = treeContext.parent!=null?treeContext.parent.node:null;
+        if (treeContext.node instanceof Expression && parentNode !=null) {
+            ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
+                @Override
+                protected SourceUnit getSourceUnit() {
+                    return null;
+                }
+
+                @Override
+                public Expression transform(final Expression exp) {
+                    if (exp==treeContext.node) {
+                        Expression replacement = treeContext.getReplacement();
+                        if (replacement!=null) {
+                            return replacement;
+                        }
+                    }
+                    return super.transform(exp);
+                }
+            };
+            parentNode.visit(trn);
+        }
         return treeContext;
     }
 
@@ -485,6 +509,14 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
         popContext();
     }
 
+    @SuppressWarnings("unchecked")
+    private static <T> Closure<T> cloneWithDelegate(final Closure<T> predicate, final Object delegate) {
+        Closure<T> clone = (Closure<T>) predicate.clone();
+        clone.setDelegate(delegate);
+        clone.setResolveStrategy(Closure.DELEGATE_FIRST);
+        return clone;
+    }
+
     public List<TreeContext> getTreePath() {
         List<TreeContext> path = new LinkedList<TreeContext>();
         path.add(lastContext);
@@ -493,6 +525,7 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
         }
         return path;
     }
+
     public List<TreeContext> pathMatches(List<ASTNodePredicate> predicates) {
         List<TreeContext> path = new LinkedList<TreeContext>();
         TreeContext current = lastContext.parent;
@@ -549,14 +582,17 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
     // ----------------------------- inner classes --------------------------------------
 
     public static class TreeContext {
+        private static enum TreeContextKey {
+            expression_replacement
+        }
         final TreeContext parent;
         final ASTNode node;
         final List<TreeContext> siblings = new LinkedList<TreeContext>();
         final List<TreeContextAction> onPopHandlers = new LinkedList<TreeContextAction>();
-        final Map<?, List<?>> userdata = MapWithDefault.newInstance(
+        final Map<Object, List<?>> userdata = MapWithDefault.newInstance(
                 new HashMap<Object, List<?>>(),
                 new Closure(this) {
-                    public Object doCall(String key) {
+                    public Object doCall(Object key) {
                         return new LinkedList<Object>();
                     }
                 }
@@ -585,6 +621,10 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
             return predicate.matches(node);
         }
 
+        public boolean matches(@DelegatesTo(value=ASTNode.class, strategy=Closure.DELEGATE_FIRST) Closure<Boolean> predicate) {
+            return cloneWithDelegate(predicate, node).call();
+        }
+
         public List<TreeContext> getSiblings() {
             return Collections.unmodifiableList(siblings);
         }
@@ -597,6 +637,23 @@ public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport
             onPopHandlers.add(action);
         }
 
+        public void afterVisit(@DelegatesTo(value=TreeContext.class, strategy=Closure.DELEGATE_FIRST) Closure<?> action) {
+            Closure<?> clone = cloneWithDelegate(action, this);
+            afterVisit(DefaultGroovyMethods.asType(clone, TreeContextAction.class));
+        }
+
+        public void setReplacement(Expression replacement) {
+            userdata.put(TreeContextKey.expression_replacement, Collections.singletonList(replacement));
+        }
+
+        public Expression getReplacement() {
+            List<?> list = userdata.get(TreeContextKey.expression_replacement);
+            if (list.size()==1) {
+                return (Expression) list.get(0);
+            }
+            return null;
+        }
+
         @Override
         public String toString() {
             final StringBuilder sb = new StringBuilder("TreeContext{");


[07/37] incubator-groovy git commit: more "macro" usage examples in SimpleMacroTest

Posted by cc...@apache.org.
more "macro" usage examples in SimpleMacroTest


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/ff1d4a0e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/ff1d4a0e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/ff1d4a0e

Branch: refs/heads/master
Commit: ff1d4a0e73fb724816d9b9bf07e585888c42c7ba
Parents: 546868a
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:21:15 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:04 2015 +0300

----------------------------------------------------------------------
 .../src/test/groovy/groovy/SimpleMacroTest.groovy           | 9 +++++++++
 1 file changed, 9 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/ff1d4a0e/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index df46802..64bb1bf 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -30,6 +30,9 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.*;
  */
 @CompileStatic
 class SimpleMacroTest extends GroovyShellTestCase {
+    
+    static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
+    
     public void testMethod() {
 
         def someVariable = new VariableExpression("someVariable");
@@ -65,6 +68,12 @@ class SimpleMacroTest extends GroovyShellTestCase {
 
         assertSyntaxTree(expected, result);
     }
+    
+    public void testMethodName() {
+        // Very useful when you don't want to hardcode method or variable names
+        assertEquals("toLowerCase", TO_LOWER_CASE_METHOD_NAME)
+        assertEquals("valueOf", macro { String.valueOf() }.getMethodAsString())
+    }
 
     public void testBlock() {
 


[04/37] incubator-groovy git commit: shared code between MacroGroovy and AstBuilderTransformation

Posted by cc...@apache.org.
shared code between MacroGroovy and AstBuilderTransformation


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/df5fa06e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/df5fa06e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/df5fa06e

Branch: refs/heads/master
Commit: df5fa06ee6ce3212a4c98b6cae13c6c4a6b6dec5
Parents: 2056035
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 12:45:29 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:04 2015 +0300

----------------------------------------------------------------------
 .../macro/transform/MacroInvocationTrap.java    | 148 ++++++-------------
 .../macro/transform/MacroTransformation.java    |  41 +----
 2 files changed, 54 insertions(+), 135 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/df5fa06e/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index 7ac10df..b082e8b 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -15,18 +15,15 @@
  */
 package org.codehaus.groovy.macro.transform;
 
-import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.ast.CodeVisitorSupport;
+import org.codehaus.groovy.ast.MethodInvocationTrap;
 import org.codehaus.groovy.ast.expr.*;
 import org.codehaus.groovy.ast.stmt.BlockStatement;
-import org.codehaus.groovy.ast.tools.ClosureUtils;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
 import org.codehaus.groovy.macro.runtime.MacroBuilder;
 import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
-import org.codehaus.groovy.syntax.SyntaxException;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -37,106 +34,73 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
-public class MacroInvocationTrap {
-
-    private final ReaderSource source;
-    private final SourceUnit sourceUnit;
-
-    /**
-     * Creates the trap and captures all macro method calls.
-     *
-     * @param source         the reader source that contains source for the SourceUnit
-     * @param sourceUnit     the source unit being compiled. Used for error messages.
-     */
-    MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
-        if (source == null) throw new IllegalArgumentException("Null: source");
-        if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
-        this.source = source;
-        this.sourceUnit = sourceUnit;
-    }
+public class MacroInvocationTrap extends MethodInvocationTrap {
 
-    /**
-     * Reports an error back to the source unit.
-     *
-     * @param msg  the error message
-     * @param expr the expression that caused the error message.
-     */
-    private void addError(String msg, ASTNode expr) {
-        sourceUnit.getErrorCollector().addErrorAndContinue(
-                new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
-        );
+    public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        super(source, sourceUnit);
     }
 
-    /**
-     * Attempts to find 'macro' invocations. When found, converts them into calls
-     * to the 'from string' approach.
-     *
-     * @param macroCall the method call expression that may or may not be a 'macro' invocation.
-     */
-    public void visitMethodCallExpression(final MethodCallExpression macroCall) {
-
-        if (!isBuildInvocation(macroCall, MacroTransformation.MACRO_METHOD)) {
-            return;
-        }
-
+    @Override
+    protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
         final ClosureExpression closureExpression = getClosureArgument(macroCall);
-        
+
         if(closureExpression == null) {
-            return;
+            return true;
         }
 
         if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
             addError("Macro closure arguments are not allowed", closureExpression);
+            return true;
         }
-        
+
         final MapExpression mapExpression = new MapExpression();
-        
+
         (new CodeVisitorSupport() {
             @Override
             public void visitMethodCallExpression(MethodCallExpression call) {
                 super.visitMethodCallExpression(call);
-                
+
                 if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
                     ClosureExpression substitutionClosureExpression = getClosureArgument(call);
-                    
+
                     if(substitutionClosureExpression == null) {
                         return;
                     }
 
                     MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
-                    
+
                     mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
                 }
             }
         }).visitClosureExpression(closureExpression);
-        
-        String source = convertClosureToSource(this.source, closureExpression);
+
+        String source = convertClosureToSource(closureExpression);
 
         BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
-        
+
         Boolean asIs = false;
-        
+
         TupleExpression macroArguments = getMacroArguments(macroCall);
-        
+
         if(macroArguments == null) {
-            return;
+            return true;
         }
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
-        
+
         if(macroArgumentsExpressions.size() > 1) {
             Expression firstArgument = macroArgumentsExpressions.get(0);
-            
+
             if(!(firstArgument instanceof ConstantExpression)) {
                 addError("AsIs argument value should be constant(true or false)", firstArgument);
-                return;
+                return true;
             }
-            
+
             ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
-            
+
             if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
                 addError("AsIs argument value should be boolean", asIsConstantExpression);
-                return;
+                return true;
             }
 
             asIs = (Boolean) asIsConstantExpression.getValue();
@@ -153,6 +117,29 @@ public class MacroInvocationTrap {
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);
         macroCall.setImplicitThis(false);
+        
+        return true;
+    }
+
+    @Override
+    protected boolean isBuildInvocation(MethodCallExpression call) {
+        return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
+    }
+
+    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
+        if (call == null) throw new IllegalArgumentException("Null: call");
+        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+
+        if(!(call.getMethod() instanceof ConstantExpression)) {
+            return false;
+        }
+
+        if(!(methodName.equals(call.getMethodAsString()))) {
+            return false;
+        }
+
+        // is method object correct type?
+        return call.getObjectExpression() == THIS_EXPRESSION;
     }
     
     protected TupleExpression getMacroArguments(MethodCallExpression call) {
@@ -193,41 +180,4 @@ public class MacroInvocationTrap {
 
         return (ClosureExpression) result;
     }
-
-    /**
-     * Looks for 'macro' method calls.
-     *
-     * @param call the method call expression, may not be null
-     */
-    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
-        if (call == null) throw new IllegalArgumentException("Null: call");
-        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
-        
-        if(!(call.getMethod() instanceof ConstantExpression)) {
-            return false;
-        }
-        
-        if(!(methodName.equals(call.getMethodAsString()))) {
-            return false;
-        }
-
-        // is method object correct type?
-        return call.getObjectExpression() == THIS_EXPRESSION;
-    }
-
-    /**
-     * Converts a ClosureExpression into the String source.
-     *
-     * @param expression a closure
-     * @return the source the closure was created from
-     */
-    private String convertClosureToSource(ReaderSource source, ClosureExpression expression) {
-
-        try {
-            return ClosureUtils.convertClosureToSource(source, expression);
-        } catch (Exception e) {
-            addError(e.getMessage(), expression);
-        }
-        return null;
-    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/df5fa06e/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
index cdf0f07..65284b5 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -15,56 +15,25 @@
  */
 package org.codehaus.groovy.macro.transform;
 
-import org.codehaus.groovy.ast.ASTNode;
-import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
-import org.codehaus.groovy.ast.ClassNode;
-import org.codehaus.groovy.ast.ModuleNode;
-import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.*;
 import org.codehaus.groovy.control.CompilePhase;
 import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.transform.ASTTransformation;
 import org.codehaus.groovy.transform.GroovyASTTransformation;
 
 /**
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
+
 @GroovyASTTransformation(phase = CompilePhase.CONVERSION)
-public class MacroTransformation extends ClassCodeVisitorSupport implements ASTTransformation {
+public class MacroTransformation extends MethodCallTransformation {
 
     public static final String DOLLAR_VALUE = "$v";
     public static final String MACRO_METHOD = "macro";
 
-    SourceUnit source;
-    
-    MacroInvocationTrap transformer;
-
-    public void visit(ASTNode[] nodes, SourceUnit source) {
-        this.source = source;
-
-        transformer = new MacroInvocationTrap(source.getSource(), source);
-
-        for(ASTNode node : nodes) {
-            if(node instanceof ClassNode) {
-                visitClass((ClassNode) node);
-            } else if(node instanceof ModuleNode) {
-                ModuleNode moduleNode = (ModuleNode) node;
-                for (ClassNode classNode : moduleNode.getClasses()) {
-                    visitClass(classNode);
-                }
-            }
-        }
-    }
-
-    @Override
-    public void visitMethodCallExpression(MethodCallExpression call) {
-        transformer.visitMethodCallExpression(call);
-        super.visitMethodCallExpression(call);
-    }
-
     @Override
-    protected SourceUnit getSourceUnit() {
-        return source;
+    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
+        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
     }
 }
 


[15/37] incubator-groovy git commit: Add support for generating classes through a MacroClass block * instead of using def ast = macro { class A {} }, use def ast=new MacroClass() { class A{} } * substitutions broken due to incorrect scoping of the

Posted by cc...@apache.org.
Add support for generating classes through a MacroClass block
   * instead of using def ast = macro { class A {} }, use def ast=new MacroClass() { class A{} }
   * substitutions broken due to incorrect scoping of the closure expression representing the substitution


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/09758c34
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/09758c34
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/09758c34

Branch: refs/heads/master
Commit: 09758c34899f09285c8333e20f4e855ab28de2e6
Parents: 248e0fd
Author: Cedric Champeau <ce...@gmail.com>
Authored: Thu Oct 16 12:09:25 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:03 2015 +0300

----------------------------------------------------------------------
 .../codehaus/groovy/ast/tools/ClosureUtils.java |  24 +-
 .../codehaus/groovy/ast/tools/GeneralUtils.java |  39 +++
 .../groovy/macro/runtime/MacroBuilder.java      |  69 ++--
 .../groovy/macro/transform/MacroClass.java      |  19 ++
 .../macro/transform/MacroInvocationTrap.java    | 160 ++++++---
 .../macro/transform/MacroTransformation.java    |  22 +-
 .../macro/transform/TransformingMacroTrap.java  | 340 +++++++++++++++++++
 7 files changed, 585 insertions(+), 88 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/src/main/org/codehaus/groovy/ast/tools/ClosureUtils.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/tools/ClosureUtils.java b/src/main/org/codehaus/groovy/ast/tools/ClosureUtils.java
index c13c31c..06d4995 100644
--- a/src/main/org/codehaus/groovy/ast/tools/ClosureUtils.java
+++ b/src/main/org/codehaus/groovy/ast/tools/ClosureUtils.java
@@ -37,32 +37,10 @@ public class ClosureUtils {
      * @throws java.lang.Exception when closure can't be read from source
      */
     public static String convertClosureToSource(ReaderSource readerSource, ClosureExpression expression) throws Exception {
-        if (expression == null) throw new IllegalArgumentException("Null: expression");
-
-        StringBuilder result = new StringBuilder();
-        for (int x = expression.getLineNumber(); x <= expression.getLastLineNumber(); x++) {
-            String line = readerSource.getLine(x, null);
-            if (line == null) {
-                throw new Exception(
-                        "Error calculating source code for expression. Trying to read line " + x + " from " + readerSource.getClass()
-                );
-            }
-            if (x == expression.getLastLineNumber()) {
-                line = line.substring(0, expression.getLastColumnNumber() - 1);
-            }
-            if (x == expression.getLineNumber()) {
-                line = line.substring(expression.getColumnNumber() - 1);
-            }
-            //restoring line breaks is important b/c of lack of semicolons
-            result.append(line).append('\n');
-        }
-
-
-        String source = result.toString().trim();
+        String source = GeneralUtils.convertASTToSource(readerSource, expression);
         if (!source.startsWith("{")) {
             throw new Exception("Error converting ClosureExpression into source code. Closures must start with {. Found: " + source);
         }
-
         return source;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
index ce4b19e..9d8508f 100644
--- a/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -18,6 +18,7 @@
  */
 package org.codehaus.groovy.ast.tools;
 
+import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.AnnotatedNode;
 import org.codehaus.groovy.ast.AnnotationNode;
 import org.codehaus.groovy.ast.ClassHelper;
@@ -53,6 +54,7 @@ import org.codehaus.groovy.ast.stmt.IfStatement;
 import org.codehaus.groovy.ast.stmt.ReturnStatement;
 import org.codehaus.groovy.ast.stmt.Statement;
 import org.codehaus.groovy.classgen.Verifier;
+import org.codehaus.groovy.control.io.ReaderSource;
 import org.codehaus.groovy.runtime.GeneratedClosure;
 import org.codehaus.groovy.runtime.MetaClassHelper;
 import org.codehaus.groovy.syntax.Token;
@@ -680,4 +682,41 @@ public class GeneralUtils {
         }
         return propX(receiver, pNode.getName());
     }
+
+    /**
+     * Converts an expression into the String source. Only some specific expressions like closure expression
+     * support this.
+     *
+     * @param readerSource a source
+     * @param expression an expression. Can't be null
+     * @return the source the closure was created from
+     * @throws java.lang.IllegalArgumentException when expression is null
+     * @throws java.lang.Exception when closure can't be read from source
+     */
+    public static String convertASTToSource(ReaderSource readerSource, ASTNode expression) throws Exception {
+        if (expression == null) throw new IllegalArgumentException("Null: expression");
+
+        StringBuilder result = new StringBuilder();
+        for (int x = expression.getLineNumber(); x <= expression.getLastLineNumber(); x++) {
+            String line = readerSource.getLine(x, null);
+            if (line == null) {
+                throw new Exception(
+                        "Error calculating source code for expression. Trying to read line " + x + " from " + readerSource.getClass()
+                );
+            }
+            if (x == expression.getLastLineNumber()) {
+                line = line.substring(0, expression.getLastColumnNumber() - 1);
+            }
+            if (x == expression.getLineNumber()) {
+                line = line.substring(expression.getColumnNumber() - 1);
+            }
+            //restoring line breaks is important b/c of lack of semicolons
+            result.append(line).append('\n');
+        }
+
+
+        String source = result.toString().trim();
+
+        return source;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index ae82081..1edbcba 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -18,6 +18,7 @@ package org.codehaus.groovy.macro.runtime;
 import groovy.lang.Closure;
 import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.ast.builder.AstBuilder;
 import org.codehaus.groovy.ast.expr.Expression;
 import org.codehaus.groovy.ast.expr.MethodCallExpression;
@@ -53,46 +54,64 @@ public enum MacroBuilder {
 
     @SuppressWarnings("unchecked")
     public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
+        boolean isClosure = source.startsWith("{");
+        final String label = isClosure ?"__synthesized__label__" + System.currentTimeMillis() + "__:":"";
         final String labelledSource = label + source;
         final int linesOffset = 1;
-        final int columnsOffset = label.length() + 1; // +1 because of {
-        
+        final int columnsOffset = label.length() + (isClosure?1:0); // +1 because of {
+
         List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
 
         for(ASTNode node : nodes) {
             if (node instanceof BlockStatement) {
 
-                BlockStatement closureBlock = (BlockStatement) ((BlockStatement)node).getStatements().get(0);
+                List<Statement> statements = ((BlockStatement) node).getStatements();
+                if (!statements.isEmpty()) {
+                    BlockStatement closureBlock = (BlockStatement) statements.get(0);
 
-                (new ClassCodeExpressionTransformer() {
-                    public Expression transform(Expression expression) {
-                        if(!(expression instanceof MethodCallExpression)) {
-                            return super.transform(expression);
-                        }
+                    performSubstitutions(linesOffset, columnsOffset, context, closureBlock);
 
-                        MethodCallExpression call = (MethodCallExpression) expression;
 
-                        if(!MacroInvocationTrap.isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
-                            return super.transform(expression);
-                        }
+                    return (T) getMacroValue(closureBlock, asIs);
+                }
+            }
+            if (node instanceof ClassNode) {
+                performSubstitutions(linesOffset, columnsOffset, context, node);
+                return (T) node;
+            }
+        }
+        return null;
+    }
 
-                        MacroSubstitutionKey key = new MacroSubstitutionKey(call, linesOffset, columnsOffset);
-                        
-                        return context.get(key).call();
-                    }
+    private void performSubstitutions(final int linesOffset, final int columnsOffset, final Map<MacroSubstitutionKey, Closure<Expression>> context, final ASTNode astNode) {
+        ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
+            public Expression transform(Expression expression) {
+                if (!(expression instanceof MethodCallExpression)) {
+                    return super.transform(expression);
+                }
 
-                    @Override
-                    protected SourceUnit getSourceUnit() {
-                        // Could be null if there are no errors
-                        return null;
-                    }
-                }).visitBlockStatement(closureBlock);
+                MethodCallExpression call = (MethodCallExpression) expression;
 
-                return (T) getMacroValue(closureBlock, asIs);
+                if (!MacroInvocationTrap.isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                    return super.transform(expression);
+                }
+
+                MacroSubstitutionKey key = new MacroSubstitutionKey(call, linesOffset, columnsOffset);
+
+                return context.get(key).call();
             }
+
+            @Override
+            protected SourceUnit getSourceUnit() {
+                // Could be null if there are no errors
+                return null;
+            }
+        };
+        if (astNode instanceof BlockStatement) {
+            trn.visitBlockStatement((BlockStatement) astNode);
+        } else if (astNode instanceof ClassNode) {
+            trn.visitClass((ClassNode) astNode);
         }
-        return null;
     }
 
     public static ASTNode getMacroValue(BlockStatement closureBlock, boolean asIs) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
new file mode 100644
index 0000000..46dc062
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.transform;
+
+public abstract class MacroClass {
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index 127fb4b..5a7c275 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -15,64 +15,104 @@
  */
 package org.codehaus.groovy.macro.transform;
 
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
 import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.ast.CodeVisitorSupport;
+import org.codehaus.groovy.ast.InnerClassNode;
 import org.codehaus.groovy.ast.MethodInvocationTrap;
-import org.codehaus.groovy.ast.expr.*;
+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.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.MapExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
+import org.codehaus.groovy.ast.expr.TupleExpression;
 import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.tools.GeneralUtils;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
 import org.codehaus.groovy.macro.runtime.MacroBuilder;
 import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
 
-import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
 
 import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
 
 /**
- *
  * @author Sergei Egorov <bs...@gmail.com>
  */
 public class MacroInvocationTrap extends MethodInvocationTrap {
 
+    private final static ClassNode MACROCLASS_TYPE = ClassHelper.make(MacroClass.class);
+    private final ReaderSource readerSource;
+
     public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
         super(source, sourceUnit);
+        this.readerSource = source;
+    }
+
+    @Override
+    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
+        ClassNode type = call.getType();
+        if (type instanceof InnerClassNode) {
+            if (((InnerClassNode) type).isAnonymous() &&
+                    MACROCLASS_TYPE.getNameWithoutPackage().equals(type.getSuperClass().getNameWithoutPackage())) {
+                //System.out.println("call = " + call.getText());
+                try {
+                    String source = convertInnerClassToSource(type);
+                    List<Expression> macroArgumentsExpressions = new LinkedList<Expression>();
+                    macroArgumentsExpressions.add(new ConstantExpression(source));
+                    macroArgumentsExpressions.add(buildSubstitutionMap(type));
+                    macroArgumentsExpressions.add(new ClassExpression(ClassHelper.make(ClassNode.class)));
+
+                    MethodCallExpression macroCall = new MethodCallExpression(
+                            new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"),
+                            MacroTransformation.MACRO_METHOD,
+                            new ArgumentListExpression(macroArgumentsExpressions)
+                    );
+
+                    macroCall.setSpreadSafe(false);
+                    macroCall.setSafe(false);
+                    macroCall.setImplicitThis(false);
+                    call.putNodeMetaData(MacroTransformation.class, macroCall);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+                return;
+            }
+        }
+        super.visitConstructorCallExpression(call);
+
+    }
+
+    private String convertInnerClassToSource(final ClassNode type) throws Exception {
+        String source = GeneralUtils.convertASTToSource(readerSource, type);
+        // we need to remove the leading "{" and trailing "}"
+        source = source.substring(source.indexOf('{')+1, source.lastIndexOf('}')-1);
+        return source;
     }
 
     @Override
     protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
         final ClosureExpression closureExpression = getClosureArgument(macroCall);
 
-        if(closureExpression == null) {
+        if (closureExpression == null) {
             return true;
         }
 
-        if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
+        if (closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
             addError("Macro closure arguments are not allowed", closureExpression);
             return true;
         }
 
-        final MapExpression mapExpression = new MapExpression();
-
-        (new CodeVisitorSupport() {
-            @Override
-            public void visitMethodCallExpression(MethodCallExpression call) {
-                super.visitMethodCallExpression(call);
-
-                if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
-                    ClosureExpression substitutionClosureExpression = getClosureArgument(call);
-
-                    if(substitutionClosureExpression == null) {
-                        return;
-                    }
-
-                    MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
-
-                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
-                }
-            }
-        }).visitClosureExpression(closureExpression);
+        final MapExpression mapExpression = buildSubstitutionMap(closureExpression);
 
         String source = convertClosureToSource(closureExpression);
 
@@ -82,18 +122,18 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
         TupleExpression macroArguments = getMacroArguments(macroCall);
 
-        if(macroArguments == null) {
+        if (macroArguments == null) {
             return true;
         }
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
 
-        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
+        if (macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
             Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
-            if((asIsArgumentExpression instanceof ConstantExpression)) {
+            if ((asIsArgumentExpression instanceof ConstantExpression)) {
                 ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
 
-                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                if (!(asIsConstantExpression.getValue() instanceof Boolean)) {
                     addError("AsIs argument value should be boolean", asIsConstantExpression);
                     return true;
                 }
@@ -112,10 +152,54 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);
         macroCall.setImplicitThis(false);
-        
+
         return true;
     }
 
+    private MapExpression buildSubstitutionMap(final ASTNode expr) {
+        final MapExpression mapExpression = new MapExpression();
+
+        ClassCodeVisitorSupport visitor = new ClassCodeVisitorSupport() {
+            @Override
+            protected SourceUnit getSourceUnit() {
+                return null;
+            }
+
+            @Override
+            public void visitClass(final ClassNode node) {
+                super.visitClass(node);
+                Iterator<InnerClassNode> it = node.getInnerClasses();
+                while (it.hasNext()) {
+                    InnerClassNode next = it.next();
+                    visitClass(next);
+                }
+            }
+
+            @Override
+            public void visitMethodCallExpression(MethodCallExpression call) {
+                super.visitMethodCallExpression(call);
+
+                if (isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                    ClosureExpression substitutionClosureExpression = getClosureArgument(call);
+
+                    if (substitutionClosureExpression == null) {
+                        return;
+                    }
+
+                    MacroSubstitutionKey key = new MacroSubstitutionKey(call, expr.getLineNumber(), expr.getColumnNumber());
+
+                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
+                }
+            }
+        };
+        if (expr instanceof ClassNode) {
+            visitor.visitClass((ClassNode) expr);
+        } else {
+            expr.visit(visitor);
+        }
+        return mapExpression;
+    }
+
     @Override
     protected boolean isBuildInvocation(MethodCallExpression call) {
         return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
@@ -123,20 +207,20 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
     public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
         if (call == null) throw new IllegalArgumentException("Null: call");
-        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+        if (methodName == null) throw new IllegalArgumentException("Null: methodName");
 
-        if(!(call.getMethod() instanceof ConstantExpression)) {
+        if (!(call.getMethod() instanceof ConstantExpression)) {
             return false;
         }
 
-        if(!(methodName.equals(call.getMethodAsString()))) {
+        if (!(methodName.equals(call.getMethodAsString()))) {
             return false;
         }
 
         // is method object correct type?
         return call.getObjectExpression() == THIS_EXPRESSION;
     }
-    
+
     protected TupleExpression getMacroArguments(MethodCallExpression call) {
         Expression macroCallArguments = call.getArguments();
         if (macroCallArguments == null) {
@@ -144,7 +228,7 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
             return null;
         }
 
-        if(!(macroCallArguments instanceof TupleExpression)) {
+        if (!(macroCallArguments instanceof TupleExpression)) {
             addError("Call should have TupleExpression as arguments", macroCallArguments);
             return null;
         }
@@ -155,14 +239,14 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
             addError("Call arguments should have expressions", tupleArguments);
             return null;
         }
-        
+
         return tupleArguments;
     }
-    
+
     protected ClosureExpression getClosureArgument(MethodCallExpression call) {
         TupleExpression tupleArguments = getMacroArguments(call);
 
-        if(tupleArguments.getExpressions().size() < 1) {
+        if (tupleArguments.getExpressions().size() < 1) {
             addError("Call arguments should have at least one argument", tupleArguments);
             return null;
         }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
index 65284b5..7920e2e 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -16,6 +16,7 @@
 package org.codehaus.groovy.macro.transform;
 
 import org.codehaus.groovy.ast.*;
+import org.codehaus.groovy.ast.expr.*;
 import org.codehaus.groovy.control.CompilePhase;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.transform.GroovyASTTransformation;
@@ -32,8 +33,25 @@ public class MacroTransformation extends MethodCallTransformation {
     public static final String MACRO_METHOD = "macro";
 
     @Override
-    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
-        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
+    protected GroovyCodeVisitor getTransformer(final ASTNode[] nodes, final SourceUnit sourceUnit) {
+        final ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
+            @Override
+            protected SourceUnit getSourceUnit() {
+                return sourceUnit;
+            }
+
+            @Override
+            public Expression transform(final Expression exp) {
+                if (exp instanceof ConstructorCallExpression) {
+                    MethodCallExpression call = exp.getNodeMetaData(MacroTransformation.class);
+                    if (call!=null) {
+                        return call;
+                    }
+                }
+                return super.transform(exp);
+            }
+        };
+        return new TransformingMacroTrap(sourceUnit, trn);
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/09758c34/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
new file mode 100644
index 0000000..35ddf55
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
@@ -0,0 +1,340 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.transform;
+
+import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.AssertStatement;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.BreakStatement;
+import org.codehaus.groovy.ast.stmt.CaseStatement;
+import org.codehaus.groovy.ast.stmt.CatchStatement;
+import org.codehaus.groovy.ast.stmt.ContinueStatement;
+import org.codehaus.groovy.ast.stmt.DoWhileStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ForStatement;
+import org.codehaus.groovy.ast.stmt.IfStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.SwitchStatement;
+import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
+import org.codehaus.groovy.ast.stmt.ThrowStatement;
+import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.ast.stmt.WhileStatement;
+import org.codehaus.groovy.classgen.BytecodeExpression;
+import org.codehaus.groovy.control.SourceUnit;
+
+class TransformingMacroTrap extends MacroInvocationTrap {
+    private final ClassCodeExpressionTransformer trn;
+
+    public TransformingMacroTrap(final SourceUnit sourceUnit, final ClassCodeExpressionTransformer trn) {
+        super(sourceUnit.getSource(), sourceUnit);
+        this.trn = trn;
+    }
+
+    @Override
+    public void visitBlockStatement(final BlockStatement block) {
+        super.visitBlockStatement(block);
+        trn.visitBlockStatement(block);
+    }
+
+    @Override
+    public void visitForLoop(final ForStatement forLoop) {
+        super.visitForLoop(forLoop);
+        trn.visitForLoop(forLoop);
+    }
+
+    @Override
+    public void visitWhileLoop(final WhileStatement loop) {
+        super.visitWhileLoop(loop);
+        trn.visitWhileLoop(loop);
+    }
+
+    @Override
+    public void visitDoWhileLoop(final DoWhileStatement loop) {
+        super.visitDoWhileLoop(loop);
+        trn.visitDoWhileLoop(loop);
+    }
+
+    @Override
+    public void visitIfElse(final IfStatement ifElse) {
+        super.visitIfElse(ifElse);
+        trn.visitIfElse(ifElse);
+    }
+
+    @Override
+    public void visitExpressionStatement(final ExpressionStatement statement) {
+        super.visitExpressionStatement(statement);
+        trn.visitExpressionStatement(statement);
+    }
+
+    @Override
+    public void visitReturnStatement(final ReturnStatement statement) {
+        super.visitReturnStatement(statement);
+        trn.visitReturnStatement(statement);
+    }
+
+    @Override
+    public void visitAssertStatement(final AssertStatement statement) {
+        super.visitAssertStatement(statement);
+        trn.visitAssertStatement(statement);
+    }
+
+    @Override
+    public void visitTryCatchFinally(final TryCatchStatement statement) {
+        super.visitTryCatchFinally(statement);
+        trn.visitTryCatchFinally(statement);
+    }
+
+    @Override
+    public void visitSwitch(final SwitchStatement statement) {
+        super.visitSwitch(statement);
+        trn.visitSwitch(statement);
+    }
+
+    @Override
+    public void visitCaseStatement(final CaseStatement statement) {
+        super.visitCaseStatement(statement);
+        trn.visitCaseStatement(statement);
+    }
+
+    @Override
+    public void visitBreakStatement(final BreakStatement statement) {
+        super.visitBreakStatement(statement);
+        trn.visitBreakStatement(statement);
+    }
+
+    @Override
+    public void visitContinueStatement(final ContinueStatement statement) {
+        super.visitContinueStatement(statement);
+        trn.visitContinueStatement(statement);
+    }
+
+    @Override
+    public void visitSynchronizedStatement(final SynchronizedStatement statement) {
+        super.visitSynchronizedStatement(statement);
+        trn.visitSynchronizedStatement(statement);
+    }
+
+    @Override
+    public void visitThrowStatement(final ThrowStatement statement) {
+        super.visitThrowStatement(statement);
+        trn.visitThrowStatement(statement);
+    }
+
+    @Override
+    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
+        super.visitStaticMethodCallExpression(call);
+        trn.visitStaticMethodCallExpression(call);
+    }
+
+    @Override
+    public void visitBinaryExpression(final BinaryExpression expression) {
+        super.visitBinaryExpression(expression);
+        trn.visitBinaryExpression(expression);
+    }
+
+    @Override
+    public void visitTernaryExpression(final TernaryExpression expression) {
+        super.visitTernaryExpression(expression);
+        trn.visitTernaryExpression(expression);
+    }
+
+    @Override
+    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
+        super.visitShortTernaryExpression(expression);
+        trn.visitShortTernaryExpression(expression);
+    }
+
+    @Override
+    public void visitPostfixExpression(final PostfixExpression expression) {
+        super.visitPostfixExpression(expression);
+        trn.visitPostfixExpression(expression);
+    }
+
+    @Override
+    public void visitPrefixExpression(final PrefixExpression expression) {
+        super.visitPrefixExpression(expression);
+        trn.visitPrefixExpression(expression);
+    }
+
+    @Override
+    public void visitBooleanExpression(final BooleanExpression expression) {
+        super.visitBooleanExpression(expression);
+        trn.visitBooleanExpression(expression);
+    }
+
+    @Override
+    public void visitNotExpression(final NotExpression expression) {
+        super.visitNotExpression(expression);
+        trn.visitNotExpression(expression);
+    }
+
+    @Override
+    public void visitClosureExpression(final ClosureExpression expression) {
+        super.visitClosureExpression(expression);
+        trn.visitClosureExpression(expression);
+    }
+
+    @Override
+    public void visitTupleExpression(final TupleExpression expression) {
+        super.visitTupleExpression(expression);
+        trn.visitTupleExpression(expression);
+    }
+
+    @Override
+    public void visitListExpression(final ListExpression expression) {
+        super.visitListExpression(expression);
+        trn.visitListExpression(expression);
+    }
+
+    @Override
+    public void visitArrayExpression(final ArrayExpression expression) {
+        super.visitArrayExpression(expression);
+        trn.visitArrayExpression(expression);
+    }
+
+    @Override
+    public void visitMapExpression(final MapExpression expression) {
+        super.visitMapExpression(expression);
+        trn.visitMapExpression(expression);
+    }
+
+    @Override
+    public void visitMapEntryExpression(final MapEntryExpression expression) {
+        super.visitMapEntryExpression(expression);
+        trn.visitMapEntryExpression(expression);
+    }
+
+    @Override
+    public void visitRangeExpression(final RangeExpression expression) {
+        super.visitRangeExpression(expression);
+        trn.visitRangeExpression(expression);
+    }
+
+    @Override
+    public void visitSpreadExpression(final SpreadExpression expression) {
+        super.visitSpreadExpression(expression);
+        trn.visitSpreadExpression(expression);
+    }
+
+    @Override
+    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
+        super.visitSpreadMapExpression(expression);
+        trn.visitSpreadMapExpression(expression);
+    }
+
+    @Override
+    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
+        super.visitMethodPointerExpression(expression);
+        trn.visitMethodPointerExpression(expression);
+    }
+
+    @Override
+    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
+        super.visitUnaryMinusExpression(expression);
+        trn.visitUnaryMinusExpression(expression);
+    }
+
+    @Override
+    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
+        super.visitUnaryPlusExpression(expression);
+        trn.visitUnaryPlusExpression(expression);
+    }
+
+    @Override
+    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
+        super.visitBitwiseNegationExpression(expression);
+        trn.visitBitwiseNegationExpression(expression);
+    }
+
+    @Override
+    public void visitCastExpression(final CastExpression expression) {
+        super.visitCastExpression(expression);
+        trn.visitCastExpression(expression);
+    }
+
+    @Override
+    public void visitConstantExpression(final ConstantExpression expression) {
+        super.visitConstantExpression(expression);
+        trn.visitConstantExpression(expression);
+    }
+
+    @Override
+    public void visitClassExpression(final ClassExpression expression) {
+        super.visitClassExpression(expression);
+        trn.visitClassExpression(expression);
+    }
+
+    @Override
+    public void visitVariableExpression(final VariableExpression expression) {
+        super.visitVariableExpression(expression);
+        trn.visitVariableExpression(expression);
+    }
+
+    @Override
+    public void visitDeclarationExpression(final DeclarationExpression expression) {
+        super.visitDeclarationExpression(expression);
+        trn.visitDeclarationExpression(expression);
+    }
+
+    @Override
+    public void visitPropertyExpression(final PropertyExpression expression) {
+        super.visitPropertyExpression(expression);
+        trn.visitPropertyExpression(expression);
+    }
+
+    @Override
+    public void visitAttributeExpression(final AttributeExpression expression) {
+        super.visitAttributeExpression(expression);
+        trn.visitAttributeExpression(expression);
+    }
+
+    @Override
+    public void visitFieldExpression(final FieldExpression expression) {
+        super.visitFieldExpression(expression);
+        trn.visitFieldExpression(expression);
+    }
+
+    @Override
+    public void visitGStringExpression(final GStringExpression expression) {
+        super.visitGStringExpression(expression);
+        trn.visitGStringExpression(expression);
+    }
+
+    @Override
+    public void visitCatchStatement(final CatchStatement statement) {
+        super.visitCatchStatement(statement);
+        trn.visitCatchStatement(statement);
+    }
+
+    @Override
+    public void visitArgumentlistExpression(final ArgumentListExpression ale) {
+        super.visitArgumentlistExpression(ale);
+        trn.visitArgumentlistExpression(ale);
+    }
+
+    @Override
+    public void visitClosureListExpression(final ClosureListExpression cle) {
+        super.visitClosureListExpression(cle);
+        trn.visitClosureListExpression(cle);
+    }
+
+    @Override
+    public void visitBytecodeExpression(final BytecodeExpression cle) {
+        super.visitBytecodeExpression(cle);
+        trn.visitBytecodeExpression(cle);
+    }
+}



[21/37] incubator-groovy git commit: ASTMatcher: Test cases for not/list/map expressions

Posted by cc...@apache.org.
ASTMatcher: Test cases for not/list/map expressions


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/02e53fcf
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/02e53fcf
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/02e53fcf

Branch: refs/heads/master
Commit: 02e53fcfe7f9cc625489ace128761eef4e828392
Parents: 3eba53c
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 10:38:16 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 58 +++++++++++--
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 86 ++++++++++++++++++++
 2 files changed, 138 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/02e53fcf/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 1bfc366..ffcf09a 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -512,7 +512,13 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitNotExpression(final NotExpression expression) {
-        super.visitNotExpression(expression);
+        doWithNode(NotExpression, current) {
+            def expr = expression.expression
+            def cur = ((NotExpression)current).expression
+            doWithNode(expr.class, cur) {
+                expr.visit(this)
+            }
+        }
     }
 
     @Override
@@ -561,7 +567,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitListExpression(final ListExpression expression) {
-        super.visitListExpression(expression);
+        doWithNode(ListExpression, current) {
+            def exprs = expression.expressions
+            doWithNode(exprs.class, ((ListExpression)current).expressions) {
+                visitListOfExpressions(exprs)
+            }
+        }
     }
 
     @Override
@@ -571,22 +582,57 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMapExpression(final MapExpression expression) {
-        super.visitMapExpression(expression);
+        doWithNode(MapExpression, current) {
+            def entries = expression.mapEntryExpressions
+            def curEntries = ((MapExpression)current).mapEntryExpressions
+            doWithNode(entries.class, curEntries) {
+                visitListOfExpressions(entries)
+            }
+        }
     }
 
     @Override
     public void visitMapEntryExpression(final MapEntryExpression expression) {
-        super.visitMapEntryExpression(expression);
+        doWithNode(MapEntryExpression, current) {
+            def key = expression.keyExpression
+            def value = expression.valueExpression
+            def cur = (MapEntryExpression) current
+            def curKey = cur.keyExpression
+            def curValue = cur.valueExpression
+            doWithNode(key.class, curKey) {
+                key.visit(this)
+            }
+            doWithNode(value.class, curValue) {
+                value.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitRangeExpression(final RangeExpression expression) {
-        super.visitRangeExpression(expression);
+        doWithNode(RangeExpression, current) {
+            def from = expression.from
+            def to = expression.to
+            def cur = (RangeExpression) current
+            def curFrom = cur.from
+            def curTo = cur.to
+            doWithNode(from.class, curFrom) {
+                from.visit(this)
+            }
+            doWithNode(to.class, curTo) {
+                to.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitSpreadExpression(final SpreadExpression expression) {
-        super.visitSpreadExpression(expression);
+        doWithNode(SpreadExpression, current) {
+            def expr = expression.expression
+            doWithNode(expr.class, ((SpreadExpression)current).expression) {
+                expr.visit(this)
+            }
+        }
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/02e53fcf/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index b473d66..064e01c 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -17,6 +17,7 @@
 package org.codehaus.groovy.macro.matcher
 
 import org.codehaus.groovy.ast.expr.ClassExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
 import org.codehaus.groovy.control.CompilePhase
 
 class ASTMatcherTest extends GroovyTestCase {
@@ -203,4 +204,89 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast5, ast6)
         assert !ASTMatcher.matches(ast5, ast7)
     }
+
+    void testNotExpression() {
+        def ast1 = macro { !a }
+        def ast2 = macro { !a }
+        def ast3 = macro { a }
+        def ast4 = macro { !b }
+        def ast5 = macro { !(a+b) }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+    }
+
+    void testMapExpression() {
+        def ast1 = macro { [:] }
+        def ast2 = macro { [:] }
+        def ast3 = macro { [a:''] }
+        def ast4 = macro { [b:''] }
+        def ast5 = macro { [a:'a'] }
+        def ast6 = macro { [a:'a',b:'b'] }
+        def ast7 = macro { [b:'b', a:'a'] }
+        def ast8 = macro { [a:'a', *:'b'] }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast4, ast5)
+        assert !ASTMatcher.matches(ast5, ast6)
+        assert !ASTMatcher.matches(ast6, ast7)
+        assert !ASTMatcher.matches(ast3, ast8)
+        assert !ASTMatcher.matches(ast6, ast8)
+    }
+
+    void testRangeExpression() {
+        def ast1 = macro { (0..10) }
+        def ast2 = macro { (0..10) }
+        def ast3 = macro { (1..10) }
+        def ast4 = macro { (0..9) }
+        def ast5 = macro { ('a'..'z') }
+        def ast6 = macro { (0.0..10.0) }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+    }
+
+    void testListExpression() {
+        def ast1 = macro { [] }
+        def ast2 = macro { [] }
+        def ast3 = macro { [a] }
+        def ast4 = macro { [a] }
+        def ast5 = macro { [b] }
+        def ast6 = macro { [a,b] }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert ASTMatcher.matches(ast3, ast3)
+        assert ASTMatcher.matches(ast3, ast4)
+        assert ASTMatcher.matches(ast4, ast3)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast4, ast5)
+        assert !ASTMatcher.matches(ast5, ast4)
+        assert !ASTMatcher.matches(ast5, ast6)
+        assert !ASTMatcher.matches(ast1, ast6)
+    }
+
+    void testSpreadExpression() {
+        def ast1 = macro { [*a] }
+        def ast2 = macro { [*a] }
+        def ast3 = macro { [*b] }
+        def ast4 = macro { [a] }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
 }


[23/37] incubator-groovy git commit: ASTMatcher: Add support for while loop

Posted by cc...@apache.org.
ASTMatcher: Add support for while loop


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/5a01b997
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/5a01b997
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/5a01b997

Branch: refs/heads/master
Commit: 5a01b997436e9191b8038a7a7e4e3f428b6da636
Parents: 199187e
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 13:51:17 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:11 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy         | 17 +++++++++++++++++
 .../groovy/macro/matcher/ASTMatcherTest.groovy     | 15 +++++++++++++++
 2 files changed, 32 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/5a01b997/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 7c3b68f..5deb80b 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -25,6 +25,7 @@ import org.codehaus.groovy.ast.stmt.ExpressionStatement
 import org.codehaus.groovy.ast.stmt.ForStatement
 import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.ast.stmt.Statement
+import org.codehaus.groovy.ast.stmt.WhileStatement
 import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
 
@@ -880,4 +881,20 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
         }
     }
+
+    @Override
+    void visitWhileLoop(final WhileStatement loop) {
+        doWithNode(WhileStatement, current) {
+            visitStatement(loop)
+            def cur = (WhileStatement) current
+            def bool = loop.booleanExpression
+            def block = loop.loopBlock
+            doWithNode(bool.class, cur.booleanExpression) {
+                bool.visit(this)
+            }
+            doWithNode(block.class, cur.loopBlock) {
+                block.visit(this)
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/5a01b997/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 75ca21c..78ec60d 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -28,6 +28,7 @@ import org.codehaus.groovy.ast.expr.UnaryMinusExpression
 import org.codehaus.groovy.ast.expr.UnaryPlusExpression
 import org.codehaus.groovy.ast.stmt.ForStatement
 import org.codehaus.groovy.ast.stmt.IfStatement
+import org.codehaus.groovy.ast.stmt.WhileStatement
 import org.codehaus.groovy.control.CompilePhase
 import org.codehaus.groovy.macro.transform.MacroClass
 
@@ -555,4 +556,18 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast3, ast5)
         assert !ASTMatcher.matches(ast3, ast6)
     }
+
+    void testWhileLoop() {
+        def ast1 = macro { while (true) {} }
+        def ast2 = macro { while (true) {} }
+        def ast3 = macro { while (false) {} }
+        def ast4 = macro { while (true) { a } }
+
+        assert ast1 instanceof WhileStatement
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
 }


[27/37] incubator-groovy git commit: ASTMatcher: Add test case for simplified AST matcher with 2 constraints in the same block

Posted by cc...@apache.org.
ASTMatcher: Add test case for simplified AST matcher with 2 constraints in the same block


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/3d6d571d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/3d6d571d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/3d6d571d

Branch: refs/heads/master
Commit: 3d6d571dd3dea0f6d93c8af810f89249ea9ca570
Parents: bea3042
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Nov 12 11:18:08 2014 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:12 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcherTest.groovy   | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3d6d571d/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 35301e4..8b5660e 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -727,4 +727,23 @@ class ASTMatcherTest extends GroovyTestCase {
         }
     }
 
+    void testInlineMacroCombinationWithSimplifiedConstraints() {
+        use(ASTMatcher) {
+            def ast1 = macro { a + b }
+            def ast2 = macro { b + b }
+            def ast3 = macro { b + c }
+            def ast4 = macro { b - b }
+            def pattern = macro {
+                a + b
+            }.withConstraints {
+                placeholder a
+                anyToken()
+            }
+            assert pattern instanceof BinaryExpression
+            assert ast1.matches(pattern)
+            assert ast2.matches(pattern)
+            assert !ast3.matches(pattern)
+            assert ast4.matches(pattern)
+        }
+    }
 }


[33/37] incubator-groovy git commit: Avoid usage of System.currentTimeMillis which is both slow and not stable across various OSes

Posted by cc...@apache.org.
Avoid usage of System.currentTimeMillis which is both slow and not stable across various OSes


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/f08195f1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/f08195f1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/f08195f1

Branch: refs/heads/master
Commit: f08195f1ca66488e257c6bec040e6ca83db70df7
Parents: 053af2e
Author: Cedric Champeau <ce...@gmail.com>
Authored: Tue Dec 30 11:06:12 2014 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:13 2015 +0300

----------------------------------------------------------------------
 .../groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java  | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f08195f1/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index 1edbcba..2895ebf 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -32,6 +32,7 @@ import org.codehaus.groovy.macro.transform.MacroTransformation;
 
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  *
@@ -52,10 +53,12 @@ public enum MacroBuilder {
         return macro(compilePhase, false, source, context, resultClass);
     }
 
+    private final static AtomicInteger COUNTER = new AtomicInteger();
+
     @SuppressWarnings("unchecked")
     public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
         boolean isClosure = source.startsWith("{");
-        final String label = isClosure ?"__synthesized__label__" + System.currentTimeMillis() + "__:":"";
+        final String label = isClosure ?"__synthesized__label__" + COUNTER.incrementAndGet() + "__:":"";
         final String labelledSource = label + source;
         final int linesOffset = 1;
         final int columnsOffset = label.length() + (isClosure?1:0); // +1 because of {


[02/37] incubator-groovy git commit: shared code between MacroGroovy and AstBuilderTransformation

Posted by cc...@apache.org.
shared code between MacroGroovy and AstBuilderTransformation


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/546868aa
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/546868aa
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/546868aa

Branch: refs/heads/master
Commit: 546868aaae30335b9b6fc1a67bb6cf1dc2b84cff
Parents: 0b5f0b0
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 12:45:29 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:03 2015 +0300

----------------------------------------------------------------------
 .../groovy/ast/MethodCallTransformation.java    | 113 ++++++++++++
 .../groovy/ast/MethodInvocationTrap.java        |  94 ++++++++++
 .../ast/builder/AstBuilderTransformation.java   | 181 +++----------------
 .../macro/transform/MacroInvocationTrap.java    | 148 +++++----------
 .../macro/transform/MacroTransformation.java    |  41 +----
 5 files changed, 289 insertions(+), 288 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/546868aa/src/main/org/codehaus/groovy/ast/MethodCallTransformation.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/MethodCallTransformation.java b/src/main/org/codehaus/groovy/ast/MethodCallTransformation.java
new file mode 100644
index 0000000..85c6f2c
--- /dev/null
+++ b/src/main/org/codehaus/groovy/ast/MethodCallTransformation.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.ast;
+
+import groovy.lang.MissingPropertyException;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.transform.ASTTransformation;
+
+/**
+ *
+ * @author Hamlet D'Arcy
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+
+public abstract class MethodCallTransformation implements ASTTransformation {
+
+    public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
+
+        GroovyCodeVisitor transformer = getTransformer(nodes, sourceUnit);
+
+        if (nodes != null) {
+            for (ASTNode it : nodes) {
+                if (!(it instanceof AnnotationNode) && !(it instanceof ClassNode)) {
+                    it.visit(transformer);
+                }
+            }
+        }
+        if (sourceUnit.getAST() != null) {
+            sourceUnit.getAST().visit(transformer);
+            if (sourceUnit.getAST().getStatementBlock() != null) {
+                sourceUnit.getAST().getStatementBlock().visit(transformer);
+            }
+            if (sourceUnit.getAST().getClasses() != null) {
+                for (ClassNode classNode : sourceUnit.getAST().getClasses()) {
+                    if (classNode.getMethods() != null) {
+                        for (MethodNode node : classNode.getMethods()) {
+                            if (node != null && node.getCode() != null) {
+                                node.getCode().visit(transformer);
+                            }
+                        }
+                    }
+
+                    try {
+                        if (classNode.getDeclaredConstructors() != null) {
+                            for (MethodNode node : classNode.getDeclaredConstructors()) {
+                                if (node != null && node.getCode() != null) {
+                                    node.getCode().visit(transformer);
+                                }
+                            }
+                        }
+                    } catch (MissingPropertyException ignored) {
+                        // todo: inner class nodes don't have a constructors field available
+                    }
+
+                    // all properties are also always fields
+                    if (classNode.getFields() != null) {
+                        for (FieldNode node : classNode.getFields()) {
+                            if (node.getInitialValueExpression() != null) {
+                                node.getInitialValueExpression().visit(transformer);
+                            }
+                        }
+                    }
+
+                    try {
+                        if (classNode.getObjectInitializerStatements() != null) {
+                            for (Statement node : classNode.getObjectInitializerStatements()) {
+                                if (node != null) {
+                                    node.visit(transformer);
+                                }
+                            }
+                        }
+                    } catch (MissingPropertyException ignored) {
+                        // todo: inner class nodes don't have a objectInitializers field available
+                    }
+
+                    // todo: is there anything to do with the module ???
+                }
+            }
+            if (sourceUnit.getAST().getMethods() != null) {
+                for (MethodNode node : sourceUnit.getAST().getMethods()) {
+                    if (node != null) {
+                        if (node.getParameters() != null) {
+                            for (Parameter parameter : node.getParameters()) {
+                                if (parameter != null && parameter.getInitialExpression() != null) {
+                                    parameter.getInitialExpression().visit(transformer);
+                                }
+                            }
+                        }
+                        if (node.getCode() != null) {
+                            node.getCode().visit(transformer);
+                        }
+                    }
+                }
+            }
+        }
+    }
+    
+    protected abstract GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit);
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/546868aa/src/main/org/codehaus/groovy/ast/MethodInvocationTrap.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/MethodInvocationTrap.java b/src/main/org/codehaus/groovy/ast/MethodInvocationTrap.java
new file mode 100644
index 0000000..6d51a5c
--- /dev/null
+++ b/src/main/org/codehaus/groovy/ast/MethodInvocationTrap.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.ast;
+
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.tools.ClosureUtils;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.control.io.ReaderSource;
+import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
+import org.codehaus.groovy.syntax.SyntaxException;
+
+/**
+ *
+ * @author Hamlet D'Arcy
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public abstract class MethodInvocationTrap extends CodeVisitorSupport {
+
+    protected final ReaderSource source;
+    protected final SourceUnit sourceUnit;
+
+    public MethodInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        if (source == null) throw new IllegalArgumentException("Null: source");
+        if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
+        this.source = source;
+        this.sourceUnit = sourceUnit;
+    }
+
+    /**
+     * Attempts to find AstBuilder 'from code' invocations. When found, converts them into calls
+     * to the 'from string' approach.
+     *
+     * @param call the method call expression that may or may not be an AstBuilder 'from code' invocation.
+     */
+    public void visitMethodCallExpression(MethodCallExpression call) {
+        boolean shouldContinueWalking = true;
+        
+        if (isBuildInvocation(call)) {
+            shouldContinueWalking = handleTargetMethodCallExpression(call);
+        }
+        
+        if(shouldContinueWalking) {
+            // continue normal tree walking
+            call.getObjectExpression().visit(this);
+            call.getMethod().visit(this);
+            call.getArguments().visit(this);
+        }
+    }
+
+    /**
+     * Reports an error back to the source unit.
+     *
+     * @param msg  the error message
+     * @param expr the expression that caused the error message.
+     */
+    protected void addError(String msg, ASTNode expr) {
+        sourceUnit.getErrorCollector().addErrorAndContinue(
+                new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
+        );
+    }
+
+    /**
+     * Converts a ClosureExpression into the String source.
+     *
+     * @param expression a closure
+     * @return the source the closure was created from
+     */
+    protected String convertClosureToSource(ClosureExpression expression) {
+        try {
+            return ClosureUtils.convertClosureToSource(source, expression);
+        } catch(Exception e) {
+            addError(e.getMessage(), expression);
+        }
+        return null;
+    }
+
+    protected abstract boolean handleTargetMethodCallExpression(MethodCallExpression call);
+
+    protected abstract boolean isBuildInvocation(MethodCallExpression call);
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/546868aa/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java b/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java
index 20a4aea..4143e34 100644
--- a/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java
+++ b/src/main/org/codehaus/groovy/ast/builder/AstBuilderTransformation.java
@@ -18,17 +18,11 @@
  */
 package org.codehaus.groovy.ast.builder;
 
-import groovy.lang.MissingPropertyException;
 import org.codehaus.groovy.ast.*;
 import org.codehaus.groovy.ast.expr.*;
-import org.codehaus.groovy.ast.stmt.Statement;
-import org.codehaus.groovy.ast.tools.ClosureUtils;
 import org.codehaus.groovy.control.CompilePhase;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
-import org.codehaus.groovy.syntax.SyntaxException;
-import org.codehaus.groovy.transform.ASTTransformation;
 import org.codehaus.groovy.transform.GroovyASTTransformation;
 
 import java.util.ArrayList;
@@ -49,92 +43,17 @@ import java.util.List;
  */
 
 @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
-public class AstBuilderTransformation implements ASTTransformation {
-
-    public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
+public class AstBuilderTransformation extends MethodCallTransformation {
 
+    @Override
+    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
         // todo : are there other import types that can be specified?
-        AstBuilderInvocationTrap transformer = new AstBuilderInvocationTrap(
-                sourceUnit.getAST().getImports(),
-                sourceUnit.getAST().getStarImports(),
-                sourceUnit.getSource(),
-                sourceUnit
+        return new AstBuilderInvocationTrap(
+            sourceUnit.getAST().getImports(),
+            sourceUnit.getAST().getStarImports(),
+            sourceUnit.getSource(),
+            sourceUnit
         );
-        if (nodes != null) {
-            for (ASTNode it : nodes) {
-                if (!(it instanceof AnnotationNode) && !(it instanceof ClassNode)) {
-                    it.visit(transformer);
-                }
-            }
-        }
-        if (sourceUnit.getAST() != null) {
-            sourceUnit.getAST().visit(transformer);
-            if (sourceUnit.getAST().getStatementBlock() != null) {
-                sourceUnit.getAST().getStatementBlock().visit(transformer);
-            }
-            if (sourceUnit.getAST().getClasses() != null) {
-                for (ClassNode classNode : sourceUnit.getAST().getClasses()) {
-                    if (classNode.getMethods() != null) {
-                        for (MethodNode node : classNode.getMethods()) {
-                            if (node != null && node.getCode() != null) {
-                                node.getCode().visit(transformer);
-                            }
-                        }
-                    }
-
-                    try {
-                        if (classNode.getDeclaredConstructors() != null) {
-                            for (MethodNode node : classNode.getDeclaredConstructors()) {
-                                if (node != null && node.getCode() != null) {
-                                    node.getCode().visit(transformer);
-                                }
-                            }
-                        }
-                    } catch (MissingPropertyException ignored) {
-                        // todo: inner class nodes don't have a constructors field available
-                    }
-
-                    // all properties are also always fields
-                    if (classNode.getFields() != null) {
-                        for (FieldNode node : classNode.getFields()) {
-                            if (node.getInitialValueExpression() != null) {
-                                node.getInitialValueExpression().visit(transformer);
-                            }
-                        }
-                    }
-
-                    try {
-                        if (classNode.getObjectInitializerStatements() != null) {
-                            for (Statement node : classNode.getObjectInitializerStatements()) {
-                                if (node != null) {
-                                    node.visit(transformer);
-                                }
-                            }
-                        }
-                    } catch (MissingPropertyException ignored) {
-                        // todo: inner class nodes don't have a objectInitializers field available
-                    }
-
-                    // todo: is there anything to do with the module ???
-                }
-            }
-            if (sourceUnit.getAST().getMethods() != null) {
-                for (MethodNode node : sourceUnit.getAST().getMethods()) {
-                    if (node != null) {
-                        if (node.getParameters() != null) {
-                            for (Parameter parameter : node.getParameters()) {
-                                if (parameter != null && parameter.getInitialExpression() != null) {
-                                    parameter.getInitialExpression().visit(transformer);
-                                }
-                            }
-                        }
-                        if (node.getCode() != null) {
-                            node.getCode().visit(transformer);
-                        }
-                    }
-                }
-            }
-        }
     }
 
     /**
@@ -142,11 +61,9 @@ public class AstBuilderTransformation implements ASTTransformation {
      * the contents of the closure into expressions by reading the source of the Closure and sending
      * that as a String to AstBuilder.build(String, CompilePhase, boolean) at runtime.
      */
-    private static class AstBuilderInvocationTrap extends CodeVisitorSupport {
+    private static class AstBuilderInvocationTrap extends MethodInvocationTrap {
 
         private final List<String> factoryTargets = new ArrayList<String>();
-        private final ReaderSource source;
-        private final SourceUnit sourceUnit;
 
         /**
          * Creates the trap and captures all the ways in which a class may be referenced via imports.
@@ -157,10 +74,7 @@ public class AstBuilderTransformation implements ASTTransformation {
          * @param sourceUnit     the source unit being compiled. Used for error messages.
          */
         AstBuilderInvocationTrap(List<ImportNode> imports, List<ImportNode> importPackages, ReaderSource source, SourceUnit sourceUnit) {
-            if (source == null) throw new IllegalArgumentException("Null: source");
-            if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
-            this.source = source;
-            this.sourceUnit = sourceUnit;
+            super(source, sourceUnit);
 
             // factory type may be references as fully qualified, an import, or an alias
             factoryTargets.add("org.codehaus.groovy.ast.builder.AstBuilder");//default package
@@ -182,47 +96,22 @@ public class AstBuilderTransformation implements ASTTransformation {
                 }
             }
         }
-
-        /**
-         * Reports an error back to the source unit.
-         *
-         * @param msg  the error message
-         * @param expr the expression that caused the error message.
-         */
-        private void addError(String msg, ASTNode expr) {
-            sourceUnit.getErrorCollector().addErrorAndContinue(
-                    new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
-            );
-        }
-
-
-        /**
-         * Attempts to find AstBuilder 'from code' invocations. When found, converts them into calls
-         * to the 'from string' approach.
-         *
-         * @param call the method call expression that may or may not be an AstBuilder 'from code' invocation.
-         */
-        public void visitMethodCallExpression(MethodCallExpression call) {
-
-            if (isBuildInvocation(call)) {
-
-                ClosureExpression closureExpression = getClosureArgument(call);
-                List<Expression> otherArgs = getNonClosureArguments(call);
-                String source = convertClosureToSource(closureExpression);
-
-                // parameter order is build(CompilePhase, boolean, String)
-                otherArgs.add(new ConstantExpression(source));
-                call.setArguments(new ArgumentListExpression(otherArgs));
-                call.setMethod(new ConstantExpression("buildFromBlock"));
-                call.setSpreadSafe(false);
-                call.setSafe(false);
-                call.setImplicitThis(false);
-            } else {
-                // continue normal tree walking
-                call.getObjectExpression().visit(this);
-                call.getMethod().visit(this);
-                call.getArguments().visit(this);
-            }
+        
+        @Override
+        protected boolean handleTargetMethodCallExpression(MethodCallExpression call) {
+            ClosureExpression closureExpression = getClosureArgument(call);
+            List<Expression> otherArgs = getNonClosureArguments(call);
+            String source = convertClosureToSource(closureExpression);
+
+            // parameter order is build(CompilePhase, boolean, String)
+            otherArgs.add(new ConstantExpression(source));
+            call.setArguments(new ArgumentListExpression(otherArgs));
+            call.setMethod(new ConstantExpression("buildFromBlock"));
+            call.setSpreadSafe(false);
+            call.setSafe(false);
+            call.setImplicitThis(false);
+            
+            return false;
         }
 
         private List<Expression> getNonClosureArguments(MethodCallExpression call) {
@@ -255,7 +144,8 @@ public class AstBuilderTransformation implements ASTTransformation {
          *
          * @param call the method call expression, may not be null
          */
-        private boolean isBuildInvocation(MethodCallExpression call) {
+        @Override
+        protected boolean isBuildInvocation(MethodCallExpression call) {
             if (call == null) throw new IllegalArgumentException("Null: call");
 
             // is method name correct?
@@ -281,21 +171,6 @@ public class AstBuilderTransformation implements ASTTransformation {
             }
             return false;
         }
-
-        /**
-         * 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(source, expression);
-            } catch(Exception e) {
-                addError(e.getMessage(), expression);
-            }
-            return null;
-        }
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/546868aa/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index 7ac10df..b082e8b 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -15,18 +15,15 @@
  */
 package org.codehaus.groovy.macro.transform;
 
-import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.ast.CodeVisitorSupport;
+import org.codehaus.groovy.ast.MethodInvocationTrap;
 import org.codehaus.groovy.ast.expr.*;
 import org.codehaus.groovy.ast.stmt.BlockStatement;
-import org.codehaus.groovy.ast.tools.ClosureUtils;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
 import org.codehaus.groovy.macro.runtime.MacroBuilder;
 import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
-import org.codehaus.groovy.syntax.SyntaxException;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -37,106 +34,73 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
-public class MacroInvocationTrap {
-
-    private final ReaderSource source;
-    private final SourceUnit sourceUnit;
-
-    /**
-     * Creates the trap and captures all macro method calls.
-     *
-     * @param source         the reader source that contains source for the SourceUnit
-     * @param sourceUnit     the source unit being compiled. Used for error messages.
-     */
-    MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
-        if (source == null) throw new IllegalArgumentException("Null: source");
-        if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
-        this.source = source;
-        this.sourceUnit = sourceUnit;
-    }
+public class MacroInvocationTrap extends MethodInvocationTrap {
 
-    /**
-     * Reports an error back to the source unit.
-     *
-     * @param msg  the error message
-     * @param expr the expression that caused the error message.
-     */
-    private void addError(String msg, ASTNode expr) {
-        sourceUnit.getErrorCollector().addErrorAndContinue(
-                new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
-        );
+    public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        super(source, sourceUnit);
     }
 
-    /**
-     * Attempts to find 'macro' invocations. When found, converts them into calls
-     * to the 'from string' approach.
-     *
-     * @param macroCall the method call expression that may or may not be a 'macro' invocation.
-     */
-    public void visitMethodCallExpression(final MethodCallExpression macroCall) {
-
-        if (!isBuildInvocation(macroCall, MacroTransformation.MACRO_METHOD)) {
-            return;
-        }
-
+    @Override
+    protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
         final ClosureExpression closureExpression = getClosureArgument(macroCall);
-        
+
         if(closureExpression == null) {
-            return;
+            return true;
         }
 
         if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
             addError("Macro closure arguments are not allowed", closureExpression);
+            return true;
         }
-        
+
         final MapExpression mapExpression = new MapExpression();
-        
+
         (new CodeVisitorSupport() {
             @Override
             public void visitMethodCallExpression(MethodCallExpression call) {
                 super.visitMethodCallExpression(call);
-                
+
                 if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
                     ClosureExpression substitutionClosureExpression = getClosureArgument(call);
-                    
+
                     if(substitutionClosureExpression == null) {
                         return;
                     }
 
                     MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
-                    
+
                     mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
                 }
             }
         }).visitClosureExpression(closureExpression);
-        
-        String source = convertClosureToSource(this.source, closureExpression);
+
+        String source = convertClosureToSource(closureExpression);
 
         BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
-        
+
         Boolean asIs = false;
-        
+
         TupleExpression macroArguments = getMacroArguments(macroCall);
-        
+
         if(macroArguments == null) {
-            return;
+            return true;
         }
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
-        
+
         if(macroArgumentsExpressions.size() > 1) {
             Expression firstArgument = macroArgumentsExpressions.get(0);
-            
+
             if(!(firstArgument instanceof ConstantExpression)) {
                 addError("AsIs argument value should be constant(true or false)", firstArgument);
-                return;
+                return true;
             }
-            
+
             ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
-            
+
             if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
                 addError("AsIs argument value should be boolean", asIsConstantExpression);
-                return;
+                return true;
             }
 
             asIs = (Boolean) asIsConstantExpression.getValue();
@@ -153,6 +117,29 @@ public class MacroInvocationTrap {
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);
         macroCall.setImplicitThis(false);
+        
+        return true;
+    }
+
+    @Override
+    protected boolean isBuildInvocation(MethodCallExpression call) {
+        return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
+    }
+
+    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
+        if (call == null) throw new IllegalArgumentException("Null: call");
+        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+
+        if(!(call.getMethod() instanceof ConstantExpression)) {
+            return false;
+        }
+
+        if(!(methodName.equals(call.getMethodAsString()))) {
+            return false;
+        }
+
+        // is method object correct type?
+        return call.getObjectExpression() == THIS_EXPRESSION;
     }
     
     protected TupleExpression getMacroArguments(MethodCallExpression call) {
@@ -193,41 +180,4 @@ public class MacroInvocationTrap {
 
         return (ClosureExpression) result;
     }
-
-    /**
-     * Looks for 'macro' method calls.
-     *
-     * @param call the method call expression, may not be null
-     */
-    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
-        if (call == null) throw new IllegalArgumentException("Null: call");
-        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
-        
-        if(!(call.getMethod() instanceof ConstantExpression)) {
-            return false;
-        }
-        
-        if(!(methodName.equals(call.getMethodAsString()))) {
-            return false;
-        }
-
-        // is method object correct type?
-        return call.getObjectExpression() == THIS_EXPRESSION;
-    }
-
-    /**
-     * Converts a ClosureExpression into the String source.
-     *
-     * @param expression a closure
-     * @return the source the closure was created from
-     */
-    private String convertClosureToSource(ReaderSource source, ClosureExpression expression) {
-
-        try {
-            return ClosureUtils.convertClosureToSource(source, expression);
-        } catch (Exception e) {
-            addError(e.getMessage(), expression);
-        }
-        return null;
-    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/546868aa/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
index cdf0f07..65284b5 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -15,56 +15,25 @@
  */
 package org.codehaus.groovy.macro.transform;
 
-import org.codehaus.groovy.ast.ASTNode;
-import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
-import org.codehaus.groovy.ast.ClassNode;
-import org.codehaus.groovy.ast.ModuleNode;
-import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.*;
 import org.codehaus.groovy.control.CompilePhase;
 import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.transform.ASTTransformation;
 import org.codehaus.groovy.transform.GroovyASTTransformation;
 
 /**
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
+
 @GroovyASTTransformation(phase = CompilePhase.CONVERSION)
-public class MacroTransformation extends ClassCodeVisitorSupport implements ASTTransformation {
+public class MacroTransformation extends MethodCallTransformation {
 
     public static final String DOLLAR_VALUE = "$v";
     public static final String MACRO_METHOD = "macro";
 
-    SourceUnit source;
-    
-    MacroInvocationTrap transformer;
-
-    public void visit(ASTNode[] nodes, SourceUnit source) {
-        this.source = source;
-
-        transformer = new MacroInvocationTrap(source.getSource(), source);
-
-        for(ASTNode node : nodes) {
-            if(node instanceof ClassNode) {
-                visitClass((ClassNode) node);
-            } else if(node instanceof ModuleNode) {
-                ModuleNode moduleNode = (ModuleNode) node;
-                for (ClassNode classNode : moduleNode.getClasses()) {
-                    visitClass(classNode);
-                }
-            }
-        }
-    }
-
-    @Override
-    public void visitMethodCallExpression(MethodCallExpression call) {
-        transformer.visitMethodCallExpression(call);
-        super.visitMethodCallExpression(call);
-    }
-
     @Override
-    protected SourceUnit getSourceUnit() {
-        return source;
+    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
+        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
     }
 }
 


[36/37] incubator-groovy git commit: fix license headers

Posted by cc...@apache.org.
fix license headers


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/9fee0243
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/9fee0243
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/9fee0243

Branch: refs/heads/master
Commit: 9fee0243db4bc890958051528877376524e3cff2
Parents: d486abd
Author: Sergei Egorov <bs...@gmail.com>
Authored: Mon Sep 28 14:53:20 2015 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:53:20 2015 +0300

----------------------------------------------------------------------
 subprojects/groovy-macro/build.gradle           | 20 +++++-
 .../groovy/macro/matcher/ASTFinder.java         | 25 ++++---
 .../groovy/macro/matcher/ASTMatcher.groovy      | 25 ++++---
 .../groovy/macro/matcher/ASTNodePredicate.java  | 25 ++++---
 .../matcher/ContextualClassCodeVisitor.java     | 25 ++++---
 .../groovy/macro/matcher/MatcherUtils.java      | 25 ++++---
 .../macro/matcher/MatchingConstraints.groovy    | 26 +++----
 .../groovy/macro/matcher/NodeComparator.java    | 25 ++++---
 .../groovy/macro/matcher/TreeContext.java       | 25 ++++---
 .../groovy/macro/matcher/TreeContextAction.java | 25 ++++---
 .../macro/matcher/internal/AnyTokenMatch.groovy | 26 +++----
 .../matcher/internal/ConstraintPredicate.groovy | 28 ++++----
 .../internal/MatchingConstraintsBuilder.groovy  | 28 ++++----
 .../groovy/macro/runtime/MacroBuilder.java      | 25 ++++---
 .../macro/runtime/MacroGroovyMethods.java       | 27 +++----
 .../macro/runtime/MacroSubstitutionKey.java     | 29 ++++----
 .../groovy/macro/transform/MacroClass.java      | 25 ++++---
 .../macro/transform/MacroInvocationTrap.java    | 25 ++++---
 .../macro/transform/MacroTransformation.java    | 26 +++----
 .../macro/transform/TransformingMacroTrap.java  | 25 ++++---
 ....codehaus.groovy.transform.ASTTransformation | 17 ++++-
 .../org/codehaus/groovy/macro/MacroTest.groovy  | 74 ++++++++++----------
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 26 +++----
 23 files changed, 358 insertions(+), 269 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/build.gradle
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/build.gradle b/subprojects/groovy-macro/build.gradle
index bc9c210..d9949ca 100644
--- a/subprojects/groovy-macro/build.gradle
+++ b/subprojects/groovy-macro/build.gradle
@@ -1,3 +1,21 @@
+/*
+ *  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.
+ */
 dependencies {
     compile rootProject
     testCompile rootProject.sourceSets.test.runtimeClasspath
@@ -8,4 +26,4 @@ task moduleDescriptor(type: org.codehaus.groovy.gradle.WriteExtensionDescriptorT
     extensionClasses = 'org.codehaus.groovy.macro.runtime.MacroGroovyMethods,org.codehaus.groovy.macro.matcher.ASTMatcher'
 }
 
-compileJava.dependsOn moduleDescriptor
\ No newline at end of file
+compileJava.dependsOn moduleDescriptor

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
index 92957ce..05f3bba 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 77bdb0d..bbb0168 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
index f69e837..4a19314 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
index 36f6105..a8a6bc2 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
index 7f7ac09..c8e4068 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
index cb30145..c3bfdbd 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
 
 import groovy.transform.CompileStatic

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
index 7f55481..e709c40 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
index 6c77d25..741c491 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
index 2c198d3..c0c39c7 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
index afc91c1..bbe2a96 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
 
 import groovy.transform.CompileStatic

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
index 5c4fdc8..f444552 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
 
 import groovy.transform.CompileStatic
@@ -21,4 +23,4 @@ import groovy.transform.CompileStatic
 @CompileStatic
 interface ConstraintPredicate<T> {
     boolean apply(T a)
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
index 5060089..0c4d195 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
 
 import org.codehaus.groovy.ast.ASTNode
@@ -79,4 +81,4 @@ class MatchingConstraintsBuilder {
         }
         this
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index 2895ebf..2e78d28 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
index 5c41c04..7e39589 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
 
@@ -28,7 +31,7 @@ public class MacroGroovyMethods {
     public static class MacroValuePlaceholder {
         public static Object $v(Closure cl) {
             // replaced with AST transformations
-            return null; 
+            return null;
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
index e895867..3f72cff 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
 
@@ -38,7 +41,7 @@ public class MacroSubstitutionKey {
         this.endLine = endLine;
         this.endColumn = endColumn;
     }
-    
+
     public MacroSubstitutionKey(Expression expression, int linesOffset, int columnsOffset) {
         this(
                 expression.getLineNumber() - linesOffset,
@@ -47,7 +50,7 @@ public class MacroSubstitutionKey {
                 expression.getLastColumnNumber() - (expression.getLastLineNumber() == linesOffset ? columnsOffset : 0)
         );
     }
-    
+
     public ConstructorCallExpression toConstructorCallExpression() {
         return new ConstructorCallExpression(
                 ClassHelper.make(this.getClass()),

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
index 46dc062..0b01efa 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroClass.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.transform;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index df13f38..b75a768 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
index 7920e2e..06de16f 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
 
@@ -54,4 +57,3 @@ public class MacroTransformation extends MethodCallTransformation {
         return new TransformingMacroTrap(sourceUnit, trn);
     }
 }
-

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
index 35ddf55..f16e47a 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/TransformingMacroTrap.java
@@ -1,17 +1,20 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.transform;
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation b/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
index 09d8397..c2ef479 100644
--- a/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
+++ b/subprojects/groovy-macro/src/main/resources/META-INF/services/org.codehaus.groovy.transform.ASTTransformation
@@ -1,2 +1,17 @@
+# 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.
+
 #global transformation for macro support
-org.codehaus.groovy.macro.transform.MacroTransformation
\ No newline at end of file
+org.codehaus.groovy.macro.transform.MacroTransformation

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
index dfff23abb..3b740c9 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/MacroTest.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2015 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 org.codehaus.groovy.macro
 
 import groovy.transform.CompileStatic;
@@ -24,56 +26,56 @@ import groovy.transform.CompileStatic;
  */
 @CompileStatic
 class MacroTest extends GroovyTestCase {
-    
+
     void testSimpleCase() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
         import org.codehaus.groovy.ast.stmt.*;
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
-        
+
         def someVariable = new VariableExpression("someVariable");
 
         ReturnStatement result = macro {
             return new NonExistingClass($v{someVariable});
         }
-        
+
         def expected = returnS(ctorX(ClassHelper.make("NonExistingClass"), args(someVariable)))
 
         AstAssert.assertSyntaxTree([expected], [result]);
 '''
     }
-    
+
     void testAsIs() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
         import org.codehaus.groovy.ast.stmt.*;
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
-        
+
         BlockStatement result = macro(true) {
             println "foo"
         }
-        
+
         def expected = block(stmt(callThisX("println", args(constX("foo")))))
 
         AstAssert.assertSyntaxTree([expected], [result]);
 '''
     }
-    
+
     void testInception() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
         import org.codehaus.groovy.ast.stmt.*;
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
-        
+
         ConstructorCallExpression result = macro {
             new NonExistingClass($v{macro {someVariable}});
         }
@@ -91,16 +93,16 @@ class MacroTest extends GroovyTestCase {
         assert "valueOf" == macro { String.valueOf() }.getMethodAsString()
 '''
     }
-    
+
     void testBlock() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
         import org.codehaus.groovy.ast.stmt.*;
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
-        
+
         def result = macro {
             println "foo"
             println "bar"
@@ -110,11 +112,11 @@ class MacroTest extends GroovyTestCase {
             stmt(callThisX("println", args(constX("foo")))),
             stmt(callThisX("println", args(constX("bar")))),
         )
-        
+
         AstAssert.assertSyntaxTree([expected], [result]);
 '''
     }
-    
+
     void testCompilePhase() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
@@ -122,9 +124,9 @@ class MacroTest extends GroovyTestCase {
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
         import org.codehaus.groovy.control.CompilePhase;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
-        
+
 
         def result = macro(CompilePhase.FINALIZATION) {
             println "foo"
@@ -140,7 +142,7 @@ class MacroTest extends GroovyTestCase {
         AstAssert.assertSyntaxTree([expected], [result]);
 '''
     }
-    
+
     void testAsIsWithCompilePhase() {
         assertScript '''
         import org.codehaus.groovy.ast.expr.*;
@@ -148,21 +150,21 @@ class MacroTest extends GroovyTestCase {
         import org.codehaus.groovy.ast.ClassHelper;
         import org.codehaus.groovy.ast.builder.AstAssert;
         import org.codehaus.groovy.control.CompilePhase;
-        
+
         import static org.codehaus.groovy.ast.tools.GeneralUtils.*;
 
         def result = macro(CompilePhase.FINALIZATION, true) {
             println "foo"
         }
-        
+
         def expected = block(
             returnS(callThisX("println", args(constX("foo"))))
         )
-        
+
         AstAssert.assertSyntaxTree([expected], [result]);
 '''
     }
-    
+
     void testCompileStatic() {
         assertScript '''
         import groovy.transform.CompileStatic
@@ -178,7 +180,7 @@ class MacroTest extends GroovyTestCase {
                 return new NonExistingClass("foo");
             }
         }
-        
+
         def expected = returnS(ctorX(ClassHelper.make("NonExistingClass"), args(constX("foo"))))
 
         AstAssert.assertSyntaxTree([expected], [getReturnStatement()]);

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/9fee0243/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 172f457..d57459d 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -1,19 +1,21 @@
 /*
- * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
 
 import org.codehaus.groovy.ast.ClassNode


[16/37] incubator-groovy git commit: ASTMatcher:First test cases for class types

Posted by cc...@apache.org.
ASTMatcher:First test cases for class types


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/bac61a14
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/bac61a14
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/bac61a14

Branch: refs/heads/master
Commit: bac61a14d911484a81b4857109e17871c9af1dbf
Parents: 02e53fc
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 11:58:41 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 285 ++++++++++++-------
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 226 +++++++++++++++
 2 files changed, 405 insertions(+), 106 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bac61a14/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index ffcf09a..9158c32 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -19,10 +19,11 @@ import groovy.transform.CompileStatic
 import groovy.transform.TypeCheckingMode
 import org.codehaus.groovy.ast.*
 import org.codehaus.groovy.ast.expr.*
-import org.codehaus.groovy.ast.stmt.*
+import org.codehaus.groovy.ast.stmt.BlockStatement
+import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.ast.stmt.Statement
 import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
-import org.codehaus.groovy.transform.stc.StaticTypesMarker
 
 @CompileStatic
 class ASTMatcher extends ClassCodeVisitorSupport {
@@ -57,6 +58,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         matcher.match
     }
 
+    private boolean failIfNot(boolean value) {
+        match = match && value
+    }
+
     /**
      * Locates all nodes in the given AST which match the pattern AST.
      * This operation can cost a lot, because it tries to match a sub-tree
@@ -73,13 +78,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     }
 
     private void doWithNode(Class expectedClass, Object next, Closure cl) {
-        if (match && (next==null || expectedClass.isAssignableFrom(next.class))) {
+        if (expectedClass == null) {
+            expectedClass = Object
+        }
+        if (match && (next == null || expectedClass.isAssignableFrom(next.class))) {
             Object old = current
             current = next
             cl()
             current = old
         } else {
-            match = false
+            failIfNot(false)
         }
     }
 
@@ -87,15 +95,22 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitClass(final ClassNode node) {
         doWithNode(ClassNode, current) {
             visitAnnotations(node)
-        }
-        doWithNode(PackageNode, ((ClassNode) current).package) {
-            visitPackage(node.package)
-        }
-        doWithNode(ModuleNode, ((ClassNode) current).module) {
-            visitImports(node.module)
-        }
-        doWithNode(ClassNode, current) {
+            doWithNode(PackageNode, ((ClassNode) current).package) {
+                visitPackage(node.package)
+            }
+            doWithNode(ModuleNode, ((ClassNode) current).module) {
+                visitImports(node.module)
+            }
+
             def cur = (ClassNode) current
+            def intfs = node.interfaces
+            def curIntfs = cur.interfaces
+            failIfNot(intfs.length == curIntfs.length)
+            if (intfs.length == curIntfs.length) {
+                for (int i = 0; i < intfs.length && match; i++) {
+                    failIfNot(intfs[i] == curIntfs[i])
+                }
+            }
             def nodeProps = node.properties
             def curProps = cur.properties
             if (nodeProps.size() == curProps.size()) {
@@ -109,7 +124,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
                 def nodeFields = node.fields
                 def curFields = cur.fields
-                if (nodeFields.size()==curFields.size()) {
+                if (nodeFields.size() == curFields.size()) {
                     iter = curFields.iterator()
                     for (FieldNode fn : nodeFields) {
                         doWithNode(fn.class, iter.next()) {
@@ -119,7 +134,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
                     def nodeConstructors = node.declaredConstructors
                     def curConstructors = cur.declaredConstructors
-                    if (nodeConstructors.size()==curConstructors.size()) {
+                    if (nodeConstructors.size() == curConstructors.size()) {
                         iter = curConstructors.iterator()
                         for (ConstructorNode cn : nodeConstructors) {
                             doWithNode(cn.class, iter.next()) {
@@ -140,19 +155,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         }
                     }
                 }
-
-
-                return
             }
-            match = false
+            failIfNot(cur.name == node.name)
         }
     }
 
     @Override
     protected void visitObjectInitializerStatements(final ClassNode node) {
         doWithNode(ClassNode, current) {
-            def initializers = ((ClassNode)current).objectInitializerStatements
-            if (initializers.size()==node.objectInitializerStatements.size()) {
+            def initializers = ((ClassNode) current).objectInitializerStatements
+            if (initializers.size() == node.objectInitializerStatements.size()) {
                 def iterator = initializers.iterator()
                 for (Statement element : node.objectInitializerStatements) {
                     doWithNode(element.class, iterator.next()) {
@@ -160,7 +172,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     }
                 }
             } else {
-                match = false
+                failIfNot(false)
             }
         }
     }
@@ -190,7 +202,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         }
                     }
                 } else {
-                    match = false
+                    failIfNot(false)
                     return
                 }
                 imports = module.starImports
@@ -203,7 +215,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         }
                     }
                 } else {
-                    match = false
+                    failIfNot(false)
                     return
                 }
                 imports = module.staticImports
@@ -216,8 +228,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         }
                     }
                 } else {
-                    match = false
-                    return
+                    failIfNot(false)
                 }
                 imports = module.staticStarImports
                 if (imports.size() == node.staticStarImports.size()) {
@@ -229,8 +240,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         }
                     }
                 } else {
-                    match = false
-                    return
+                    failIfNot(false)
                 }
             }
         }
@@ -242,39 +252,39 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             List<AnnotationNode> refAnnotations = node.annotations
             AnnotatedNode cur = (AnnotatedNode) current
             List<AnnotationNode> curAnnotations = cur.annotations
-            if (refAnnotations.size()!=curAnnotations.size()) {
-                match = false
+            if (refAnnotations.size() != curAnnotations.size()) {
+                failIfNot(false)
                 return
             }
             if (refAnnotations.empty) return
             def iter = curAnnotations.iterator()
             for (AnnotationNode an : refAnnotations) {
                 AnnotationNode curNext = iter.next()
+
                 // skip built-in properties
                 if (an.builtIn) {
                     if (!curNext.builtIn) {
-                        match = false
-                        return
+                        failIfNot(false)
                     }
                     continue
                 }
-
+                failIfNot(an.classNode==curNext.classNode)
                 def refEntrySet = an.members.entrySet()
                 def curEntrySet = curNext.members.entrySet()
-                if (refEntrySet.size()==curEntrySet.size()) {
+                if (refEntrySet.size() == curEntrySet.size()) {
                     def entryIt = curEntrySet.iterator()
                     for (Map.Entry<String, Expression> member : refEntrySet) {
                         def next = entryIt.next()
-                        if (next.key==member.key) {
+                        if (next.key == member.key) {
                             doWithNode(member.value.class, next.value) {
                                 member.value.visit(this)
                             }
                         } else {
-                            match = false
+                            failIfNot(false)
                         }
                     }
                 } else {
-                    match = false
+                    failIfNot(false)
                 }
             }
         }
@@ -307,14 +317,14 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
             def params = node.parameters
             def curParams = cur.parameters
-            if (params.length==curParams.length) {
+            if (params.length == curParams.length) {
                 params.eachWithIndex { Parameter entry, int i ->
                     doWithNode(entry.class, curParams[i]) {
                         visitAnnotations(entry)
                     }
                 }
             } else {
-                match = false
+                failIfNot(false)
             }
         }
     }
@@ -324,23 +334,23 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         doWithNode(FieldNode, current) {
             visitAnnotations(node)
             def fieldNode = (FieldNode) current
-            if (fieldNode.name==node.name) {
-                Expression init = node.initialExpression
-
-                Expression curInit = fieldNode.initialExpression
-                if (init) {
-                    if (curInit) {
-                        doWithNode(init.class, curInit) {
-                            init.visit(this)
-                        }
-                    } else {
-                        match = false
+            failIfNot(fieldNode.name == node.name)
+            failIfNot(fieldNode.originType == node.originType)
+            failIfNot(fieldNode.modifiers == node.modifiers)
+
+            Expression init = node.initialExpression
+
+            Expression curInit = fieldNode.initialExpression
+            if (init) {
+                if (curInit) {
+                    doWithNode(init.class, curInit) {
+                        init.visit(this)
                     }
-                } else if (curInit) {
-                    match = false
+                } else {
+                    failIfNot(false)
                 }
-            } else {
-                match = false
+            } else if (curInit) {
+                failIfNot(false)
             }
         }
     }
@@ -353,13 +363,13 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
             Statement statement = node.getterBlock
             Statement curStatement = pNode.getterBlock
-            doWithNode(statement.class, curStatement) {
+            doWithNode(statement?.class, curStatement) {
                 visitClassCodeContainer(statement)
             }
 
             statement = node.setterBlock
             curStatement = pNode.setterBlock
-            doWithNode(statement.class, curStatement) {
+            doWithNode(statement?.class, curStatement) {
                 visitClassCodeContainer(statement)
             }
 
@@ -371,10 +381,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         init.visit(this)
                     }
                 } else {
-                    match = false
+                    failIfNot(false)
                 }
             } else if (curInit) {
-                match = false
+                failIfNot(false)
             }
         }
     }
@@ -382,7 +392,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     void visitExpressionStatement(final ExpressionStatement statement) {
         visitStatement(statement)
-        doWithNode(statement.expression.class, ((ExpressionStatement)current).expression) {
+        doWithNode(statement.expression.class, ((ExpressionStatement) current).expression) {
             statement.expression.visit(this)
         }
     }
@@ -391,7 +401,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitBlockStatement(BlockStatement block) {
         doWithNode(BlockStatement, current) {
             def statements = ((BlockStatement) current).statements
-            if (statements.size()==block.statements.size()) {
+            if (statements.size() == block.statements.size()) {
                 def iter = statements.iterator()
                 for (Statement statement : block.statements) {
                     doWithNode(statement.class, iter.next()) {
@@ -399,7 +409,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     }
                 }
             } else {
-                match = false
+                failIfNot(false)
             }
         }
     }
@@ -417,10 +427,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             doWithNode(call.arguments.class, mce.arguments) {
                 call.arguments.visit(this)
             }
-            match = match && (call.methodAsString==mce.methodAsString) &&
-                    (call.safe==mce.safe) &&
+            failIfNot((call.methodAsString == mce.methodAsString) &&
+                    (call.safe == mce.safe) &&
                     (call.spreadSafe == mce.spreadSafe) &&
-                    (call.implicitThis == mce.implicitThis)
+                    (call.implicitThis == mce.implicitThis))
         }
     }
 
@@ -434,8 +444,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         def cur = (ConstructorCallExpression) current
         doWithNode(call.arguments.class, cur.arguments) {
             call.arguments.visit(this)
-            match = match &&
-                    (call.type == cur.type)
+            failIfNot(call.type == cur.type)
         }
     }
 
@@ -451,8 +460,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             doWithNode(rightExpression.class, bin.rightExpression) {
                 rightExpression.visit(this)
             }
-            if (bin.operation.type!=expression.operation.type) {
-                match = false
+            if (bin.operation.type != expression.operation.type) {
+                failIfNot(false)
             }
         }
     }
@@ -482,8 +491,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             def curExpr = (PostfixExpression) current
             doWithNode(origExpr.class, curExpr.expression) {
                 origExpr.visit(this)
-                match = match &&
-                        (expression.operation.type==curExpr.operation.type)
+                failIfNot(expression.operation.type == curExpr.operation.type)
             }
         }
     }
@@ -495,8 +503,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             def curExpr = (PrefixExpression) current
             doWithNode(origExpr.class, curExpr.expression) {
                 origExpr.visit(this)
-                match = match &&
-                        (expression.operation.type==curExpr.operation.type)
+                failIfNot(expression.operation.type == curExpr.operation.type)
             }
         }
     }
@@ -504,7 +511,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     public void visitBooleanExpression(final BooleanExpression expression) {
         doWithNode(BooleanExpression, current) {
-            doWithNode(expression.expression.class, ((BooleanExpression)current).expression) {
+            doWithNode(expression.expression.class, ((BooleanExpression) current).expression) {
                 expression.expression.visit(this)
             }
         }
@@ -514,7 +521,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitNotExpression(final NotExpression expression) {
         doWithNode(NotExpression, current) {
             def expr = expression.expression
-            def cur = ((NotExpression)current).expression
+            def cur = ((NotExpression) current).expression
             doWithNode(expr.class, cur) {
                 expr.visit(this)
             }
@@ -534,24 +541,23 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     }
 
     private void checkParameters(Parameter[] nodeParams, Parameter[] curParams) {
-        if (nodeParams==null && curParams!=null || nodeParams!=null && curParams==null) {
-            match = false
+        if (nodeParams == null && curParams != null || nodeParams != null && curParams == null) {
+            failIfNot(false)
             return
         }
         if (nodeParams) {
-            if (curParams.length==nodeParams.length) {
+            if (curParams.length == nodeParams.length) {
                 for (int i = 0; i < nodeParams.length && match; i++) {
                     def n = nodeParams[i]
                     def c = curParams[i]
                     doWithNode(n.class, c) {
-                        match = match &&
-                                (n.name == c.name) &&
+                        failIfNot((n.name == c.name) &&
                                 (n.originType == c.originType) &&
-                                (n.type == c.originType)
+                                (n.type == c.originType))
                     }
                 }
             } else {
-                match = false
+                failIfNot(false)
             }
         }
     }
@@ -569,7 +575,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitListExpression(final ListExpression expression) {
         doWithNode(ListExpression, current) {
             def exprs = expression.expressions
-            doWithNode(exprs.class, ((ListExpression)current).expressions) {
+            doWithNode(exprs.class, ((ListExpression) current).expressions) {
                 visitListOfExpressions(exprs)
             }
         }
@@ -577,14 +583,27 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitArrayExpression(final ArrayExpression expression) {
-        super.visitArrayExpression(expression);
+        doWithNode(ArrayExpression, current) {
+            def expressions = expression.expressions
+            def size = expression.sizeExpression
+            def cur = (ArrayExpression) current
+            def curExprs = cur.expressions
+            def curSize = cur.sizeExpression
+            doWithNode(expressions.class, curExprs) {
+                visitListOfExpressions(expressions)
+            }
+            doWithNode(size.class, curSize) {
+                visitListOfExpressions(size)
+            }
+            failIfNot(expression.elementType == cur.elementType)
+        }
     }
 
     @Override
     public void visitMapExpression(final MapExpression expression) {
         doWithNode(MapExpression, current) {
             def entries = expression.mapEntryExpressions
-            def curEntries = ((MapExpression)current).mapEntryExpressions
+            def curEntries = ((MapExpression) current).mapEntryExpressions
             doWithNode(entries.class, curEntries) {
                 visitListOfExpressions(entries)
             }
@@ -629,7 +648,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitSpreadExpression(final SpreadExpression expression) {
         doWithNode(SpreadExpression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((SpreadExpression)current).expression) {
+            doWithNode(expr.class, ((SpreadExpression) current).expression) {
                 expr.visit(this)
             }
         }
@@ -642,27 +661,60 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMethodPointerExpression(final MethodPointerExpression expression) {
-        super.visitMethodPointerExpression(expression);
+        doWithNode(MethodPointerExpression, current) {
+            def cur = (MethodPointerExpression) current
+            def expr = expression.expression
+            def methodName = expression.methodName
+            def curExpr = cur.expression
+            def curName = cur.methodName
+            doWithNode(expr.class, curExpr) {
+                expr.visit(this)
+            }
+            doWithNode(methodName.class, curName) {
+                methodName.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
-        super.visitUnaryMinusExpression(expression);
+        doWithNode(UnaryMinusExpression, current) {
+            def expr = expression.expression
+            doWithNode(expr.class, ((UnaryMinusExpression) current).expression) {
+                expr.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
-        super.visitUnaryPlusExpression(expression);
+        doWithNode(UnaryPlusExpression, current) {
+            def expr = expression.expression
+            doWithNode(expr.class, ((UnaryPlusExpression) current).expression) {
+                expr.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
-        super.visitBitwiseNegationExpression(expression);
+        doWithNode(BitwiseNegationExpression, current) {
+            def expr = expression.expression
+            doWithNode(expr.class, ((BitwiseNegationExpression) current).expression) {
+                expr.visit(this)
+            }
+        }
     }
 
     @Override
     public void visitCastExpression(final CastExpression expression) {
-        super.visitCastExpression(expression);
+        doWithNode(CastExpression, current) {
+            def expr = expression.expression
+            doWithNode(expr.class, ((CastExpression) current).expression) {
+                expr.visit(this)
+            }
+            failIfNot(expression.type == ((CastExpression) current).type)
+        }
     }
 
     @Override
@@ -671,9 +723,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         doWithNode(ConstantExpression, current) {
             def cur = (ConstantExpression) current
             super.visitConstantExpression(expression)
-            match = match &&
-                    (expression.type==cur.type) &&
-                    (expression.value==cur.value)
+            failIfNot((expression.type == cur.type) &&
+                    (expression.value == cur.value))
         }
     }
 
@@ -683,7 +734,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         doWithNode(ClassExpression, current) {
             super.visitClassExpression(expression)
             def cexp = (ClassExpression) current
-            match = match && (cexp.type == expression.type)
+            failIfNot(cexp.type == expression.type)
         }
     }
 
@@ -691,10 +742,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitVariableExpression(final VariableExpression expression) {
         doWithNode(VariableExpression, current) {
             def curVar = (VariableExpression) current
-            match = match &&
-                    (expression.name == curVar.name) &&
+            failIfNot((expression.name == curVar.name) &&
                     (expression.type == curVar.type) &&
-                    (expression.originType == curVar.originType)
+                    (expression.originType == curVar.originType))
         }
     }
 
@@ -708,17 +758,28 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             doWithNode(expression.property.class, currentPexp.property) {
                 expression.property.visit(this)
             }
-            match = match &&
-                    (expression.propertyAsString==currentPexp.propertyAsString) &&
-                    (expression.implicitThis==currentPexp.implicitThis) &&
-                    (expression.safe==currentPexp.safe) &&
-                    (expression.spreadSafe==currentPexp.spreadSafe)
+            failIfNot((expression.propertyAsString == currentPexp.propertyAsString) &&
+                    (expression.implicitThis == currentPexp.implicitThis) &&
+                    (expression.safe == currentPexp.safe) &&
+                    (expression.spreadSafe == currentPexp.spreadSafe))
         }
     }
 
     @Override
     public void visitAttributeExpression(final AttributeExpression expression) {
-        super.visitAttributeExpression(expression);
+        doWithNode(AttributeExpression, current) {
+            def currentPexp = (AttributeExpression) current
+            doWithNode(expression.objectExpression.class, currentPexp.objectExpression) {
+                expression.objectExpression.visit(this)
+            }
+            doWithNode(expression.property.class, currentPexp.property) {
+                expression.property.visit(this)
+            }
+            failIfNot((expression.propertyAsString == currentPexp.propertyAsString) &&
+                    (expression.implicitThis == currentPexp.implicitThis) &&
+                    (expression.safe == currentPexp.safe) &&
+                    (expression.spreadSafe == currentPexp.spreadSafe))
+        }
     }
 
     @Override
@@ -728,15 +789,27 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitGStringExpression(final GStringExpression expression) {
-        super.visitGStringExpression(expression);
+        doWithNode(GStringExpression, current) {
+            def cur = (GStringExpression) current
+            def strings = expression.strings
+            def values = expression.values
+            def curStrings = cur.strings
+            def curValues = cur.values
+            doWithNode(strings.class, curStrings) {
+                visitListOfExpressions(strings)
+            }
+            doWithNode(values.class, curValues) {
+                visitListOfExpressions(values)
+            }
+        }
     }
 
     @Override
     protected void visitListOfExpressions(final List<? extends Expression> list) {
         if (list == null) return;
         def currentExprs = (List<Expression>) current
-        if (currentExprs.size()!=list.size()) {
-            match = false
+        if (currentExprs.size() != list.size()) {
+            failIfNot(false)
             return
         }
         def iter = currentExprs.iterator()
@@ -745,7 +818,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             if (expression instanceof SpreadExpression) {
                 doWithNode(SpreadExpression, next) {
                     Expression spread = ((SpreadExpression) expression).getExpression()
-                    doWithNode(Expression, ((SpreadExpression)current).expression) {
+                    doWithNode(Expression, ((SpreadExpression) current).expression) {
                         spread.visit(this)
                     }
                 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bac61a14/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 064e01c..ef7c489 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -16,9 +16,18 @@
 
 package org.codehaus.groovy.macro.matcher
 
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.expr.ArrayExpression
+import org.codehaus.groovy.ast.expr.BitwiseNegationExpression
+import org.codehaus.groovy.ast.expr.CastExpression
 import org.codehaus.groovy.ast.expr.ClassExpression
+import org.codehaus.groovy.ast.expr.GStringExpression
+import org.codehaus.groovy.ast.expr.MethodPointerExpression
 import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.UnaryMinusExpression
+import org.codehaus.groovy.ast.expr.UnaryPlusExpression
 import org.codehaus.groovy.control.CompilePhase
+import org.codehaus.groovy.macro.transform.MacroClass
 
 class ASTMatcherTest extends GroovyTestCase {
     void testMatchesSimpleVar() {
@@ -77,6 +86,22 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast1, ast6)
     }
 
+    void testAttributeExpression() {
+        def ast1 = macro { this.@p }
+        def ast2 = macro { this.@p }
+        def ast3 = macro { that.@p }
+        def ast4 = macro { this.@p2 }
+        def ast5 = macro { this?.@p }
+        def ast6 = macro { this*.@p }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+    }
+
     void testClassExpression() {
         def ast1 = macro(CompilePhase.SEMANTIC_ANALYSIS) { String }
         def ast2 = macro(CompilePhase.SEMANTIC_ANALYSIS) { String }
@@ -289,4 +314,205 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast1, ast3)
         assert !ASTMatcher.matches(ast1, ast4)
     }
+
+    void testArrayExpression() {
+        def ast1 = macro { new Integer[0] }
+        def ast2 = macro { new Integer[0] }
+        def ast3 = macro { new Integer[1] }
+        def ast4 = macro { new int[0] }
+        def ast5 = macro { new Integer[a] }
+        assert ast1 instanceof ArrayExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+    }
+
+    void testMethodPointerExpression() {
+        def ast1 = macro { this.&foo }
+        def ast2 = macro { this.&foo }
+        def ast3 = macro { that.&foo }
+        def ast4 = macro { this.&bar }
+        assert ast1 instanceof MethodPointerExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testUnaryMinus() {
+        def ast1 = macro { -a }
+        def ast2 = macro { -a }
+        def ast3 = macro { -0 }
+        def ast4 = macro { a }
+        assert ast1 instanceof UnaryMinusExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testUnaryPlus() {
+        def ast1 = macro { +a }
+        def ast2 = macro { +a }
+        def ast3 = macro { +0 }
+        def ast4 = macro { a }
+        assert ast1 instanceof UnaryPlusExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testBitwiseNegate() {
+        def ast1 = macro { ~a }
+        def ast2 = macro { ~a }
+        def ast3 = macro { ~0 }
+        def ast4 = macro { a }
+        assert ast1 instanceof BitwiseNegationExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testCastExpression() {
+        def ast1 = macro { (String) foo }
+        def ast2 = macro { (String) foo }
+        def ast3 = macro { (Integer) foo }
+        def ast4 = macro { (String) bar }
+        assert ast1 instanceof CastExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testGStringExpression() {
+        def ast1 = macro { "123$a" }
+        def ast2 = macro { "123$a" }
+        def ast3 = macro { "$a" }
+        def ast4 = macro { "123$b" }
+        assert ast1 instanceof GStringExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testClassComparison() {
+        def ast1 = new MacroClass() {
+            class A {}
+        }
+        def ast2 = new MacroClass() {
+            class A {}
+        }
+        def ast3 = new MacroClass() {
+            class A implements Serializable {}
+        }
+        def ast4 = new MacroClass() {
+            class B {}
+        }
+        assert ast1 instanceof ClassNode
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testPropertyComparison() {
+        def ast1 = new MacroClass() {
+            class A { String str }
+        }
+        def ast2 = new MacroClass() {
+            class A { String str }
+        }
+        def ast3 = new MacroClass() {
+            class A { String foo }
+        }
+        def ast4 = new MacroClass() {
+            class A { Integer str }
+        }
+        def ast5 = new MacroClass() {
+            class A { String str = null }
+        }
+        def ast6 = new MacroClass() {
+            class A { String str = 'foo' }
+        }
+        def ast7 = new MacroClass() {
+            class A { String str = 'bar' }
+        }
+        def ast8 = new MacroClass() {
+            class A { @Foo String str }
+        }
+        def ast9 = new MacroClass() {
+            class A { @Bar String str }
+        }
+        assert ast1 instanceof ClassNode
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+        assert !ASTMatcher.matches(ast6, ast7)
+        assert !ASTMatcher.matches(ast1, ast8)
+        assert ASTMatcher.matches(ast8, ast8)
+        assert !ASTMatcher.matches(ast8, ast9)
+    }
+    void testFieldComparison() {
+        def ast1 = new MacroClass() {
+            class A { public String str }
+        }
+        def ast2 = new MacroClass() {
+            class A { public String str }
+        }
+        def ast3 = new MacroClass() {
+            class A { public String foo }
+        }
+        def ast4 = new MacroClass() {
+            class A { public Integer str }
+        }
+        def ast5 = new MacroClass() {
+            class A { public String str = null }
+        }
+        def ast6 = new MacroClass() {
+            class A { public String str = 'foo' }
+        }
+        def ast7 = new MacroClass() {
+            class A { public String str = 'bar' }
+        }
+        def ast8 = new MacroClass() {
+            class A { public @Foo String str }
+        }
+        def ast9 = new MacroClass() {
+            class A { public @Bar String str }
+        }
+        def ast10 = new MacroClass() {
+            class A { private String str }
+        }
+        assert ast1 instanceof ClassNode
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+        assert !ASTMatcher.matches(ast6, ast7)
+        assert !ASTMatcher.matches(ast1, ast8)
+        assert ASTMatcher.matches(ast8, ast8)
+        assert !ASTMatcher.matches(ast8, ast9)
+        assert !ASTMatcher.matches(ast1, ast10)
+    }
 }



[26/37] incubator-groovy git commit: ASTMatcher: First bits of work for wildcard matching

Posted by cc...@apache.org.
ASTMatcher: First bits of work for wildcard matching


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/1cd27ea2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/1cd27ea2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/1cd27ea2

Branch: refs/heads/master
Commit: 1cd27ea261a9eb712234e996115dcc5d3f039f53
Parents: 4b7db4c
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 16:05:26 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:11 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 240 ++++++++++---------
 .../groovy/macro/matcher/ASTMatcherTest.groovy  |  30 +++
 2 files changed, 157 insertions(+), 113 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/1cd27ea2/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 0020aeb..858924b 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -32,6 +32,8 @@ import org.codehaus.groovy.control.SourceUnit
 @CompileStatic
 class ASTMatcher extends ClassCodeVisitorSupport {
 
+    public static final String WILDCARD = "_";
+
     private Object current = null
     private boolean match = true
 
@@ -66,6 +68,14 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         match = match && value
     }
 
+    private static boolean matchByName(String a, String b) {
+        return a.equals(b) || WILDCARD.equals(a) || WILDCARD.equals(b);
+    }
+
+    private static boolean isWildcardExpression(Object exp) {
+        return exp instanceof VariableExpression && WILDCARD.equals(exp.getName());
+    }
+
     /**
      * Locates all nodes in the given AST which match the pattern AST.
      * This operation can cost a lot, because it tries to match a sub-tree
@@ -81,10 +91,14 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         finder.matches
     }
 
-    private void doWithNode(Class expectedClass, Object next, Closure cl) {
+    private void doWithNode(Object search, Object next, Closure cl) {
+        Class expectedClass = search?search.class:Object
         if (expectedClass == null) {
             expectedClass = Object
         }
+        if (isWildcardExpression(search)) {
+            return
+        }
         if (match && (next == null || expectedClass.isAssignableFrom(next.class))) {
             Object old = current
             current = next
@@ -97,12 +111,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitClass(final ClassNode node) {
-        doWithNode(ClassNode, current) {
+        doWithNode(node, current) {
             visitAnnotations(node)
-            doWithNode(PackageNode, ((ClassNode) current).package) {
+            doWithNode(node.package, ((ClassNode) current).package) {
                 visitPackage(node.package)
             }
-            doWithNode(ModuleNode, ((ClassNode) current).module) {
+            doWithNode(node.module, ((ClassNode) current).module) {
                 visitImports(node.module)
             }
 
@@ -123,7 +137,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 def iter = curProps.iterator()
                 // now let's visit the contents of the class
                 for (PropertyNode pn : nodeProps) {
-                    doWithNode(pn.class, iter.next()) {
+                    doWithNode(pn, iter.next()) {
                         visitProperty(pn)
                     }
                 }
@@ -133,7 +147,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 if (nodeFields.size() == curFields.size()) {
                     iter = curFields.iterator()
                     for (FieldNode fn : nodeFields) {
-                        doWithNode(fn.class, iter.next()) {
+                        doWithNode(fn, iter.next()) {
                             visitField(fn)
                         }
                     }
@@ -143,7 +157,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     if (nodeConstructors.size() == curConstructors.size()) {
                         iter = curConstructors.iterator()
                         for (ConstructorNode cn : nodeConstructors) {
-                            doWithNode(cn.class, iter.next()) {
+                            doWithNode(cn, iter.next()) {
                                 visitConstructor(cn)
                             }
                         }
@@ -153,7 +167,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                         if (nodeMethods.size() == curMethods.size()) {
                             iter = curMethods.iterator()
                             for (MethodNode mn : nodeMethods) {
-                                doWithNode(mn.class, iter.next()) {
+                                doWithNode(mn, iter.next()) {
                                     visitMethod(mn)
                                 }
                             }
@@ -162,18 +176,18 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     }
                 }
             }
-            failIfNot(cur.name == node.name)
+            failIfNot(matchByName(cur.name,node.name))
         }
     }
 
     @Override
     protected void visitObjectInitializerStatements(final ClassNode node) {
-        doWithNode(ClassNode, current) {
+        doWithNode(node, current) {
             def initializers = ((ClassNode) current).objectInitializerStatements
             if (initializers.size() == node.objectInitializerStatements.size()) {
                 def iterator = initializers.iterator()
                 for (Statement element : node.objectInitializerStatements) {
-                    doWithNode(element.class, iterator.next()) {
+                    doWithNode(element, iterator.next()) {
                         element.visit(this)
                     }
                 }
@@ -186,7 +200,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     public void visitPackage(final PackageNode node) {
         if (node) {
-            doWithNode(node.class, current) {
+            doWithNode(node, current) {
                 visitAnnotations(node)
                 node.visit(this)
             }
@@ -196,13 +210,13 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     public void visitImports(final ModuleNode node) {
         if (node) {
-            doWithNode(ModuleNode, current) {
+            doWithNode(node, current) {
                 ModuleNode module = (ModuleNode) current
                 def imports = module.imports
                 if (imports.size() == node.imports.size()) {
                     def iter = imports.iterator()
                     for (ImportNode importNode : node.imports) {
-                        doWithNode(importNode.class, iter.next()) {
+                        doWithNode(importNode, iter.next()) {
                             visitAnnotations(importNode)
                             importNode.visit(this)
                         }
@@ -215,7 +229,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 if (imports.size() == node.starImports.size()) {
                     def iter = imports.iterator()
                     for (ImportNode importNode : node.starImports) {
-                        doWithNode(importNode.class, iter.next()) {
+                        doWithNode(importNode, iter.next()) {
                             visitAnnotations(importNode)
                             importNode.visit(this)
                         }
@@ -228,7 +242,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 if (imports.size() == node.staticImports.size()) {
                     def iter = imports.values().iterator()
                     for (ImportNode importNode : node.staticImports.values()) {
-                        doWithNode(importNode.class, iter.next()) {
+                        doWithNode(importNode, iter.next()) {
                             visitAnnotations(importNode)
                             importNode.visit(this)
                         }
@@ -240,7 +254,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 if (imports.size() == node.staticStarImports.size()) {
                     def iter = imports.values().iterator()
                     for (ImportNode importNode : node.staticStarImports.values()) {
-                        doWithNode(importNode.class, iter.next()) {
+                        doWithNode(importNode, iter.next()) {
                             visitAnnotations(importNode)
                             importNode.visit(this)
                         }
@@ -254,7 +268,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitAnnotations(final AnnotatedNode node) {
-        doWithNode(AnnotatedNode, current) {
+        doWithNode(node, current) {
             List<AnnotationNode> refAnnotations = node.annotations
             AnnotatedNode cur = (AnnotatedNode) current
             List<AnnotationNode> curAnnotations = cur.annotations
@@ -282,7 +296,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     for (Map.Entry<String, Expression> member : refEntrySet) {
                         def next = entryIt.next()
                         if (next.key == member.key) {
-                            doWithNode(member.value.class, next.value) {
+                            doWithNode(member.value, next.value) {
                                 member.value.visit(this)
                             }
                         } else {
@@ -298,7 +312,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     protected void visitClassCodeContainer(final Statement code) {
-        doWithNode(Statement, current) {
+        doWithNode(code, current) {
             if (code) {
                 code.visit(this)
             }
@@ -308,24 +322,24 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     @CompileStatic(TypeCheckingMode.SKIP)
     public void visitDeclarationExpression(final DeclarationExpression expression) {
-        doWithNode(DeclarationExpression, current) {
+        doWithNode(expression, current) {
             super.visitDeclarationExpression(expression)
         }
     }
 
     @Override
     protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
-        doWithNode(MethodNode, current) {
+        doWithNode(node, current) {
             visitAnnotations(node)
             def cur = (MethodNode) current
-            doWithNode(Statement, cur.code) {
+            doWithNode(node.code, cur.code) {
                 visitClassCodeContainer(node.code)
             }
             def params = node.parameters
             def curParams = cur.parameters
             if (params.length == curParams.length) {
                 params.eachWithIndex { Parameter entry, int i ->
-                    doWithNode(entry.class, curParams[i]) {
+                    doWithNode(entry, curParams[i]) {
                         visitAnnotations(entry)
                     }
                 }
@@ -337,10 +351,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitField(final FieldNode node) {
-        doWithNode(FieldNode, current) {
+        doWithNode(node, current) {
             visitAnnotations(node)
             def fieldNode = (FieldNode) current
-            failIfNot(fieldNode.name == node.name)
+            failIfNot(matchByName(fieldNode.name,node.name))
             failIfNot(fieldNode.originType == node.originType)
             failIfNot(fieldNode.modifiers == node.modifiers)
 
@@ -349,7 +363,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             Expression curInit = fieldNode.initialExpression
             if (init) {
                 if (curInit) {
-                    doWithNode(init.class, curInit) {
+                    doWithNode(init, curInit) {
                         init.visit(this)
                     }
                 } else {
@@ -363,19 +377,19 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitProperty(final PropertyNode node) {
-        doWithNode(PropertyNode, current) {
+        doWithNode(node, current) {
             PropertyNode pNode = (PropertyNode) current
             visitAnnotations(node)
 
             Statement statement = node.getterBlock
             Statement curStatement = pNode.getterBlock
-            doWithNode(statement?.class, curStatement) {
+            doWithNode(statement, curStatement) {
                 visitClassCodeContainer(statement)
             }
 
             statement = node.setterBlock
             curStatement = pNode.setterBlock
-            doWithNode(statement?.class, curStatement) {
+            doWithNode(statement, curStatement) {
                 visitClassCodeContainer(statement)
             }
 
@@ -383,7 +397,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             Expression curInit = pNode.initialExpression
             if (init) {
                 if (curInit) {
-                    doWithNode(init.class, curInit) {
+                    doWithNode(init, curInit) {
                         init.visit(this)
                     }
                 } else {
@@ -397,7 +411,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     void visitExpressionStatement(final ExpressionStatement statement) {
-        doWithNode(statement.expression.class, ((ExpressionStatement) current).expression) {
+        doWithNode(statement.expression, ((ExpressionStatement) current).expression) {
             visitStatement(statement)
             statement.expression.visit(this)
         }
@@ -405,12 +419,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitBlockStatement(BlockStatement block) {
-        doWithNode(BlockStatement, current) {
+        doWithNode(block, current) {
             def statements = ((BlockStatement) current).statements
             if (statements.size() == block.statements.size()) {
                 def iter = statements.iterator()
                 for (Statement statement : block.statements) {
-                    doWithNode(statement.class, iter.next()) {
+                    doWithNode(statement, iter.next()) {
                         statement.visit(this)
                     }
                 }
@@ -422,18 +436,18 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMethodCallExpression(final MethodCallExpression call) {
-        doWithNode(MethodCallExpression, current) {
+        doWithNode(call, current) {
             def mce = (MethodCallExpression) current
-            doWithNode(call.objectExpression.class, mce.objectExpression) {
+            doWithNode(call.objectExpression, mce.objectExpression) {
                 call.objectExpression.visit(this)
             }
-            doWithNode(call.method.class, mce.method) {
+            doWithNode(call.method, mce.method) {
                 call.method.visit(this)
             }
-            doWithNode(call.arguments.class, mce.arguments) {
+            doWithNode(call.arguments, mce.arguments) {
                 call.arguments.visit(this)
             }
-            failIfNot((call.methodAsString == mce.methodAsString) &&
+            failIfNot(matchByName(call.methodAsString, mce.methodAsString) &&
                     (call.safe == mce.safe) &&
                     (call.spreadSafe == mce.spreadSafe) &&
                     (call.implicitThis == mce.implicitThis))
@@ -448,7 +462,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     public void visitConstructorCallExpression(final ConstructorCallExpression call) {
         def cur = (ConstructorCallExpression) current
-        doWithNode(call.arguments.class, cur.arguments) {
+        doWithNode(call.arguments, cur.arguments) {
             call.arguments.visit(this)
             failIfNot(call.type == cur.type)
         }
@@ -456,14 +470,14 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitBinaryExpression(final BinaryExpression expression) {
-        doWithNode(BinaryExpression, current) {
+        doWithNode(expression, current) {
             def bin = (BinaryExpression) current
             def leftExpression = expression.getLeftExpression()
-            doWithNode(leftExpression.class, bin.leftExpression) {
+            doWithNode(leftExpression, bin.leftExpression) {
                 leftExpression.visit(this)
             }
             def rightExpression = expression.getRightExpression()
-            doWithNode(rightExpression.class, bin.rightExpression) {
+            doWithNode(rightExpression, bin.rightExpression) {
                 rightExpression.visit(this)
             }
             if (bin.operation.type != expression.operation.type) {
@@ -474,17 +488,17 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitTernaryExpression(final TernaryExpression expression) {
-        doWithNode(TernaryExpression, current) {
+        doWithNode(expression, current) {
             TernaryExpression te = (TernaryExpression) current
-            doWithNode(BooleanExpression, te.booleanExpression) {
+            doWithNode(expression.booleanExpression, te.booleanExpression) {
                 expression.booleanExpression.visit(this)
             }
             def trueExpression = expression.trueExpression
-            doWithNode(trueExpression.class, te.trueExpression) {
+            doWithNode(trueExpression, te.trueExpression) {
                 trueExpression.visit(this)
             }
             def falseExpression = expression.falseExpression
-            doWithNode(falseExpression.class, te.falseExpression) {
+            doWithNode(falseExpression, te.falseExpression) {
                 falseExpression.visit(this)
             }
         }
@@ -492,10 +506,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitPostfixExpression(final PostfixExpression expression) {
-        doWithNode(PostfixExpression, current) {
+        doWithNode(expression, current) {
             def origExpr = expression.expression
             def curExpr = (PostfixExpression) current
-            doWithNode(origExpr.class, curExpr.expression) {
+            doWithNode(origExpr, curExpr.expression) {
                 origExpr.visit(this)
                 failIfNot(expression.operation.type == curExpr.operation.type)
             }
@@ -504,10 +518,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitPrefixExpression(final PrefixExpression expression) {
-        doWithNode(PrefixExpression, current) {
+        doWithNode(expression, current) {
             def origExpr = expression.expression
             def curExpr = (PrefixExpression) current
-            doWithNode(origExpr.class, curExpr.expression) {
+            doWithNode(origExpr, curExpr.expression) {
                 origExpr.visit(this)
                 failIfNot(expression.operation.type == curExpr.operation.type)
             }
@@ -516,8 +530,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitBooleanExpression(final BooleanExpression expression) {
-        doWithNode(BooleanExpression, current) {
-            doWithNode(expression.expression.class, ((BooleanExpression) current).expression) {
+        doWithNode(expression, current) {
+            doWithNode(expression.expression, ((BooleanExpression) current).expression) {
                 expression.expression.visit(this)
             }
         }
@@ -525,10 +539,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitNotExpression(final NotExpression expression) {
-        doWithNode(NotExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
             def cur = ((NotExpression) current).expression
-            doWithNode(expr.class, cur) {
+            doWithNode(expr, cur) {
                 expr.visit(this)
             }
         }
@@ -536,10 +550,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitClosureExpression(final ClosureExpression expression) {
-        doWithNode(ClosureExpression, current) {
+        doWithNode(expression, current) {
             def code = expression.code
             def cl = (ClosureExpression) current
-            doWithNode(code.class, cl.code) {
+            doWithNode(code, cl.code) {
                 code.visit(this)
                 checkParameters(expression.parameters, cl.parameters)
             }
@@ -556,8 +570,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                 for (int i = 0; i < nodeParams.length && match; i++) {
                     def n = nodeParams[i]
                     def c = curParams[i]
-                    doWithNode(n.class, c) {
-                        failIfNot((n.name == c.name) &&
+                    doWithNode(n, c) {
+                        failIfNot(matchByName(n.name,c.name) &&
                                 (n.originType == c.originType) &&
                                 (n.type == c.originType))
                     }
@@ -570,8 +584,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitTupleExpression(final TupleExpression expression) {
-        doWithNode(TupleExpression, current) {
-            doWithNode(List, ((TupleExpression) current).expressions) {
+        doWithNode(expression, current) {
+            doWithNode(expression.expressions, ((TupleExpression) current).expressions) {
                 visitListOfExpressions(expression.expressions)
             }
         }
@@ -579,9 +593,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitListExpression(final ListExpression expression) {
-        doWithNode(ListExpression, current) {
+        doWithNode(expression, current) {
             def exprs = expression.expressions
-            doWithNode(exprs.class, ((ListExpression) current).expressions) {
+            doWithNode(exprs, ((ListExpression) current).expressions) {
                 visitListOfExpressions(exprs)
             }
         }
@@ -589,16 +603,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitArrayExpression(final ArrayExpression expression) {
-        doWithNode(ArrayExpression, current) {
+        doWithNode(expression, current) {
             def expressions = expression.expressions
             def size = expression.sizeExpression
             def cur = (ArrayExpression) current
             def curExprs = cur.expressions
             def curSize = cur.sizeExpression
-            doWithNode(expressions.class, curExprs) {
+            doWithNode(expressions, curExprs) {
                 visitListOfExpressions(expressions)
             }
-            doWithNode(size.class, curSize) {
+            doWithNode(size, curSize) {
                 visitListOfExpressions(size)
             }
             failIfNot(expression.elementType == cur.elementType)
@@ -607,10 +621,10 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMapExpression(final MapExpression expression) {
-        doWithNode(MapExpression, current) {
+        doWithNode(expression, current) {
             def entries = expression.mapEntryExpressions
             def curEntries = ((MapExpression) current).mapEntryExpressions
-            doWithNode(entries.class, curEntries) {
+            doWithNode(entries, curEntries) {
                 visitListOfExpressions(entries)
             }
         }
@@ -618,16 +632,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMapEntryExpression(final MapEntryExpression expression) {
-        doWithNode(MapEntryExpression, current) {
+        doWithNode(expression, current) {
             def key = expression.keyExpression
             def value = expression.valueExpression
             def cur = (MapEntryExpression) current
             def curKey = cur.keyExpression
             def curValue = cur.valueExpression
-            doWithNode(key.class, curKey) {
+            doWithNode(key, curKey) {
                 key.visit(this)
             }
-            doWithNode(value.class, curValue) {
+            doWithNode(value, curValue) {
                 value.visit(this)
             }
         }
@@ -635,16 +649,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitRangeExpression(final RangeExpression expression) {
-        doWithNode(RangeExpression, current) {
+        doWithNode(expression, current) {
             def from = expression.from
             def to = expression.to
             def cur = (RangeExpression) current
             def curFrom = cur.from
             def curTo = cur.to
-            doWithNode(from.class, curFrom) {
+            doWithNode(from, curFrom) {
                 from.visit(this)
             }
-            doWithNode(to.class, curTo) {
+            doWithNode(to, curTo) {
                 to.visit(this)
             }
         }
@@ -652,9 +666,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitSpreadExpression(final SpreadExpression expression) {
-        doWithNode(SpreadExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((SpreadExpression) current).expression) {
+            doWithNode(expr, ((SpreadExpression) current).expression) {
                 expr.visit(this)
             }
         }
@@ -667,16 +681,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitMethodPointerExpression(final MethodPointerExpression expression) {
-        doWithNode(MethodPointerExpression, current) {
+        doWithNode(expression, current) {
             def cur = (MethodPointerExpression) current
             def expr = expression.expression
             def methodName = expression.methodName
             def curExpr = cur.expression
             def curName = cur.methodName
-            doWithNode(expr.class, curExpr) {
+            doWithNode(expr, curExpr) {
                 expr.visit(this)
             }
-            doWithNode(methodName.class, curName) {
+            doWithNode(methodName, curName) {
                 methodName.visit(this)
             }
         }
@@ -684,9 +698,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
-        doWithNode(UnaryMinusExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((UnaryMinusExpression) current).expression) {
+            doWithNode(expr, ((UnaryMinusExpression) current).expression) {
                 expr.visit(this)
             }
         }
@@ -694,9 +708,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
-        doWithNode(UnaryPlusExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((UnaryPlusExpression) current).expression) {
+            doWithNode(expr, ((UnaryPlusExpression) current).expression) {
                 expr.visit(this)
             }
         }
@@ -704,9 +718,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
-        doWithNode(BitwiseNegationExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((BitwiseNegationExpression) current).expression) {
+            doWithNode(expr, ((BitwiseNegationExpression) current).expression) {
                 expr.visit(this)
             }
         }
@@ -714,9 +728,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitCastExpression(final CastExpression expression) {
-        doWithNode(CastExpression, current) {
+        doWithNode(expression, current) {
             def expr = expression.expression
-            doWithNode(expr.class, ((CastExpression) current).expression) {
+            doWithNode(expr, ((CastExpression) current).expression) {
                 expr.visit(this)
             }
             failIfNot(expression.type == ((CastExpression) current).type)
@@ -726,7 +740,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     @CompileStatic(TypeCheckingMode.SKIP)
     public void visitConstantExpression(final ConstantExpression expression) {
-        doWithNode(ConstantExpression, current) {
+        doWithNode(expression, current) {
             def cur = (ConstantExpression) current
             super.visitConstantExpression(expression)
             failIfNot((expression.type == cur.type) &&
@@ -737,7 +751,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     @CompileStatic(TypeCheckingMode.SKIP)
     public void visitClassExpression(final ClassExpression expression) {
-        doWithNode(ClassExpression, current) {
+        doWithNode(expression, current) {
             super.visitClassExpression(expression)
             def cexp = (ClassExpression) current
             failIfNot(cexp.type == expression.type)
@@ -746,9 +760,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitVariableExpression(final VariableExpression expression) {
-        doWithNode(VariableExpression, current) {
+        doWithNode(expression, current) {
             def curVar = (VariableExpression) current
-            failIfNot((expression.name == curVar.name) &&
+            failIfNot(matchByName(expression.name,curVar.name) &&
                     (expression.type == curVar.type) &&
                     (expression.originType == curVar.originType))
         }
@@ -756,12 +770,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitPropertyExpression(final PropertyExpression expression) {
-        doWithNode(PropertyExpression, current) {
+        doWithNode(expression, current) {
             def currentPexp = (PropertyExpression) current
-            doWithNode(expression.objectExpression.class, currentPexp.objectExpression) {
+            doWithNode(expression.objectExpression, currentPexp.objectExpression) {
                 expression.objectExpression.visit(this)
             }
-            doWithNode(expression.property.class, currentPexp.property) {
+            doWithNode(expression.property, currentPexp.property) {
                 expression.property.visit(this)
             }
             failIfNot((expression.propertyAsString == currentPexp.propertyAsString) &&
@@ -773,12 +787,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitAttributeExpression(final AttributeExpression expression) {
-        doWithNode(AttributeExpression, current) {
+        doWithNode(expression, current) {
             def currentPexp = (AttributeExpression) current
-            doWithNode(expression.objectExpression.class, currentPexp.objectExpression) {
+            doWithNode(expression.objectExpression, currentPexp.objectExpression) {
                 expression.objectExpression.visit(this)
             }
-            doWithNode(expression.property.class, currentPexp.property) {
+            doWithNode(expression.property, currentPexp.property) {
                 expression.property.visit(this)
             }
             failIfNot((expression.propertyAsString == currentPexp.propertyAsString) &&
@@ -795,16 +809,16 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitGStringExpression(final GStringExpression expression) {
-        doWithNode(GStringExpression, current) {
+        doWithNode(expression, current) {
             def cur = (GStringExpression) current
             def strings = expression.strings
             def values = expression.values
             def curStrings = cur.strings
             def curValues = cur.values
-            doWithNode(strings.class, curStrings) {
+            doWithNode(strings, curStrings) {
                 visitListOfExpressions(strings)
             }
-            doWithNode(values.class, curValues) {
+            doWithNode(values, curValues) {
                 visitListOfExpressions(values)
             }
         }
@@ -821,7 +835,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         def iter = currentExprs.iterator()
         for (Expression expression : list) {
             def next = iter.next()
-            doWithNode(expression.class, next) {
+            doWithNode(expression, next) {
                 expression.visit(this)
             }
         }
@@ -834,9 +848,9 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitClosureListExpression(final ClosureListExpression cle) {
-        doWithNode(ClosureListExpression, current) {
+        doWithNode(cle, current) {
             def exprs = cle.expressions
-            doWithNode(exprs.class, ((ClosureListExpression)current).expressions) {
+            doWithNode(exprs, ((ClosureListExpression)current).expressions) {
                 visitListOfExpressions(exprs)
             }
         }
@@ -849,20 +863,20 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     void visitIfElse(final IfStatement ifElse) {
-        doWithNode(IfStatement, current) {
+        doWithNode(ifElse, current) {
             visitStatement(ifElse)
             def cur = (IfStatement) current
             def bool = ifElse.booleanExpression
             def ifBlock = ifElse.ifBlock
             def elseBlock = ifElse.elseBlock
-            doWithNode(bool.class, cur.booleanExpression) {
+            doWithNode(bool, cur.booleanExpression) {
                 bool.visit(this)
             }
-            doWithNode(ifBlock.class, cur.ifBlock) {
+            doWithNode(ifBlock, cur.ifBlock) {
                 ifBlock.visit(this)
             }
             failIfNot(elseBlock && cur.elseBlock || !elseBlock && !cur.elseBlock)
-            doWithNode(elseBlock.class, cur.elseBlock) {
+            doWithNode(elseBlock, cur.elseBlock) {
                 elseBlock.visit(this)
             }
         }
@@ -870,15 +884,15 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     void visitForLoop(final ForStatement forLoop) {
-        doWithNode(ForStatement, current) {
+        doWithNode(forLoop, current) {
             visitStatement(forLoop)
             def cur = (ForStatement) current
             def col = forLoop.collectionExpression
             def block = forLoop.loopBlock
-            doWithNode(col.class, cur.collectionExpression) {
+            doWithNode(col, cur.collectionExpression) {
                 col.visit(this)
             }
-            doWithNode(block.class, cur.loopBlock) {
+            doWithNode(block, cur.loopBlock) {
                 block.visit(this)
             }
         }
@@ -886,15 +900,15 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     void visitWhileLoop(final WhileStatement loop) {
-        doWithNode(WhileStatement, current) {
+        doWithNode(loop, current) {
             visitStatement(loop)
             def cur = (WhileStatement) current
             def bool = loop.booleanExpression
             def block = loop.loopBlock
-            doWithNode(bool.class, cur.booleanExpression) {
+            doWithNode(bool, cur.booleanExpression) {
                 bool.visit(this)
             }
-            doWithNode(block.class, cur.loopBlock) {
+            doWithNode(block, cur.loopBlock) {
                 block.visit(this)
             }
         }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/1cd27ea2/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 9c02e65..e1e88a3 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -574,4 +574,34 @@ class ASTMatcherTest extends GroovyTestCase {
         assert !ASTMatcher.matches(ast1, ast3)
         assert !ASTMatcher.matches(ast1, ast4)
     }
+
+    void testWildcardMatchVariable() {
+        def ast1 = macro { a }
+        def ast2 = macro { _ }
+        def ast3 = macro { b }
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast3)
+    }
+
+    void testWildcardMatchVariableInBinaryExpression() {
+        def ast1 = macro { a+b }
+        def ast2 = macro { _+_ }
+        def ast3 = macro { _+c }
+        def ast4 = macro { c+_ }
+        def ast5 = macro { a+_ }
+        def ast6 = macro { _+b }
+        assert ASTMatcher.matches(ast1, ast2)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert ASTMatcher.matches(ast1, ast5)
+        assert ASTMatcher.matches(ast1, ast6)
+    }
+
+    void testWildcardForSubExpression() {
+        def ast1 = macro { a+foo(b) }
+        def ast2 = macro { _+foo(b) }
+        def ast3 = macro { a+_ }
+        //assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast1, ast3)
+    }
 }



[14/37] incubator-groovy git commit: First prototype of an AST pattern matcher. * implemetation is *far from complete* * no unit test * implemented both match/find operations * moved the context aware visitor to the macro project

Posted by cc...@apache.org.
First prototype of an AST pattern matcher.
   * implemetation is *far from complete*
   * no unit test
   * implemented both match/find operations
   * moved the context aware visitor to the macro project


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/248e0fd9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/248e0fd9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/248e0fd9

Branch: refs/heads/master
Commit: 248e0fd9530573d234212d7b3627e3d42168fde4
Parents: 7704cf9
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Oct 15 18:35:08 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:06 2015 +0300

----------------------------------------------------------------------
 .../groovy/ast/ClassCodeVisitorSupport.java     |   5 -
 .../groovy/ast/ContextualClassCodeVisitor.java  | 695 -------------------
 .../groovy/macro/matcher/ASTFinder.java         | 424 +++++++++++
 .../groovy/macro/matcher/ASTMatcher.groovy      | 646 +++++++++++++++++
 .../groovy/macro/matcher/ASTNodePredicate.java  |  22 +
 .../matcher/ContextualClassCodeVisitor.java     | 603 ++++++++++++++++
 .../groovy/macro/matcher/MatcherUtils.java      |  28 +
 .../groovy/macro/matcher/NodeComparator.java    |  22 +
 .../groovy/macro/matcher/TreeContext.java       | 121 ++++
 .../groovy/macro/matcher/TreeContextAction.java |  20 +
 .../groovy/macro/runtime/MacroBuilder.java      | 109 +++
 .../macro/runtime/MacroGroovyMethods.java       |  50 ++
 .../macro/runtime/MacroSubstitutionKey.java     |  96 +++
 .../macro/transform/MacroInvocationTrap.java    | 178 +++++
 .../macro/transform/MacroTransformation.java    |  39 ++
 .../groovy/macro/runtime/MacroBuilder.java      | 109 ---
 .../macro/runtime/MacroGroovyMethods.java       |  50 --
 .../macro/runtime/MacroSubstitutionKey.java     |  96 ---
 .../macro/transform/MacroInvocationTrap.java    | 178 -----
 .../macro/transform/MacroTransformation.java    |  39 --
 20 files changed, 2358 insertions(+), 1172 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java b/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java
index c675b9e..69c45b0 100644
--- a/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java
+++ b/src/main/org/codehaus/groovy/ast/ClassCodeVisitorSupport.java
@@ -161,11 +161,6 @@ public abstract class ClassCodeVisitorSupport extends CodeVisitorSupport impleme
         super.visitAssertStatement(statement);
     }
 
-    public void visitBlockStatement(BlockStatement block) {
-        visitStatement(block);
-        super.visitBlockStatement(block);
-    }
-
     public void visitBreakStatement(BreakStatement statement) {
         visitStatement(statement);
         super.visitBreakStatement(statement);

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java b/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
deleted file mode 100644
index 360a91e..0000000
--- a/src/main/org/codehaus/groovy/ast/ContextualClassCodeVisitor.java
+++ /dev/null
@@ -1,695 +0,0 @@
-/*
- * Copyright 2003-2014 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 org.codehaus.groovy.ast;
-
-import groovy.lang.Closure;
-import groovy.lang.DelegatesTo;
-import groovy.lang.MapWithDefault;
-import org.codehaus.groovy.ast.expr.*;
-import org.codehaus.groovy.ast.stmt.AssertStatement;
-import org.codehaus.groovy.ast.stmt.BlockStatement;
-import org.codehaus.groovy.ast.stmt.BreakStatement;
-import org.codehaus.groovy.ast.stmt.CaseStatement;
-import org.codehaus.groovy.ast.stmt.CatchStatement;
-import org.codehaus.groovy.ast.stmt.ContinueStatement;
-import org.codehaus.groovy.ast.stmt.DoWhileStatement;
-import org.codehaus.groovy.ast.stmt.EmptyStatement;
-import org.codehaus.groovy.ast.stmt.ExpressionStatement;
-import org.codehaus.groovy.ast.stmt.ForStatement;
-import org.codehaus.groovy.ast.stmt.IfStatement;
-import org.codehaus.groovy.ast.stmt.ReturnStatement;
-import org.codehaus.groovy.ast.stmt.SwitchStatement;
-import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
-import org.codehaus.groovy.ast.stmt.ThrowStatement;
-import org.codehaus.groovy.ast.stmt.TryCatchStatement;
-import org.codehaus.groovy.ast.stmt.WhileStatement;
-import org.codehaus.groovy.classgen.BytecodeExpression;
-import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.runtime.DefaultGroovyMethods;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A class code visitor which is capable of remembering the context of the current
- * visit. This makes it easier for subclasses to perform context-dependent transformations,
- * where for example it is necessary to check the parent nodes of an AST node before
- * performing some operations.
- *
- * @author Cedric Champeau
- * @since 2.4.0
- */
-public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport {
-    private final Deque<TreeContext> treeContextStack = new ArrayDeque<TreeContext>();
-    private TreeContext lastContext;
-
-    public ContextualClassCodeVisitor() {
-        pushContext(new TreeContext(null, null));
-    }
-
-    public TreeContext getTreeContext() {
-        return treeContextStack.isEmpty()?null:treeContextStack.peek();
-    }
-
-    protected void pushContext(TreeContext ctx) {
-        treeContextStack.push(ctx);
-    }
-
-    protected TreeContext popContext() {
-        final TreeContext treeContext = treeContextStack.pop();
-        List<TreeContextAction> actions = treeContext.getOnPopHandlers();
-        for (TreeContextAction contextAction : actions) {
-            contextAction.call(treeContext);
-        }
-        lastContext = treeContext;
-        ASTNode parentNode = treeContext.parent!=null?treeContext.parent.node:null;
-        if (treeContext.node instanceof Expression && parentNode !=null) {
-            ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
-                @Override
-                protected SourceUnit getSourceUnit() {
-                    return null;
-                }
-
-                @Override
-                public Expression transform(final Expression exp) {
-                    if (exp==treeContext.node) {
-                        Expression replacement = treeContext.getReplacement();
-                        if (replacement!=null) {
-                            return replacement;
-                        }
-                    }
-                    return super.transform(exp);
-                }
-            };
-            parentNode.visit(trn);
-        }
-        return treeContext;
-    }
-
-    protected void pushContext(ASTNode node) {
-        pushContext(getTreeContext().fork(node));
-    }
-
-
-    // ----------------------- override visit methods to provide contextual information ---------------------------
-
-
-    @Override
-    public void visitClass(final ClassNode node) {
-        pushContext(node);
-        super.visitClass(node);
-        popContext();
-    }
-
-    @Override
-    public void visitPackage(final PackageNode node) {
-        if (node!=null) {
-            pushContext(node);
-        }
-        super.visitPackage(node);
-        if (node!=null) {
-            popContext();
-        }
-    }
-
-    @Override
-    public void visitImports(final ModuleNode node) {
-        pushContext(node);
-        super.visitImports(node);
-        popContext();
-    }
-
-    @Override
-    protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
-        pushContext(node);
-        super.visitConstructorOrMethod(node, isConstructor);
-        popContext();
-    }
-
-    @Override
-    public void visitField(final FieldNode node) {
-        pushContext(node);
-        super.visitField(node);
-        popContext();
-    }
-
-    @Override
-    public void visitProperty(final PropertyNode node) {
-        pushContext(node);
-        super.visitProperty(node);
-        popContext();
-    }
-
-    @Override
-    public void visitMethodCallExpression(final MethodCallExpression call) {
-        pushContext(call);
-        super.visitMethodCallExpression(call);
-        popContext();
-    }
-
-    @Override
-    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
-        pushContext(call);
-        super.visitStaticMethodCallExpression(call);
-        popContext();
-    }
-
-    @Override
-    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
-        pushContext(call);
-        super.visitConstructorCallExpression(call);
-        popContext();
-    }
-
-    @Override
-    public void visitBinaryExpression(final BinaryExpression expression) {
-        pushContext(expression);
-        super.visitBinaryExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitTernaryExpression(final TernaryExpression expression) {
-        pushContext(expression);
-        super.visitTernaryExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
-        pushContext(expression);
-        super.visitShortTernaryExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitPostfixExpression(final PostfixExpression expression) {
-        pushContext(expression);
-        super.visitPostfixExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitPrefixExpression(final PrefixExpression expression) {
-        pushContext(expression);
-        super.visitPrefixExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitBooleanExpression(final BooleanExpression expression) {
-        pushContext(expression);
-        super.visitBooleanExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitNotExpression(final NotExpression expression) {
-        pushContext(expression);
-        super.visitNotExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitClosureExpression(final ClosureExpression expression) {
-        pushContext(expression);
-        super.visitClosureExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitTupleExpression(final TupleExpression expression) {
-        pushContext(expression);
-        super.visitTupleExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitListExpression(final ListExpression expression) {
-        pushContext(expression);
-        super.visitListExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitArrayExpression(final ArrayExpression expression) {
-        pushContext(expression);
-        super.visitArrayExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitMapExpression(final MapExpression expression) {
-        pushContext(expression);
-        super.visitMapExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitMapEntryExpression(final MapEntryExpression expression) {
-        pushContext(expression);
-        super.visitMapEntryExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitRangeExpression(final RangeExpression expression) {
-        pushContext(expression);
-        super.visitRangeExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitSpreadExpression(final SpreadExpression expression) {
-        pushContext(expression);
-        super.visitSpreadExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
-        pushContext(expression);
-        super.visitSpreadMapExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
-        pushContext(expression);
-        super.visitMethodPointerExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
-        pushContext(expression);
-        super.visitUnaryMinusExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
-        pushContext(expression);
-        super.visitUnaryPlusExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
-        pushContext(expression);
-        super.visitBitwiseNegationExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitCastExpression(final CastExpression expression) {
-        pushContext(expression);
-        super.visitCastExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitConstantExpression(final ConstantExpression expression) {
-        pushContext(expression);
-        super.visitConstantExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitClassExpression(final ClassExpression expression) {
-        pushContext(expression);
-        super.visitClassExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitVariableExpression(final VariableExpression expression) {
-        pushContext(expression);
-        super.visitVariableExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitPropertyExpression(final PropertyExpression expression) {
-        pushContext(expression);
-        super.visitPropertyExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitAttributeExpression(final AttributeExpression expression) {
-        pushContext(expression);
-        super.visitAttributeExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitFieldExpression(final FieldExpression expression) {
-        pushContext(expression);
-        super.visitFieldExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitGStringExpression(final GStringExpression expression) {
-        pushContext(expression);
-        super.visitGStringExpression(expression);
-        popContext();
-    }
-
-    @Override
-    public void visitClosureListExpression(final ClosureListExpression cle) {
-        pushContext(cle);
-        super.visitClosureListExpression(cle);
-        popContext();
-    }
-
-    @Override
-    public void visitBytecodeExpression(final BytecodeExpression cle) {
-        pushContext(cle);
-        super.visitBytecodeExpression(cle);
-        popContext();
-    }
-
-    @Override
-    public void visitAssertStatement(final AssertStatement statement) {
-        pushContext(statement);
-        super.visitAssertStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitBlockStatement(final BlockStatement block) {
-        pushContext(block);
-        super.visitBlockStatement(block);
-        popContext();
-    }
-
-    @Override
-    public void visitBreakStatement(final BreakStatement statement) {
-        pushContext(statement);
-        super.visitBreakStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitCaseStatement(final CaseStatement statement) {
-        pushContext(statement);
-        super.visitCaseStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitCatchStatement(final CatchStatement statement) {
-        pushContext(statement);
-        super.visitCatchStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitContinueStatement(final ContinueStatement statement) {
-        pushContext(statement);
-        super.visitContinueStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitDoWhileLoop(final DoWhileStatement loop) {
-        pushContext(loop);
-        super.visitDoWhileLoop(loop);
-        popContext();
-    }
-
-    @Override
-    public void visitExpressionStatement(final ExpressionStatement statement) {
-        pushContext(statement);
-        super.visitExpressionStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitForLoop(final ForStatement forLoop) {
-        pushContext(forLoop);
-        super.visitForLoop(forLoop);
-        popContext();
-    }
-
-    @Override
-    public void visitIfElse(final IfStatement ifElse) {
-        pushContext(ifElse);
-        super.visitIfElse(ifElse);
-        popContext();
-    }
-
-    @Override
-    public void visitReturnStatement(final ReturnStatement statement) {
-        pushContext(statement);
-        super.visitReturnStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitSwitch(final SwitchStatement statement) {
-        pushContext(statement);
-        super.visitSwitch(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitSynchronizedStatement(final SynchronizedStatement statement) {
-        pushContext(statement);
-        super.visitSynchronizedStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitThrowStatement(final ThrowStatement statement) {
-        pushContext(statement);
-        super.visitThrowStatement(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitTryCatchFinally(final TryCatchStatement statement) {
-        pushContext(statement);
-        super.visitTryCatchFinally(statement);
-        popContext();
-    }
-
-    @Override
-    public void visitWhileLoop(final WhileStatement loop) {
-        pushContext(loop);
-        super.visitWhileLoop(loop);
-        popContext();
-    }
-
-    @Override
-    protected void visitEmptyStatement(final EmptyStatement statement) {
-        pushContext(statement);
-        super.visitEmptyStatement(statement);
-        popContext();
-    }
-
-    @SuppressWarnings("unchecked")
-    private static <T> Closure<T> cloneWithDelegate(final Closure<T> predicate, final Object delegate) {
-        Closure<T> clone = (Closure<T>) predicate.clone();
-        clone.setDelegate(delegate);
-        clone.setResolveStrategy(Closure.DELEGATE_FIRST);
-        return clone;
-    }
-
-    public List<TreeContext> getTreePath() {
-        List<TreeContext> path = new LinkedList<TreeContext>();
-        path.add(lastContext);
-        for (TreeContext treeContext : treeContextStack) {
-            path.add(treeContext);
-        }
-        return path;
-    }
-
-    public List<TreeContext> pathMatches(List<ASTNodePredicate> predicates) {
-        List<TreeContext> path = new LinkedList<TreeContext>();
-        TreeContext current = lastContext.parent;
-        for (ASTNodePredicate predicate : predicates) {
-            path.add(current);
-            if (current==null || !predicate.matches(current.node)) {
-                return Collections.emptyList();
-            }
-            current = current.parent;
-        }
-        if (!path.isEmpty()) {
-            path.add(0, lastContext);
-        }
-        return path;
-    }
-
-    public List<TreeContext> pathUpTo(ASTNodePredicate predicate) {
-        return pathUpTo(null, predicate);
-    }
-
-    public List<TreeContext> pathUpTo(Class<ASTNode> node) {
-        return pathUpTo(node, null);
-    }
-
-    public List<TreeContext> pathUpTo(Class<ASTNode> node, ASTNodePredicate predicate) {
-        List<TreeContext> path = new LinkedList<TreeContext>();
-        TreeContext current = lastContext;
-        boolean found = false;
-        while (current!=null && !found) {
-            path.add(current);
-            ASTNode currentNode = current.node;
-            if (node==null) {
-                if (predicate.matches(currentNode)) {
-                    found = true;
-                }
-            } else {
-                if (predicate==null) {
-                    if (currentNode==null || node==currentNode.getClass()) {
-                        found = true;
-                    }
-                } else {
-                    found = currentNode!=null && node==currentNode.getClass() && predicate.matches(currentNode);
-                }
-            }
-
-            current = current.parent;
-        }
-        if (found) {
-            return path;
-        }
-        return Collections.emptyList();
-    }
-
-    // ----------------------------- inner classes --------------------------------------
-
-    public static class TreeContext {
-        private static enum TreeContextKey {
-            expression_replacement
-        }
-        final TreeContext parent;
-        final ASTNode node;
-        final List<TreeContext> siblings = new LinkedList<TreeContext>();
-        final List<TreeContextAction> onPopHandlers = new LinkedList<TreeContextAction>();
-        final Map<Object, List<?>> userdata = MapWithDefault.newInstance(
-                new HashMap<Object, List<?>>(),
-                new Closure(this) {
-                    public Object doCall(Object key) {
-                        return new LinkedList<Object>();
-                    }
-                }
-        );
-
-        private TreeContext(final TreeContext parent, final ASTNode node) {
-            this.parent = parent;
-            this.node = node;
-            if (parent!=null) {
-                parent.siblings.add(this);
-            }
-        }
-
-        public Map<?, ?> getUserdata() {
-            return userdata;
-        }
-
-        public TreeContext getParent() { return parent; }
-        public ASTNode getNode() { return node; }
-
-        public TreeContext fork(ASTNode node) {
-            return new TreeContext(this, node);
-        }
-
-        public boolean matches(ASTNodePredicate predicate) {
-            return predicate.matches(node);
-        }
-
-        public boolean matches(@DelegatesTo(value=ASTNode.class, strategy=Closure.DELEGATE_FIRST) Closure<Boolean> predicate) {
-            return cloneWithDelegate(predicate, node).call();
-        }
-
-        public List<TreeContext> getSiblings() {
-            return Collections.unmodifiableList(siblings);
-        }
-
-        public List<TreeContextAction> getOnPopHandlers() {
-            return Collections.unmodifiableList(onPopHandlers);
-        }
-
-        public void afterVisit(TreeContextAction action) {
-            onPopHandlers.add(action);
-        }
-
-        public void afterVisit(@DelegatesTo(value=TreeContext.class, strategy=Closure.DELEGATE_FIRST) Closure<?> action) {
-            Closure<?> clone = cloneWithDelegate(action, this);
-            afterVisit(DefaultGroovyMethods.asType(clone, TreeContextAction.class));
-        }
-
-        public void setReplacement(Expression replacement) {
-            userdata.put(TreeContextKey.expression_replacement, Collections.singletonList(replacement));
-        }
-
-        public Expression getReplacement() {
-            List<?> list = userdata.get(TreeContextKey.expression_replacement);
-            if (list.size()==1) {
-                return (Expression) list.get(0);
-            }
-            return null;
-        }
-
-        @Override
-        public String toString() {
-            final StringBuilder sb = new StringBuilder("TreeContext{");
-            sb.append("node=").append(node!=null?node.getClass().getSimpleName():"undefined");
-            //sb.append(", siblings=").append(siblings);
-            sb.append('}');
-            return sb.toString();
-        }
-    }
-
-    public static interface ASTNodePredicate {
-        boolean matches(ASTNode node);
-    }
-
-    public static interface TreeContextAction {
-        void call(TreeContext context);
-    }
-
-    public static List<ASTNodePredicate> matchByClass(Class<ASTNode>... classes) {
-        ArrayList<ASTNodePredicate> result = new ArrayList<ASTNodePredicate>(classes.length);
-        for (final Class<ASTNode> astNodeClass : classes) {
-            result.add(new MatchByClass(astNodeClass));
-        }
-        return result;
-    }
-
-    private static class MatchByClass implements ASTNodePredicate {
-        private final Class<ASTNode> astNodeClass;
-
-        public MatchByClass(final Class<ASTNode> astNodeClass) {
-            this.astNodeClass = astNodeClass;
-        }
-
-        @Override
-        public boolean matches(final ASTNode node) {
-            return astNodeClass ==node.getClass();
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
new file mode 100644
index 0000000..92957ce
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTFinder.java
@@ -0,0 +1,424 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.ConstructorNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.ModuleNode;
+import org.codehaus.groovy.ast.PackageNode;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.AssertStatement;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.BreakStatement;
+import org.codehaus.groovy.ast.stmt.CaseStatement;
+import org.codehaus.groovy.ast.stmt.CatchStatement;
+import org.codehaus.groovy.ast.stmt.ContinueStatement;
+import org.codehaus.groovy.ast.stmt.DoWhileStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ForStatement;
+import org.codehaus.groovy.ast.stmt.IfStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.ast.stmt.SwitchStatement;
+import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
+import org.codehaus.groovy.ast.stmt.ThrowStatement;
+import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.ast.stmt.WhileStatement;
+import org.codehaus.groovy.classgen.BytecodeExpression;
+import org.codehaus.groovy.control.SourceUnit;
+
+import java.util.LinkedList;
+import java.util.List;
+
+class ASTFinder extends ContextualClassCodeVisitor {
+
+    private final ASTNode initial;
+    private final List<TreeContext> matches = new LinkedList<TreeContext>();
+
+    ASTFinder(final ASTNode initial) {
+        this.initial = initial;
+    }
+
+    @Override
+    protected SourceUnit getSourceUnit() {
+        return null;
+    }
+
+    public List<TreeContext> getMatches() {
+        return matches;
+    }
+
+    private void tryFind(final Class<?> clazz, final ASTNode node) {
+        if (clazz.isAssignableFrom(initial.getClass()) && ASTMatcher.matches(node, initial)) {
+            matches.add(getLastContext());
+        }
+    }
+
+    @Override
+    public void visitClass(final ClassNode node) {
+        super.visitClass(node);
+        tryFind(ClassNode.class, node);
+    }
+
+    @Override
+    public void visitPackage(final PackageNode node) {
+        super.visitPackage(node);
+        tryFind(PackageNode.class, node);
+    }
+
+    @Override
+    public void visitImports(final ModuleNode node) {
+        super.visitImports(node);
+        tryFind(ModuleNode.class, node);
+    }
+
+    @Override
+    public void visitDeclarationExpression(final DeclarationExpression expression) {
+        super.visitDeclarationExpression(expression);
+        tryFind(DeclarationExpression.class, expression);
+    }
+
+    @Override
+    protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
+        super.visitConstructorOrMethod(node, isConstructor);
+        tryFind(MethodNode.class, node);
+    }
+
+    @Override
+    public void visitField(final FieldNode node) {
+        super.visitField(node);
+        tryFind(FieldNode.class, node);
+    }
+
+    @Override
+    public void visitProperty(final PropertyNode node) {
+        super.visitProperty(node);
+        tryFind(PropertyNode.class, node);
+    }
+
+    @Override
+    public void visitAssertStatement(final AssertStatement statement) {
+        super.visitAssertStatement(statement);
+        tryFind(AssertStatement.class, statement);
+    }
+
+    @Override
+    public void visitBreakStatement(final BreakStatement statement) {
+        super.visitBreakStatement(statement);
+        tryFind(BreakStatement.class, statement);
+    }
+
+    @Override
+    public void visitCaseStatement(final CaseStatement statement) {
+        super.visitCaseStatement(statement);
+        tryFind(CaseStatement.class, statement);
+    }
+
+    @Override
+    public void visitCatchStatement(final CatchStatement statement) {
+        super.visitCatchStatement(statement);
+        tryFind(CatchStatement.class, statement);
+    }
+
+    @Override
+    public void visitContinueStatement(final ContinueStatement statement) {
+        super.visitContinueStatement(statement);
+        tryFind(ContinueStatement.class, statement);
+    }
+
+    @Override
+    public void visitDoWhileLoop(final DoWhileStatement loop) {
+        super.visitDoWhileLoop(loop);
+        tryFind(DoWhileStatement.class, loop);
+    }
+
+    @Override
+    public void visitExpressionStatement(final ExpressionStatement statement) {
+        super.visitExpressionStatement(statement);
+        tryFind(ExpressionStatement.class, statement);
+    }
+
+    @Override
+    public void visitForLoop(final ForStatement forLoop) {
+        super.visitForLoop(forLoop);
+        tryFind(ForStatement.class, forLoop);
+    }
+
+    @Override
+    public void visitIfElse(final IfStatement ifElse) {
+        super.visitIfElse(ifElse);
+        tryFind(IfStatement.class, ifElse);
+    }
+
+    @Override
+    public void visitReturnStatement(final ReturnStatement statement) {
+        super.visitReturnStatement(statement);
+        tryFind(ReturnStatement.class, statement);
+    }
+
+    @Override
+    public void visitSwitch(final SwitchStatement statement) {
+        super.visitSwitch(statement);
+        tryFind(SwitchStatement.class, statement);
+    }
+
+    @Override
+    public void visitSynchronizedStatement(final SynchronizedStatement statement) {
+        super.visitSynchronizedStatement(statement);
+        tryFind(SynchronizedStatement.class, statement);
+    }
+
+    @Override
+    public void visitThrowStatement(final ThrowStatement statement) {
+        super.visitThrowStatement(statement);
+        tryFind(ThrowStatement.class, statement);
+    }
+
+    @Override
+    public void visitTryCatchFinally(final TryCatchStatement statement) {
+        super.visitTryCatchFinally(statement);
+        tryFind(TryCatchStatement.class, statement);
+    }
+
+    @Override
+    public void visitWhileLoop(final WhileStatement loop) {
+        super.visitWhileLoop(loop);
+        tryFind(WhileStatement.class, loop);
+    }
+
+    @Override
+    public void visitBlockStatement(final BlockStatement block) {
+        super.visitBlockStatement(block);
+        tryFind(BlockStatement.class, block);
+    }
+
+    @Override
+    protected void visitEmptyStatement(final EmptyStatement statement) {
+        super.visitEmptyStatement(statement);
+        tryFind(EmptyStatement.class, statement);
+    }
+
+    @Override
+    public void visitMethodCallExpression(final MethodCallExpression call) {
+        super.visitMethodCallExpression(call);
+        tryFind(MethodCallExpression.class, call);
+    }
+
+    @Override
+    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
+        super.visitStaticMethodCallExpression(call);
+        tryFind(StaticMethodCallExpression.class, call);
+    }
+
+    @Override
+    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
+        super.visitConstructorCallExpression(call);
+        tryFind(ConstructorCallExpression.class, call);
+    }
+
+    @Override
+    public void visitBinaryExpression(final BinaryExpression expression) {
+        super.visitBinaryExpression(expression);
+        tryFind(BinaryExpression.class, expression);
+    }
+
+    @Override
+    public void visitTernaryExpression(final TernaryExpression expression) {
+        super.visitTernaryExpression(expression);
+        tryFind(TernaryExpression.class, expression);
+    }
+
+    @Override
+    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
+        super.visitShortTernaryExpression(expression);
+        tryFind(ElvisOperatorExpression.class, expression);
+    }
+
+    @Override
+    public void visitPostfixExpression(final PostfixExpression expression) {
+        super.visitPostfixExpression(expression);
+        tryFind(PostfixExpression.class, expression);
+    }
+
+    @Override
+    public void visitPrefixExpression(final PrefixExpression expression) {
+        super.visitPrefixExpression(expression);
+        tryFind(PrefixExpression.class, expression);
+    }
+
+    @Override
+    public void visitBooleanExpression(final BooleanExpression expression) {
+        super.visitBooleanExpression(expression);
+        tryFind(BooleanExpression.class, expression);
+    }
+
+    @Override
+    public void visitNotExpression(final NotExpression expression) {
+        super.visitNotExpression(expression);
+        tryFind(NotExpression.class, expression);
+    }
+
+    @Override
+    public void visitClosureExpression(final ClosureExpression expression) {
+        super.visitClosureExpression(expression);
+        tryFind(ClosureExpression.class, expression);
+    }
+
+    @Override
+    public void visitTupleExpression(final TupleExpression expression) {
+        super.visitTupleExpression(expression);
+        tryFind(TupleExpression.class, expression);
+    }
+
+    @Override
+    public void visitListExpression(final ListExpression expression) {
+        super.visitListExpression(expression);
+        tryFind(ListExpression.class, expression);
+    }
+
+    @Override
+    public void visitArrayExpression(final ArrayExpression expression) {
+        super.visitArrayExpression(expression);
+        tryFind(ArrayExpression.class, expression);
+    }
+
+    @Override
+    public void visitMapExpression(final MapExpression expression) {
+        super.visitMapExpression(expression);
+        tryFind(MapExpression.class, expression);
+    }
+
+    @Override
+    public void visitMapEntryExpression(final MapEntryExpression expression) {
+        super.visitMapEntryExpression(expression);
+        tryFind(MapEntryExpression.class, expression);
+    }
+
+    @Override
+    public void visitRangeExpression(final RangeExpression expression) {
+        super.visitRangeExpression(expression);
+        tryFind(RangeExpression.class, expression);
+    }
+
+    @Override
+    public void visitSpreadExpression(final SpreadExpression expression) {
+        super.visitSpreadExpression(expression);
+        tryFind(SpreadExpression.class, expression);
+    }
+
+    @Override
+    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
+        super.visitSpreadMapExpression(expression);
+        tryFind(SpreadMapExpression.class, expression);
+    }
+
+    @Override
+    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
+        super.visitMethodPointerExpression(expression);
+        tryFind(MethodPointerExpression.class, expression);
+    }
+
+    @Override
+    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
+        super.visitUnaryMinusExpression(expression);
+        tryFind(UnaryMinusExpression.class, expression);
+    }
+
+    @Override
+    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
+        super.visitUnaryPlusExpression(expression);
+        tryFind(UnaryPlusExpression.class, expression);
+    }
+
+    @Override
+    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
+        super.visitBitwiseNegationExpression(expression);
+        tryFind(BitwiseNegationExpression.class, expression);
+    }
+
+    @Override
+    public void visitCastExpression(final CastExpression expression) {
+        super.visitCastExpression(expression);
+        tryFind(CastExpression.class, expression);
+    }
+
+    @Override
+    public void visitConstantExpression(final ConstantExpression expression) {
+        super.visitConstantExpression(expression);
+        tryFind(ConstantExpression.class, expression);
+    }
+
+    @Override
+    public void visitClassExpression(final ClassExpression expression) {
+        super.visitClassExpression(expression);
+        tryFind(ClassExpression.class, expression);
+    }
+
+    @Override
+    public void visitVariableExpression(final VariableExpression expression) {
+        super.visitVariableExpression(expression);
+        tryFind(VariableExpression.class, expression);
+    }
+
+    @Override
+    public void visitPropertyExpression(final PropertyExpression expression) {
+        super.visitPropertyExpression(expression);
+        tryFind(PropertyExpression.class, expression);
+    }
+
+    @Override
+    public void visitAttributeExpression(final AttributeExpression expression) {
+        super.visitAttributeExpression(expression);
+        tryFind(AttributeExpression.class, expression);
+    }
+
+    @Override
+    public void visitFieldExpression(final FieldExpression expression) {
+        super.visitFieldExpression(expression);
+        tryFind(FieldExpression.class, expression);
+    }
+
+    @Override
+    public void visitGStringExpression(final GStringExpression expression) {
+        super.visitGStringExpression(expression);
+        tryFind(GStringExpression.class, expression);
+    }
+
+    @Override
+    public void visitArgumentlistExpression(final ArgumentListExpression ale) {
+        super.visitArgumentlistExpression(ale);
+        tryFind(ArgumentListExpression.class, ale);
+    }
+
+    @Override
+    public void visitClosureListExpression(final ClosureListExpression cle) {
+        super.visitClosureListExpression(cle);
+        tryFind(ClosureListExpression.class, cle);
+    }
+
+    @Override
+    public void visitBytecodeExpression(final BytecodeExpression cle) {
+        super.visitBytecodeExpression(cle);
+        tryFind(BytecodeExpression.class, cle);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
new file mode 100644
index 0000000..bce42da
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -0,0 +1,646 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
+
+import groovy.transform.CompileStatic
+import org.codehaus.groovy.ast.*
+import org.codehaus.groovy.ast.expr.*
+import org.codehaus.groovy.ast.stmt.*
+import org.codehaus.groovy.classgen.BytecodeExpression
+import org.codehaus.groovy.control.SourceUnit
+
+@CompileStatic
+class ASTMatcher extends ClassCodeVisitorSupport {
+
+    private Object current = null
+    private boolean match = true
+
+    private ASTMatcher() {}
+
+    @Override
+    protected SourceUnit getSourceUnit() {
+        null
+    }
+
+    /**
+     * Matches an AST with another AST (pattern). It will return true if the AST matches
+     * all the nodes from the pattern AST.
+     * @param node the AST we want to match with
+     * @param pattern the pattern AST we want to match to
+     * @return true if this AST matches the pattern
+     */
+    public static boolean matches(ASTNode node, ASTNode pattern) {
+        ASTMatcher matcher = new ASTMatcher()
+        matcher.current = node
+        matcher.match = true
+        if (pattern instanceof ClassNode) {
+            matcher.visitClass(pattern)
+        } else {
+            pattern.visit(matcher)
+        }
+
+        matcher.match
+    }
+
+    /**
+     * Locates all nodes in the given AST which match the pattern AST.
+     * This operation can cost a lot, because it tries to match a sub-tree
+     * to every node of the AST.
+     * @param node an AST Node
+     * @param pattern a pattern to be found somewhere in the AST
+     * @return a list of {@link TreeContext}, always not null.
+     */
+    public static List<TreeContext> find(ASTNode node, ASTNode pattern) {
+        ASTFinder finder = new ASTFinder(pattern);
+        node.visit(finder);
+
+        finder.matches
+    }
+
+    private void doWithNode(Class expectedClass, Object next, Closure cl) {
+        if (match && (next==null || expectedClass.isAssignableFrom(next.class))) {
+            Object old = current
+            current = next
+            cl()
+            current = old
+        } else {
+            match = false
+        }
+    }
+
+    @Override
+    public void visitClass(final ClassNode node) {
+        doWithNode(ClassNode, current) {
+            visitAnnotations(node)
+        }
+        doWithNode(PackageNode, ((ClassNode) current).package) {
+            visitPackage(node.package)
+        }
+        doWithNode(ModuleNode, ((ClassNode) current).module) {
+            visitImports(node.module)
+        }
+        doWithNode(ClassNode, current) {
+            def cur = (ClassNode) current
+            def nodeProps = node.properties
+            def curProps = cur.properties
+            if (nodeProps.size() == curProps.size()) {
+                def iter = curProps.iterator()
+                // now let's visit the contents of the class
+                for (PropertyNode pn : nodeProps) {
+                    doWithNode(pn.class, iter.next()) {
+                        visitProperty(pn)
+                    }
+                }
+
+                def nodeFields = node.fields
+                def curFields = cur.fields
+                if (nodeFields.size()==curFields.size()) {
+                    iter = curFields.iterator()
+                    for (FieldNode fn : nodeFields) {
+                        doWithNode(fn.class, iter.next()) {
+                            visitField(fn)
+                        }
+                    }
+
+                    def nodeConstructors = node.declaredConstructors
+                    def curConstructors = cur.declaredConstructors
+                    if (nodeConstructors.size()==curConstructors.size()) {
+                        iter = curConstructors.iterator()
+                        for (ConstructorNode cn : nodeConstructors) {
+                            doWithNode(cn.class, iter.next()) {
+                                visitConstructor(cn)
+                            }
+                        }
+
+                        def nodeMethods = node.methods
+                        def curMethods = cur.methods
+                        if (nodeMethods.size() == curMethods.size()) {
+                            iter = curMethods.iterator()
+                            for (MethodNode mn : nodeMethods) {
+                                doWithNode(mn.class, iter.next()) {
+                                    visitMethod(mn)
+                                }
+                            }
+                            visitObjectInitializerStatements(node)
+                        }
+                    }
+                }
+
+
+                return
+            }
+            match = false
+        }
+    }
+
+    @Override
+    protected void visitObjectInitializerStatements(final ClassNode node) {
+        doWithNode(ClassNode, current) {
+            def initializers = ((ClassNode)current).objectInitializerStatements
+            if (initializers.size()==node.objectInitializerStatements.size()) {
+                def iterator = initializers.iterator()
+                for (Statement element : node.objectInitializerStatements) {
+                    doWithNode(element.class, iterator.next()) {
+                        element.visit(this)
+                    }
+                }
+            } else {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    public void visitPackage(final PackageNode node) {
+        if (node) {
+            doWithNode(node.class, current) {
+                visitAnnotations(node)
+                node.visit(this)
+            }
+        }
+    }
+
+    @Override
+    public void visitImports(final ModuleNode node) {
+        if (node) {
+            doWithNode(ModuleNode, current) {
+                ModuleNode module = (ModuleNode) current
+                def imports = module.imports
+                if (imports.size() == node.imports.size()) {
+                    def iter = imports.iterator()
+                    for (ImportNode importNode : node.imports) {
+                        doWithNode(importNode.class, iter.next()) {
+                            visitAnnotations(importNode)
+                            importNode.visit(this)
+                        }
+                    }
+                } else {
+                    match = false
+                    return
+                }
+                imports = module.starImports
+                if (imports.size() == node.starImports.size()) {
+                    def iter = imports.iterator()
+                    for (ImportNode importNode : node.starImports) {
+                        doWithNode(importNode.class, iter.next()) {
+                            visitAnnotations(importNode)
+                            importNode.visit(this)
+                        }
+                    }
+                } else {
+                    match = false
+                    return
+                }
+                imports = module.staticImports
+                if (imports.size() == node.staticImports.size()) {
+                    def iter = imports.values().iterator()
+                    for (ImportNode importNode : node.staticImports.values()) {
+                        doWithNode(importNode.class, iter.next()) {
+                            visitAnnotations(importNode)
+                            importNode.visit(this)
+                        }
+                    }
+                } else {
+                    match = false
+                    return
+                }
+                imports = module.staticStarImports
+                if (imports.size() == node.staticStarImports.size()) {
+                    def iter = imports.values().iterator()
+                    for (ImportNode importNode : node.staticStarImports.values()) {
+                        doWithNode(importNode.class, iter.next()) {
+                            visitAnnotations(importNode)
+                            importNode.visit(this)
+                        }
+                    }
+                } else {
+                    match = false
+                    return
+                }
+            }
+        }
+    }
+
+    @Override
+    public void visitAnnotations(final AnnotatedNode node) {
+        doWithNode(AnnotatedNode, current) {
+            List<AnnotationNode> refAnnotations = node.annotations
+            AnnotatedNode cur = (AnnotatedNode) current
+            List<AnnotationNode> curAnnotations = cur.annotations
+            if (refAnnotations.size()!=curAnnotations.size()) {
+                match = false
+                return
+            }
+            if (refAnnotations.empty) return
+            def iter = curAnnotations.iterator()
+            for (AnnotationNode an : refAnnotations) {
+                AnnotationNode curNext = iter.next()
+                // skip built-in properties
+                if (an.builtIn) {
+                    if (!curNext.builtIn) {
+                        match = false
+                        return
+                    }
+                    continue
+                }
+
+                def refEntrySet = an.members.entrySet()
+                def curEntrySet = curNext.members.entrySet()
+                if (refEntrySet.size()==curEntrySet.size()) {
+                    def entryIt = curEntrySet.iterator()
+                    for (Map.Entry<String, Expression> member : refEntrySet) {
+                        def next = entryIt.next()
+                        if (next.key==member.key) {
+                            doWithNode(member.value.class, next.value) {
+                                member.value.visit(this)
+                            }
+                        } else {
+                            match = false
+                        }
+                    }
+                } else {
+                    match = false
+                }
+            }
+        }
+    }
+
+    @Override
+    protected void visitClassCodeContainer(final Statement code) {
+        doWithNode(Statement, current) {
+            if (code) {
+                code.visit(this)
+            }
+        }
+    }
+
+    @Override
+    public void visitDeclarationExpression(final DeclarationExpression expression) {
+        doWithNode(DeclarationExpression, current) {
+            super.visitDeclarationExpression(expression)
+        }
+    }
+
+    @Override
+    protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
+        doWithNode(MethodNode, current) {
+            visitAnnotations(node)
+            def cur = (MethodNode) current
+            doWithNode(Statement, cur.code) {
+                visitClassCodeContainer(node.code)
+            }
+            def params = node.parameters
+            def curParams = cur.parameters
+            if (params.length==curParams.length) {
+                params.eachWithIndex { Parameter entry, int i ->
+                    doWithNode(entry.class, curParams[i]) {
+                        visitAnnotations(entry)
+                    }
+                }
+            } else {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    public void visitField(final FieldNode node) {
+        doWithNode(FieldNode, current) {
+            visitAnnotations(node)
+            def fieldNode = (FieldNode) current
+            if (fieldNode.name==node.name) {
+                Expression init = node.initialExpression
+
+                Expression curInit = fieldNode.initialExpression
+                if (init) {
+                    if (curInit) {
+                        doWithNode(init.class, curInit) {
+                            init.visit(this)
+                        }
+                    } else {
+                        match = false
+                    }
+                } else if (curInit) {
+                    match = false
+                }
+            } else {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    public void visitProperty(final PropertyNode node) {
+        doWithNode(PropertyNode, current) {
+            PropertyNode pNode = (PropertyNode) current
+            visitAnnotations(node)
+
+            Statement statement = node.getterBlock
+            Statement curStatement = pNode.getterBlock
+            doWithNode(statement.class, curStatement) {
+                visitClassCodeContainer(statement)
+            }
+
+            statement = node.setterBlock
+            curStatement = pNode.setterBlock
+            doWithNode(statement.class, curStatement) {
+                visitClassCodeContainer(statement)
+            }
+
+            Expression init = node.initialExpression
+            Expression curInit = pNode.initialExpression
+            if (init) {
+                if (curInit) {
+                    doWithNode(init.class, curInit) {
+                        init.visit(this)
+                    }
+                } else {
+                    match = false
+                }
+            } else if (curInit) {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    void visitExpressionStatement(final ExpressionStatement statement) {
+        visitStatement(statement)
+        doWithNode(statement.expression.class, ((ExpressionStatement)current).expression) {
+            statement.expression.visit(this)
+        }
+    }
+
+    @Override
+    public void visitBlockStatement(BlockStatement block) {
+        doWithNode(BlockStatement, current) {
+            def statements = ((BlockStatement) current).statements
+            if (statements.size()==block.statements.size()) {
+                def iter = statements.iterator()
+                for (Statement statement : block.statements) {
+                    doWithNode(statement.class, iter.next()) {
+                        statement.visit(this)
+                    }
+                }
+            } else {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    public void visitMethodCallExpression(final MethodCallExpression call) {
+        doWithNode(MethodCallExpression, current) {
+            def mce = (MethodCallExpression) current
+            doWithNode(call.objectExpression.class, mce.objectExpression) {
+                call.objectExpression.visit(this)
+            }
+            doWithNode(call.method.class, mce.method) {
+                call.method.visit(this)
+            }
+            doWithNode(call.arguments.class, mce.arguments) {
+                call.arguments.visit(this)
+            }
+            match = match && (call.methodAsString==mce.methodAsString) &&
+                    (call.safe==mce.safe) &&
+                    (call.spreadSafe == mce.spreadSafe)
+        }
+    }
+
+    @Override
+    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
+        super.visitStaticMethodCallExpression(call);
+    }
+
+    @Override
+    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
+        doWithNode(call.arguments.class, ((ConstructorCallExpression)call).arguments) {
+            call.arguments.visit(this)
+        }
+    }
+
+    @Override
+    public void visitBinaryExpression(final BinaryExpression expression) {
+        doWithNode(BinaryExpression, current) {
+            def bin = (BinaryExpression) current
+            def leftExpression = expression.getLeftExpression()
+            doWithNode(leftExpression.class, bin.leftExpression) {
+                leftExpression.visit(this)
+            }
+            def rightExpression = expression.getRightExpression()
+            doWithNode(rightExpression.class, bin.rightExpression) {
+                rightExpression.visit(this)
+            }
+            if (bin.operation.type!=expression.operation.type) {
+                match = false
+            }
+        }
+    }
+
+    @Override
+    public void visitTernaryExpression(final TernaryExpression expression) {
+        doWithNode(TernaryExpression, current) {
+            TernaryExpression te = (TernaryExpression) current
+            doWithNode(BooleanExpression, te.booleanExpression) {
+                expression.booleanExpression.visit(this)
+            }
+            def trueExpression = expression.trueExpression
+            doWithNode(trueExpression.class, te.trueExpression) {
+                trueExpression.visit(this)
+            }
+            def falseExpression = expression.falseExpression
+            doWithNode(falseExpression.class, te.falseExpression) {
+                falseExpression.visit(this)
+            }
+        }
+    }
+
+    @Override
+    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
+        super.visitShortTernaryExpression(expression);
+    }
+
+    @Override
+    public void visitPostfixExpression(final PostfixExpression expression) {
+        super.visitPostfixExpression(expression);
+    }
+
+    @Override
+    public void visitPrefixExpression(final PrefixExpression expression) {
+        super.visitPrefixExpression(expression);
+    }
+
+    @Override
+    public void visitBooleanExpression(final BooleanExpression expression) {
+        doWithNode(BooleanExpression, current) {
+            doWithNode(expression.expression.class, ((BooleanExpression)current).expression) {
+                expression.expression.visit(this)
+            }
+        }
+    }
+
+    @Override
+    public void visitNotExpression(final NotExpression expression) {
+        super.visitNotExpression(expression);
+    }
+
+    @Override
+    public void visitClosureExpression(final ClosureExpression expression) {
+        super.visitClosureExpression(expression);
+    }
+
+    @Override
+    public void visitTupleExpression(final TupleExpression expression) {
+        doWithNode(TupleExpression, current) {
+            doWithNode(List, ((TupleExpression) current).expressions) {
+                visitListOfExpressions(expression.expressions)
+            }
+        }
+    }
+
+    @Override
+    public void visitListExpression(final ListExpression expression) {
+        super.visitListExpression(expression);
+    }
+
+    @Override
+    public void visitArrayExpression(final ArrayExpression expression) {
+        super.visitArrayExpression(expression);
+    }
+
+    @Override
+    public void visitMapExpression(final MapExpression expression) {
+        super.visitMapExpression(expression);
+    }
+
+    @Override
+    public void visitMapEntryExpression(final MapEntryExpression expression) {
+        super.visitMapEntryExpression(expression);
+    }
+
+    @Override
+    public void visitRangeExpression(final RangeExpression expression) {
+        super.visitRangeExpression(expression);
+    }
+
+    @Override
+    public void visitSpreadExpression(final SpreadExpression expression) {
+        super.visitSpreadExpression(expression);
+    }
+
+    @Override
+    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
+        super.visitSpreadMapExpression(expression);
+    }
+
+    @Override
+    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
+        super.visitMethodPointerExpression(expression);
+    }
+
+    @Override
+    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
+        super.visitUnaryMinusExpression(expression);
+    }
+
+    @Override
+    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
+        super.visitUnaryPlusExpression(expression);
+    }
+
+    @Override
+    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
+        super.visitBitwiseNegationExpression(expression);
+    }
+
+    @Override
+    public void visitCastExpression(final CastExpression expression) {
+        super.visitCastExpression(expression);
+    }
+
+    @Override
+    public void visitConstantExpression(final ConstantExpression expression) {
+        super.visitConstantExpression(expression);
+    }
+
+    @Override
+    public void visitClassExpression(final ClassExpression expression) {
+        super.visitClassExpression(expression);
+    }
+
+    @Override
+    public void visitVariableExpression(final VariableExpression expression) {
+        doWithNode(VariableExpression, current) {
+            match = expression.name == ((VariableExpression) current).name
+        }
+    }
+
+    @Override
+    public void visitPropertyExpression(final PropertyExpression expression) {
+        super.visitPropertyExpression(expression);
+    }
+
+    @Override
+    public void visitAttributeExpression(final AttributeExpression expression) {
+        super.visitAttributeExpression(expression);
+    }
+
+    @Override
+    public void visitFieldExpression(final FieldExpression expression) {
+        super.visitFieldExpression(expression);
+    }
+
+    @Override
+    public void visitGStringExpression(final GStringExpression expression) {
+        super.visitGStringExpression(expression);
+    }
+
+    @Override
+    protected void visitListOfExpressions(final List<? extends Expression> list) {
+        if (list == null) return;
+        def iter = ((List<Expression>) current).iterator()
+        for (Expression expression : list) {
+            def next = iter.next()
+            if (expression instanceof SpreadExpression) {
+                doWithNode(SpreadExpression, next) {
+                    Expression spread = ((SpreadExpression) expression).getExpression()
+                    doWithNode(Expression, ((SpreadExpression)current).expression) {
+                        spread.visit(this)
+                    }
+                }
+            } else {
+                doWithNode(Expression, next) {
+                    expression.visit(this)
+                }
+            }
+        }
+    }
+
+    @Override
+    public void visitArgumentlistExpression(final ArgumentListExpression ale) {
+        super.visitArgumentlistExpression(ale);
+    }
+
+    @Override
+    public void visitClosureListExpression(final ClosureListExpression cle) {
+        super.visitClosureListExpression(cle);
+    }
+
+    @Override
+    public void visitBytecodeExpression(final BytecodeExpression cle) {
+        super.visitBytecodeExpression(cle);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
new file mode 100644
index 0000000..f69e837
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTNodePredicate.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import org.codehaus.groovy.ast.ASTNode;
+
+public interface ASTNodePredicate {
+    boolean matches(ASTNode node);
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
new file mode 100644
index 0000000..babd3e3
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
@@ -0,0 +1,603 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.FieldNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.ModuleNode;
+import org.codehaus.groovy.ast.PackageNode;
+import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.AssertStatement;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.BreakStatement;
+import org.codehaus.groovy.ast.stmt.CaseStatement;
+import org.codehaus.groovy.ast.stmt.CatchStatement;
+import org.codehaus.groovy.ast.stmt.ContinueStatement;
+import org.codehaus.groovy.ast.stmt.DoWhileStatement;
+import org.codehaus.groovy.ast.stmt.EmptyStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.ForStatement;
+import org.codehaus.groovy.ast.stmt.IfStatement;
+import org.codehaus.groovy.ast.stmt.ReturnStatement;
+import org.codehaus.groovy.ast.stmt.SwitchStatement;
+import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
+import org.codehaus.groovy.ast.stmt.ThrowStatement;
+import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.ast.stmt.WhileStatement;
+import org.codehaus.groovy.classgen.BytecodeExpression;
+import org.codehaus.groovy.control.SourceUnit;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * A class code visitor which is capable of remembering the context of the current
+ * visit. This makes it easier for subclasses to perform context-dependent transformations,
+ * where for example it is necessary to check the parent nodes of an AST node before
+ * performing some operations.
+ *
+ * @author Cedric Champeau
+ * @since 2.4.0
+ */
+public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport {
+    private final Deque<TreeContext> treeContextStack = new ArrayDeque<TreeContext>();
+    private TreeContext lastContext;
+
+    public ContextualClassCodeVisitor() {
+        pushContext(new TreeContext(null, null));
+    }
+
+    public TreeContext getTreeContext() {
+        return treeContextStack.isEmpty()?null:treeContextStack.peek();
+    }
+
+    public TreeContext getLastContext() {
+        return lastContext;
+    }
+
+    protected void pushContext(TreeContext ctx) {
+        treeContextStack.push(ctx);
+    }
+
+    protected TreeContext popContext() {
+        final TreeContext treeContext = treeContextStack.pop();
+        List<TreeContextAction> actions = treeContext.getOnPopHandlers();
+        for (TreeContextAction contextAction : actions) {
+            contextAction.call(treeContext);
+        }
+        lastContext = treeContext;
+        ASTNode parentNode = treeContext.parent!=null?treeContext.parent.node:null;
+        if (treeContext.node instanceof Expression && parentNode !=null) {
+            ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
+                @Override
+                protected SourceUnit getSourceUnit() {
+                    return null;
+                }
+
+                @Override
+                public Expression transform(final Expression exp) {
+                    if (exp==treeContext.node) {
+                        Expression replacement = treeContext.getReplacement();
+                        if (replacement!=null) {
+                            return replacement;
+                        }
+                    }
+                    return super.transform(exp);
+                }
+            };
+            parentNode.visit(trn);
+        }
+        return treeContext;
+    }
+
+    protected void pushContext(ASTNode node) {
+        pushContext(getTreeContext().fork(node));
+    }
+
+
+    // ----------------------- override visit methods to provide contextual information ---------------------------
+
+
+    @Override
+    public void visitClass(final ClassNode node) {
+        pushContext(node);
+        super.visitClass(node);
+        popContext();
+    }
+
+    @Override
+    public void visitPackage(final PackageNode node) {
+        if (node!=null) {
+            pushContext(node);
+        }
+        super.visitPackage(node);
+        if (node!=null) {
+            popContext();
+        }
+    }
+
+    @Override
+    public void visitImports(final ModuleNode node) {
+        pushContext(node);
+        super.visitImports(node);
+        popContext();
+    }
+
+    @Override
+    protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
+        pushContext(node);
+        super.visitConstructorOrMethod(node, isConstructor);
+        popContext();
+    }
+
+    @Override
+    public void visitField(final FieldNode node) {
+        pushContext(node);
+        super.visitField(node);
+        popContext();
+    }
+
+    @Override
+    public void visitProperty(final PropertyNode node) {
+        pushContext(node);
+        super.visitProperty(node);
+        popContext();
+    }
+
+    @Override
+    public void visitMethodCallExpression(final MethodCallExpression call) {
+        pushContext(call);
+        super.visitMethodCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitStaticMethodCallExpression(final StaticMethodCallExpression call) {
+        pushContext(call);
+        super.visitStaticMethodCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitConstructorCallExpression(final ConstructorCallExpression call) {
+        pushContext(call);
+        super.visitConstructorCallExpression(call);
+        popContext();
+    }
+
+    @Override
+    public void visitBinaryExpression(final BinaryExpression expression) {
+        pushContext(expression);
+        super.visitBinaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitTernaryExpression(final TernaryExpression expression) {
+        pushContext(expression);
+        super.visitTernaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
+        pushContext(expression);
+        super.visitShortTernaryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPostfixExpression(final PostfixExpression expression) {
+        pushContext(expression);
+        super.visitPostfixExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPrefixExpression(final PrefixExpression expression) {
+        pushContext(expression);
+        super.visitPrefixExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitBooleanExpression(final BooleanExpression expression) {
+        pushContext(expression);
+        super.visitBooleanExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitNotExpression(final NotExpression expression) {
+        pushContext(expression);
+        super.visitNotExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClosureExpression(final ClosureExpression expression) {
+        pushContext(expression);
+        super.visitClosureExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitTupleExpression(final TupleExpression expression) {
+        pushContext(expression);
+        super.visitTupleExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitListExpression(final ListExpression expression) {
+        pushContext(expression);
+        super.visitListExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitArrayExpression(final ArrayExpression expression) {
+        pushContext(expression);
+        super.visitArrayExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMapExpression(final MapExpression expression) {
+        pushContext(expression);
+        super.visitMapExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMapEntryExpression(final MapEntryExpression expression) {
+        pushContext(expression);
+        super.visitMapEntryExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitRangeExpression(final RangeExpression expression) {
+        pushContext(expression);
+        super.visitRangeExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitSpreadExpression(final SpreadExpression expression) {
+        pushContext(expression);
+        super.visitSpreadExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitSpreadMapExpression(final SpreadMapExpression expression) {
+        pushContext(expression);
+        super.visitSpreadMapExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitMethodPointerExpression(final MethodPointerExpression expression) {
+        pushContext(expression);
+        super.visitMethodPointerExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitUnaryMinusExpression(final UnaryMinusExpression expression) {
+        pushContext(expression);
+        super.visitUnaryMinusExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitUnaryPlusExpression(final UnaryPlusExpression expression) {
+        pushContext(expression);
+        super.visitUnaryPlusExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) {
+        pushContext(expression);
+        super.visitBitwiseNegationExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitCastExpression(final CastExpression expression) {
+        pushContext(expression);
+        super.visitCastExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitConstantExpression(final ConstantExpression expression) {
+        pushContext(expression);
+        super.visitConstantExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClassExpression(final ClassExpression expression) {
+        pushContext(expression);
+        super.visitClassExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitVariableExpression(final VariableExpression expression) {
+        pushContext(expression);
+        super.visitVariableExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitPropertyExpression(final PropertyExpression expression) {
+        pushContext(expression);
+        super.visitPropertyExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitAttributeExpression(final AttributeExpression expression) {
+        pushContext(expression);
+        super.visitAttributeExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitFieldExpression(final FieldExpression expression) {
+        pushContext(expression);
+        super.visitFieldExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitGStringExpression(final GStringExpression expression) {
+        pushContext(expression);
+        super.visitGStringExpression(expression);
+        popContext();
+    }
+
+    @Override
+    public void visitClosureListExpression(final ClosureListExpression cle) {
+        pushContext(cle);
+        super.visitClosureListExpression(cle);
+        popContext();
+    }
+
+    @Override
+    public void visitBytecodeExpression(final BytecodeExpression cle) {
+        pushContext(cle);
+        super.visitBytecodeExpression(cle);
+        popContext();
+    }
+
+    @Override
+    public void visitAssertStatement(final AssertStatement statement) {
+        pushContext(statement);
+        super.visitAssertStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitBlockStatement(final BlockStatement block) {
+        pushContext(block);
+        super.visitBlockStatement(block);
+        popContext();
+    }
+
+    @Override
+    public void visitBreakStatement(final BreakStatement statement) {
+        pushContext(statement);
+        super.visitBreakStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitCaseStatement(final CaseStatement statement) {
+        pushContext(statement);
+        super.visitCaseStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitCatchStatement(final CatchStatement statement) {
+        pushContext(statement);
+        super.visitCatchStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitContinueStatement(final ContinueStatement statement) {
+        pushContext(statement);
+        super.visitContinueStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitDoWhileLoop(final DoWhileStatement loop) {
+        pushContext(loop);
+        super.visitDoWhileLoop(loop);
+        popContext();
+    }
+
+    @Override
+    public void visitExpressionStatement(final ExpressionStatement statement) {
+        pushContext(statement);
+        super.visitExpressionStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitForLoop(final ForStatement forLoop) {
+        pushContext(forLoop);
+        super.visitForLoop(forLoop);
+        popContext();
+    }
+
+    @Override
+    public void visitIfElse(final IfStatement ifElse) {
+        pushContext(ifElse);
+        super.visitIfElse(ifElse);
+        popContext();
+    }
+
+    @Override
+    public void visitReturnStatement(final ReturnStatement statement) {
+        pushContext(statement);
+        super.visitReturnStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitSwitch(final SwitchStatement statement) {
+        pushContext(statement);
+        super.visitSwitch(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitSynchronizedStatement(final SynchronizedStatement statement) {
+        pushContext(statement);
+        super.visitSynchronizedStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitThrowStatement(final ThrowStatement statement) {
+        pushContext(statement);
+        super.visitThrowStatement(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitTryCatchFinally(final TryCatchStatement statement) {
+        pushContext(statement);
+        super.visitTryCatchFinally(statement);
+        popContext();
+    }
+
+    @Override
+    public void visitWhileLoop(final WhileStatement loop) {
+        pushContext(loop);
+        super.visitWhileLoop(loop);
+        popContext();
+    }
+
+    @Override
+    protected void visitEmptyStatement(final EmptyStatement statement) {
+        pushContext(statement);
+        super.visitEmptyStatement(statement);
+        popContext();
+    }
+
+    public List<TreeContext> getTreePath() {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        path.add(lastContext);
+        for (TreeContext treeContext : treeContextStack) {
+            path.add(treeContext);
+        }
+        return path;
+    }
+
+    public List<TreeContext> pathMatches(List<ASTNodePredicate> predicates) {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        TreeContext current = lastContext.parent;
+        for (ASTNodePredicate predicate : predicates) {
+            path.add(current);
+            if (current==null || !predicate.matches(current.node)) {
+                return Collections.emptyList();
+            }
+            current = current.parent;
+        }
+        if (!path.isEmpty()) {
+            path.add(0, lastContext);
+        }
+        return path;
+    }
+
+    public List<TreeContext> pathUpTo(ASTNodePredicate predicate) {
+        return pathUpTo(null, predicate);
+    }
+
+    public List<TreeContext> pathUpTo(Class<ASTNode> node) {
+        return pathUpTo(node, null);
+    }
+
+    public List<TreeContext> pathUpTo(Class<ASTNode> node, ASTNodePredicate predicate) {
+        List<TreeContext> path = new LinkedList<TreeContext>();
+        TreeContext current = lastContext;
+        boolean found = false;
+        while (current!=null && !found) {
+            path.add(current);
+            ASTNode currentNode = current.node;
+            if (node==null) {
+                if (predicate.matches(currentNode)) {
+                    found = true;
+                }
+            } else {
+                if (predicate==null) {
+                    if (currentNode==null || node==currentNode.getClass()) {
+                        found = true;
+                    }
+                } else {
+                    found = currentNode!=null && node==currentNode.getClass() && predicate.matches(currentNode);
+                }
+            }
+
+            current = current.parent;
+        }
+        if (found) {
+            return path;
+        }
+        return Collections.emptyList();
+    }
+
+    // ----------------------------- inner classes --------------------------------------
+
+    public static List<ASTNodePredicate> matchByClass(Class<ASTNode>... classes) {
+        ArrayList<ASTNodePredicate> result = new ArrayList<ASTNodePredicate>(classes.length);
+        for (final Class<ASTNode> astNodeClass : classes) {
+            result.add(new MatchByClass(astNodeClass));
+        }
+        return result;
+    }
+
+    private static class MatchByClass implements ASTNodePredicate {
+        private final Class<ASTNode> astNodeClass;
+
+        public MatchByClass(final Class<ASTNode> astNodeClass) {
+            this.astNodeClass = astNodeClass;
+        }
+
+        @Override
+        public boolean matches(final ASTNode node) {
+            return astNodeClass ==node.getClass();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
new file mode 100644
index 0000000..7f7ac09
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatcherUtils.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import groovy.lang.Closure;
+
+class MatcherUtils {
+    @SuppressWarnings("unchecked")
+    static <T> Closure<T> cloneWithDelegate(final Closure<T> predicate, final Object delegate) {
+        Closure<T> clone = (Closure<T>) predicate.clone();
+        clone.setDelegate(delegate);
+        clone.setResolveStrategy(Closure.DELEGATE_FIRST);
+        return clone;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
new file mode 100644
index 0000000..7f55481
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/NodeComparator.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import org.codehaus.groovy.ast.ASTNode;
+
+public interface NodeComparator {
+    boolean equals(ASTNode a, ASTNode b);
+}



[29/37] incubator-groovy git commit: ASTMatcher: Rework wildcard so that it only works on the pattern side

Posted by cc...@apache.org.
ASTMatcher: Rework wildcard so that it only works on the pattern side


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/cd39e26d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/cd39e26d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/cd39e26d

Branch: refs/heads/master
Commit: cd39e26d6e648417f23beed441fc26c728b1f778
Parents: 1cd27ea
Author: Cedric Champeau <ce...@gmail.com>
Authored: Fri Oct 17 16:19:21 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:12 2015 +0300

----------------------------------------------------------------------
 .../codehaus/groovy/macro/matcher/ASTMatcher.groovy | 16 ++++++++--------
 .../groovy/macro/matcher/ASTMatcherTest.groovy      | 16 ++++++++++++++--
 2 files changed, 22 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/cd39e26d/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 858924b..5b5dc8e 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -20,7 +20,6 @@ import groovy.transform.TypeCheckingMode
 import org.codehaus.groovy.ast.*
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.BlockStatement
-import org.codehaus.groovy.ast.stmt.EmptyStatement
 import org.codehaus.groovy.ast.stmt.ExpressionStatement
 import org.codehaus.groovy.ast.stmt.ForStatement
 import org.codehaus.groovy.ast.stmt.IfStatement
@@ -68,12 +67,13 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         match = match && value
     }
 
-    private static boolean matchByName(String a, String b) {
-        return a.equals(b) || WILDCARD.equals(a) || WILDCARD.equals(b);
+    private static boolean matchByName(String potentialWildcard, String node) {
+        return node.equals(potentialWildcard) || WILDCARD.equals(potentialWildcard);
     }
 
     private static boolean isWildcardExpression(Object exp) {
-        return exp instanceof VariableExpression && WILDCARD.equals(exp.getName());
+        return (exp instanceof VariableExpression && WILDCARD.equals(exp.getName())
+            || (exp instanceof ConstantExpression && WILDCARD.equals(exp.getValue())));
     }
 
     /**
@@ -176,7 +176,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     }
                 }
             }
-            failIfNot(matchByName(cur.name,node.name))
+            failIfNot(matchByName(cur.name, node.name))
         }
     }
 
@@ -354,7 +354,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
         doWithNode(node, current) {
             visitAnnotations(node)
             def fieldNode = (FieldNode) current
-            failIfNot(matchByName(fieldNode.name,node.name))
+            failIfNot(matchByName(node.name, fieldNode.name))
             failIfNot(fieldNode.originType == node.originType)
             failIfNot(fieldNode.modifiers == node.modifiers)
 
@@ -571,7 +571,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
                     def n = nodeParams[i]
                     def c = curParams[i]
                     doWithNode(n, c) {
-                        failIfNot(matchByName(n.name,c.name) &&
+                        failIfNot(matchByName(n.name, c.name) &&
                                 (n.originType == c.originType) &&
                                 (n.type == c.originType))
                     }
@@ -762,7 +762,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     public void visitVariableExpression(final VariableExpression expression) {
         doWithNode(expression, current) {
             def curVar = (VariableExpression) current
-            failIfNot(matchByName(expression.name,curVar.name) &&
+            failIfNot(matchByName(expression.name, curVar.name) &&
                     (expression.type == curVar.type) &&
                     (expression.originType == curVar.originType))
         }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/cd39e26d/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index e1e88a3..63d4a9a 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -580,7 +580,8 @@ class ASTMatcherTest extends GroovyTestCase {
         def ast2 = macro { _ }
         def ast3 = macro { b }
         assert ASTMatcher.matches(ast1, ast2)
-        assert ASTMatcher.matches(ast2, ast3)
+        assert !ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast2, ast3)
     }
 
     void testWildcardMatchVariableInBinaryExpression() {
@@ -591,6 +592,7 @@ class ASTMatcherTest extends GroovyTestCase {
         def ast5 = macro { a+_ }
         def ast6 = macro { _+b }
         assert ASTMatcher.matches(ast1, ast2)
+        assert !ASTMatcher.matches(ast2, ast1)
         assert !ASTMatcher.matches(ast1, ast3)
         assert !ASTMatcher.matches(ast1, ast4)
         assert ASTMatcher.matches(ast1, ast5)
@@ -601,7 +603,17 @@ class ASTMatcherTest extends GroovyTestCase {
         def ast1 = macro { a+foo(b) }
         def ast2 = macro { _+foo(b) }
         def ast3 = macro { a+_ }
-        //assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert !ASTMatcher.matches(ast2, ast1)
         assert ASTMatcher.matches(ast1, ast3)
     }
+
+    void testWildcardInMethodName() {
+        def ast1 = macro { a+foo(b) }
+        def ast2 = macro { a+_(b) }
+        def ast3 = macro { a+_(c) }
+        assert ASTMatcher.matches(ast1, ast2)
+        assert !ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+    }
 }


[13/37] incubator-groovy git commit: First prototype of an AST pattern matcher. * implemetation is *far from complete* * no unit test * implemented both match/find operations * moved the context aware visitor to the macro project

Posted by cc...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
new file mode 100644
index 0000000..6020592
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContext.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+import groovy.lang.Closure;
+import groovy.lang.DelegatesTo;
+import groovy.lang.MapWithDefault;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.runtime.DefaultGroovyMethods;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+public class TreeContext {
+    private static enum TreeContextKey {
+        expression_replacement
+    }
+    final TreeContext parent;
+    final ASTNode node;
+    final List<TreeContext> siblings = new LinkedList<TreeContext>();
+    final List<TreeContextAction> onPopHandlers = new LinkedList<TreeContextAction>();
+    final Map<Object, List<?>> userdata = MapWithDefault.newInstance(
+            new HashMap<Object, List<?>>(),
+            new Closure(this) {
+                public Object doCall(Object key) {
+                    return new LinkedList<Object>();
+                }
+            }
+    );
+
+    TreeContext(final TreeContext parent, final ASTNode node) {
+        this.parent = parent;
+        this.node = node;
+        if (parent!=null) {
+            parent.siblings.add(this);
+        }
+    }
+
+    public Map<?, ?> getUserdata() {
+        return userdata;
+    }
+
+    public TreeContext getParent() { return parent; }
+    public ASTNode getNode() { return node; }
+
+    public TreeContext fork(ASTNode node) {
+        return new TreeContext(this, node);
+    }
+
+    public boolean matches(ASTNodePredicate predicate) {
+        return predicate.matches(node);
+    }
+
+    public boolean matches(@DelegatesTo(value=ASTNode.class, strategy=Closure.DELEGATE_FIRST) Closure<Boolean> predicate) {
+        return MatcherUtils.cloneWithDelegate(predicate, node).call();
+    }
+
+    public List<TreeContext> getSiblings() {
+        return Collections.unmodifiableList(siblings);
+    }
+
+    public List<TreeContextAction> getOnPopHandlers() {
+        return Collections.unmodifiableList(onPopHandlers);
+    }
+
+    public void afterVisit(TreeContextAction action) {
+        onPopHandlers.add(action);
+    }
+
+    public void afterVisit(@DelegatesTo(value=TreeContext.class, strategy=Closure.DELEGATE_FIRST) Closure<?> action) {
+        Closure<?> clone = MatcherUtils.cloneWithDelegate(action, this);
+        afterVisit(DefaultGroovyMethods.asType(clone, TreeContextAction.class));
+    }
+
+    public void setReplacement(Expression replacement) {
+        userdata.put(TreeContextKey.expression_replacement, Collections.singletonList(replacement));
+    }
+
+    public Expression getReplacement() {
+        List<?> list = userdata.get(TreeContextKey.expression_replacement);
+        if (list.size()==1) {
+            return (Expression) list.get(0);
+        }
+        return null;
+    }
+
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder("TreeContext{");
+        sb.append("node=").append(node!=null?node.getClass().getSimpleName():"undefined");
+        TreeContext p = parent;
+        if (p!=null) {
+            sb.append(", path=");
+        }
+        while (p!=null) {
+            sb.append(p.node!=null?p.node.getClass().getSimpleName():"undefined");
+            sb.append("<-");
+            p = p.parent;
+        }
+        //sb.append(", siblings=").append(siblings);
+        sb.append('}');
+        return sb.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
new file mode 100644
index 0000000..2c198d3
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/TreeContextAction.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher;
+
+public interface TreeContextAction {
+    void call(TreeContext context);
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
new file mode 100644
index 0000000..ae82081
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import groovy.lang.Closure;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.builder.AstBuilder;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.macro.transform.MacroInvocationTrap;
+import org.codehaus.groovy.macro.transform.MacroTransformation;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public enum MacroBuilder {
+    INSTANCE;
+
+    public <T> T macro(String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(false, source, context, resultClass);
+    }
+
+    public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(CompilePhase.CONVERSION, asIs, source, context, resultClass);
+    }
+
+    public <T> T macro(CompilePhase compilePhase, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        return macro(compilePhase, false, source, context, resultClass);
+    }
+
+    @SuppressWarnings("unchecked")
+    public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+        final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
+        final String labelledSource = label + source;
+        final int linesOffset = 1;
+        final int columnsOffset = label.length() + 1; // +1 because of {
+        
+        List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
+
+        for(ASTNode node : nodes) {
+            if (node instanceof BlockStatement) {
+
+                BlockStatement closureBlock = (BlockStatement) ((BlockStatement)node).getStatements().get(0);
+
+                (new ClassCodeExpressionTransformer() {
+                    public Expression transform(Expression expression) {
+                        if(!(expression instanceof MethodCallExpression)) {
+                            return super.transform(expression);
+                        }
+
+                        MethodCallExpression call = (MethodCallExpression) expression;
+
+                        if(!MacroInvocationTrap.isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                            return super.transform(expression);
+                        }
+
+                        MacroSubstitutionKey key = new MacroSubstitutionKey(call, linesOffset, columnsOffset);
+                        
+                        return context.get(key).call();
+                    }
+
+                    @Override
+                    protected SourceUnit getSourceUnit() {
+                        // Could be null if there are no errors
+                        return null;
+                    }
+                }).visitBlockStatement(closureBlock);
+
+                return (T) getMacroValue(closureBlock, asIs);
+            }
+        }
+        return null;
+    }
+
+    public static ASTNode getMacroValue(BlockStatement closureBlock, boolean asIs) {
+        if(!asIs && closureBlock.getStatements().size() == 1) {
+            Statement result = closureBlock.getStatements().get(0);
+            if(result instanceof ExpressionStatement) {
+                return ((ExpressionStatement) result).getExpression();
+            } else {
+                return result;
+            }
+        }
+        return closureBlock;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
new file mode 100644
index 0000000..5c41c04
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import groovy.lang.Closure;
+import groovy.lang.DelegatesTo;
+import org.codehaus.groovy.control.CompilePhase;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroGroovyMethods {
+
+    public static class MacroValuePlaceholder {
+        public static Object $v(Closure cl) {
+            // replaced with AST transformations
+            return null; 
+        }
+    }
+
+    public static <T> T macro(Object self, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+
+    public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
new file mode 100644
index 0000000..e895867
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
+
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.expr.ArgumentListExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroSubstitutionKey {
+
+    private int startLine;
+    private int startColumn;
+    private int endLine;
+    private int endColumn;
+
+    public MacroSubstitutionKey(int startLine, int startColumn, int endLine, int endColumn) {
+        this.startLine = startLine;
+        this.startColumn = startColumn;
+        this.endLine = endLine;
+        this.endColumn = endColumn;
+    }
+    
+    public MacroSubstitutionKey(Expression expression, int linesOffset, int columnsOffset) {
+        this(
+                expression.getLineNumber() - linesOffset,
+                expression.getColumnNumber() - (expression.getLineNumber() == linesOffset ? columnsOffset : 0),
+                expression.getLastLineNumber() - linesOffset,
+                expression.getLastColumnNumber() - (expression.getLastLineNumber() == linesOffset ? columnsOffset : 0)
+        );
+    }
+    
+    public ConstructorCallExpression toConstructorCallExpression() {
+        return new ConstructorCallExpression(
+                ClassHelper.make(this.getClass()),
+                new ArgumentListExpression(new Expression[] {
+                        new ConstantExpression(startLine),
+                        new ConstantExpression(startColumn),
+                        new ConstantExpression(endLine),
+                        new ConstantExpression(endColumn)
+                })
+        );
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        MacroSubstitutionKey that = (MacroSubstitutionKey) o;
+
+        if (endColumn != that.endColumn) return false;
+        if (endLine != that.endLine) return false;
+        if (startColumn != that.startColumn) return false;
+        if (startLine != that.startLine) return false;
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = startLine;
+        result = 31 * result + startColumn;
+        result = 31 * result + endLine;
+        result = 31 * result + endColumn;
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "SubstitutionKey{" +
+                "startLine=" + startLine +
+                ", startColumn=" + startColumn +
+                ", endLine=" + endLine +
+                ", endColumn=" + endColumn +
+                '}';
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
new file mode 100644
index 0000000..127fb4b
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
+
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.CodeVisitorSupport;
+import org.codehaus.groovy.ast.MethodInvocationTrap;
+import org.codehaus.groovy.ast.expr.*;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.control.io.ReaderSource;
+import org.codehaus.groovy.macro.runtime.MacroBuilder;
+import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+public class MacroInvocationTrap extends MethodInvocationTrap {
+
+    public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        super(source, sourceUnit);
+    }
+
+    @Override
+    protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
+        final ClosureExpression closureExpression = getClosureArgument(macroCall);
+
+        if(closureExpression == null) {
+            return true;
+        }
+
+        if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
+            addError("Macro closure arguments are not allowed", closureExpression);
+            return true;
+        }
+
+        final MapExpression mapExpression = new MapExpression();
+
+        (new CodeVisitorSupport() {
+            @Override
+            public void visitMethodCallExpression(MethodCallExpression call) {
+                super.visitMethodCallExpression(call);
+
+                if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
+                    ClosureExpression substitutionClosureExpression = getClosureArgument(call);
+
+                    if(substitutionClosureExpression == null) {
+                        return;
+                    }
+
+                    MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
+
+                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
+                }
+            }
+        }).visitClosureExpression(closureExpression);
+
+        String source = convertClosureToSource(closureExpression);
+
+        BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
+
+        Boolean asIs = false;
+
+        TupleExpression macroArguments = getMacroArguments(macroCall);
+
+        if(macroArguments == null) {
+            return true;
+        }
+
+        List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
+
+        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
+            Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
+            if((asIsArgumentExpression instanceof ConstantExpression)) {
+                ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
+
+                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                    addError("AsIs argument value should be boolean", asIsConstantExpression);
+                    return true;
+                }
+
+                asIs = (Boolean) asIsConstantExpression.getValue();
+            }
+        }
+
+        macroArgumentsExpressions.remove(macroArgumentsExpressions.size() - 1);
+
+        macroArgumentsExpressions.add(new ConstantExpression(source));
+        macroArgumentsExpressions.add(mapExpression);
+        macroArgumentsExpressions.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
+
+        macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
+        macroCall.setSpreadSafe(false);
+        macroCall.setSafe(false);
+        macroCall.setImplicitThis(false);
+        
+        return true;
+    }
+
+    @Override
+    protected boolean isBuildInvocation(MethodCallExpression call) {
+        return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
+    }
+
+    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
+        if (call == null) throw new IllegalArgumentException("Null: call");
+        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+
+        if(!(call.getMethod() instanceof ConstantExpression)) {
+            return false;
+        }
+
+        if(!(methodName.equals(call.getMethodAsString()))) {
+            return false;
+        }
+
+        // is method object correct type?
+        return call.getObjectExpression() == THIS_EXPRESSION;
+    }
+    
+    protected TupleExpression getMacroArguments(MethodCallExpression call) {
+        Expression macroCallArguments = call.getArguments();
+        if (macroCallArguments == null) {
+            addError("Call should have arguments", call);
+            return null;
+        }
+
+        if(!(macroCallArguments instanceof TupleExpression)) {
+            addError("Call should have TupleExpression as arguments", macroCallArguments);
+            return null;
+        }
+
+        TupleExpression tupleArguments = (TupleExpression) macroCallArguments;
+
+        if (tupleArguments.getExpressions() == null) {
+            addError("Call arguments should have expressions", tupleArguments);
+            return null;
+        }
+        
+        return tupleArguments;
+    }
+    
+    protected ClosureExpression getClosureArgument(MethodCallExpression call) {
+        TupleExpression tupleArguments = getMacroArguments(call);
+
+        if(tupleArguments.getExpressions().size() < 1) {
+            addError("Call arguments should have at least one argument", tupleArguments);
+            return null;
+        }
+
+        Expression result = tupleArguments.getExpression(tupleArguments.getExpressions().size() - 1);
+        if (!(result instanceof ClosureExpression)) {
+            addError("Last call argument should be a closure", result);
+            return null;
+        }
+
+        return (ClosureExpression) result;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
new file mode 100644
index 0000000..65284b5
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
+
+import org.codehaus.groovy.ast.*;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+
+/**
+ *
+ * @author Sergei Egorov <bs...@gmail.com>
+ */
+
+@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
+public class MacroTransformation extends MethodCallTransformation {
+
+    public static final String DOLLAR_VALUE = "$v";
+    public static final String MACRO_METHOD = "macro";
+
+    @Override
+    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
+        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
deleted file mode 100644
index ae82081..0000000
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
-
-import groovy.lang.Closure;
-import org.codehaus.groovy.ast.ASTNode;
-import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
-import org.codehaus.groovy.ast.builder.AstBuilder;
-import org.codehaus.groovy.ast.expr.Expression;
-import org.codehaus.groovy.ast.expr.MethodCallExpression;
-import org.codehaus.groovy.ast.stmt.BlockStatement;
-import org.codehaus.groovy.ast.stmt.ExpressionStatement;
-import org.codehaus.groovy.ast.stmt.Statement;
-import org.codehaus.groovy.control.CompilePhase;
-import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.macro.transform.MacroInvocationTrap;
-import org.codehaus.groovy.macro.transform.MacroTransformation;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-public enum MacroBuilder {
-    INSTANCE;
-
-    public <T> T macro(String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(false, source, context, resultClass);
-    }
-
-    public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(CompilePhase.CONVERSION, asIs, source, context, resultClass);
-    }
-
-    public <T> T macro(CompilePhase compilePhase, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(compilePhase, false, source, context, resultClass);
-    }
-
-    @SuppressWarnings("unchecked")
-    public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
-        final String labelledSource = label + source;
-        final int linesOffset = 1;
-        final int columnsOffset = label.length() + 1; // +1 because of {
-        
-        List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
-
-        for(ASTNode node : nodes) {
-            if (node instanceof BlockStatement) {
-
-                BlockStatement closureBlock = (BlockStatement) ((BlockStatement)node).getStatements().get(0);
-
-                (new ClassCodeExpressionTransformer() {
-                    public Expression transform(Expression expression) {
-                        if(!(expression instanceof MethodCallExpression)) {
-                            return super.transform(expression);
-                        }
-
-                        MethodCallExpression call = (MethodCallExpression) expression;
-
-                        if(!MacroInvocationTrap.isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
-                            return super.transform(expression);
-                        }
-
-                        MacroSubstitutionKey key = new MacroSubstitutionKey(call, linesOffset, columnsOffset);
-                        
-                        return context.get(key).call();
-                    }
-
-                    @Override
-                    protected SourceUnit getSourceUnit() {
-                        // Could be null if there are no errors
-                        return null;
-                    }
-                }).visitBlockStatement(closureBlock);
-
-                return (T) getMacroValue(closureBlock, asIs);
-            }
-        }
-        return null;
-    }
-
-    public static ASTNode getMacroValue(BlockStatement closureBlock, boolean asIs) {
-        if(!asIs && closureBlock.getStatements().size() == 1) {
-            Statement result = closureBlock.getStatements().get(0);
-            if(result instanceof ExpressionStatement) {
-                return ((ExpressionStatement) result).getExpression();
-            } else {
-                return result;
-            }
-        }
-        return closureBlock;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
deleted file mode 100644
index 5c41c04..0000000
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
-
-import groovy.lang.Closure;
-import groovy.lang.DelegatesTo;
-import org.codehaus.groovy.control.CompilePhase;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-public class MacroGroovyMethods {
-
-    public static class MacroValuePlaceholder {
-        public static Object $v(Closure cl) {
-            // replaced with AST transformations
-            return null; 
-        }
-    }
-
-    public static <T> T macro(Object self, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
-
-    public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
-
-    public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
-
-    public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
deleted file mode 100644
index e895867..0000000
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroSubstitutionKey.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.runtime;
-
-import org.codehaus.groovy.ast.ClassHelper;
-import org.codehaus.groovy.ast.expr.ArgumentListExpression;
-import org.codehaus.groovy.ast.expr.ConstantExpression;
-import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
-import org.codehaus.groovy.ast.expr.Expression;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-public class MacroSubstitutionKey {
-
-    private int startLine;
-    private int startColumn;
-    private int endLine;
-    private int endColumn;
-
-    public MacroSubstitutionKey(int startLine, int startColumn, int endLine, int endColumn) {
-        this.startLine = startLine;
-        this.startColumn = startColumn;
-        this.endLine = endLine;
-        this.endColumn = endColumn;
-    }
-    
-    public MacroSubstitutionKey(Expression expression, int linesOffset, int columnsOffset) {
-        this(
-                expression.getLineNumber() - linesOffset,
-                expression.getColumnNumber() - (expression.getLineNumber() == linesOffset ? columnsOffset : 0),
-                expression.getLastLineNumber() - linesOffset,
-                expression.getLastColumnNumber() - (expression.getLastLineNumber() == linesOffset ? columnsOffset : 0)
-        );
-    }
-    
-    public ConstructorCallExpression toConstructorCallExpression() {
-        return new ConstructorCallExpression(
-                ClassHelper.make(this.getClass()),
-                new ArgumentListExpression(new Expression[] {
-                        new ConstantExpression(startLine),
-                        new ConstantExpression(startColumn),
-                        new ConstantExpression(endLine),
-                        new ConstantExpression(endColumn)
-                })
-        );
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-
-        MacroSubstitutionKey that = (MacroSubstitutionKey) o;
-
-        if (endColumn != that.endColumn) return false;
-        if (endLine != that.endLine) return false;
-        if (startColumn != that.startColumn) return false;
-        if (startLine != that.startLine) return false;
-
-        return true;
-    }
-
-    @Override
-    public int hashCode() {
-        int result = startLine;
-        result = 31 * result + startColumn;
-        result = 31 * result + endLine;
-        result = 31 * result + endColumn;
-        return result;
-    }
-
-    @Override
-    public String toString() {
-        return "SubstitutionKey{" +
-                "startLine=" + startLine +
-                ", startColumn=" + startColumn +
-                ", endLine=" + endLine +
-                ", endColumn=" + endColumn +
-                '}';
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
deleted file mode 100644
index 127fb4b..0000000
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
-
-import org.codehaus.groovy.ast.ClassHelper;
-import org.codehaus.groovy.ast.CodeVisitorSupport;
-import org.codehaus.groovy.ast.MethodInvocationTrap;
-import org.codehaus.groovy.ast.expr.*;
-import org.codehaus.groovy.ast.stmt.BlockStatement;
-import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.control.io.ReaderSource;
-import org.codehaus.groovy.macro.runtime.MacroBuilder;
-import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-public class MacroInvocationTrap extends MethodInvocationTrap {
-
-    public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
-        super(source, sourceUnit);
-    }
-
-    @Override
-    protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
-        final ClosureExpression closureExpression = getClosureArgument(macroCall);
-
-        if(closureExpression == null) {
-            return true;
-        }
-
-        if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
-            addError("Macro closure arguments are not allowed", closureExpression);
-            return true;
-        }
-
-        final MapExpression mapExpression = new MapExpression();
-
-        (new CodeVisitorSupport() {
-            @Override
-            public void visitMethodCallExpression(MethodCallExpression call) {
-                super.visitMethodCallExpression(call);
-
-                if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
-                    ClosureExpression substitutionClosureExpression = getClosureArgument(call);
-
-                    if(substitutionClosureExpression == null) {
-                        return;
-                    }
-
-                    MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
-
-                    mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
-                }
-            }
-        }).visitClosureExpression(closureExpression);
-
-        String source = convertClosureToSource(closureExpression);
-
-        BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
-
-        Boolean asIs = false;
-
-        TupleExpression macroArguments = getMacroArguments(macroCall);
-
-        if(macroArguments == null) {
-            return true;
-        }
-
-        List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
-
-        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
-            Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
-            if((asIsArgumentExpression instanceof ConstantExpression)) {
-                ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
-
-                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
-                    addError("AsIs argument value should be boolean", asIsConstantExpression);
-                    return true;
-                }
-
-                asIs = (Boolean) asIsConstantExpression.getValue();
-            }
-        }
-
-        macroArgumentsExpressions.remove(macroArgumentsExpressions.size() - 1);
-
-        macroArgumentsExpressions.add(new ConstantExpression(source));
-        macroArgumentsExpressions.add(mapExpression);
-        macroArgumentsExpressions.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
-
-        macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
-        macroCall.setSpreadSafe(false);
-        macroCall.setSafe(false);
-        macroCall.setImplicitThis(false);
-        
-        return true;
-    }
-
-    @Override
-    protected boolean isBuildInvocation(MethodCallExpression call) {
-        return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
-    }
-
-    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
-        if (call == null) throw new IllegalArgumentException("Null: call");
-        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
-
-        if(!(call.getMethod() instanceof ConstantExpression)) {
-            return false;
-        }
-
-        if(!(methodName.equals(call.getMethodAsString()))) {
-            return false;
-        }
-
-        // is method object correct type?
-        return call.getObjectExpression() == THIS_EXPRESSION;
-    }
-    
-    protected TupleExpression getMacroArguments(MethodCallExpression call) {
-        Expression macroCallArguments = call.getArguments();
-        if (macroCallArguments == null) {
-            addError("Call should have arguments", call);
-            return null;
-        }
-
-        if(!(macroCallArguments instanceof TupleExpression)) {
-            addError("Call should have TupleExpression as arguments", macroCallArguments);
-            return null;
-        }
-
-        TupleExpression tupleArguments = (TupleExpression) macroCallArguments;
-
-        if (tupleArguments.getExpressions() == null) {
-            addError("Call arguments should have expressions", tupleArguments);
-            return null;
-        }
-        
-        return tupleArguments;
-    }
-    
-    protected ClosureExpression getClosureArgument(MethodCallExpression call) {
-        TupleExpression tupleArguments = getMacroArguments(call);
-
-        if(tupleArguments.getExpressions().size() < 1) {
-            addError("Call arguments should have at least one argument", tupleArguments);
-            return null;
-        }
-
-        Expression result = tupleArguments.getExpression(tupleArguments.getExpressions().size() - 1);
-        if (!(result instanceof ClosureExpression)) {
-            addError("Last call argument should be a closure", result);
-            return null;
-        }
-
-        return (ClosureExpression) result;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/248e0fd9/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
deleted file mode 100644
index 65284b5..0000000
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2003-2013 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 org.codehaus.groovy.macro.transform;
-
-import org.codehaus.groovy.ast.*;
-import org.codehaus.groovy.control.CompilePhase;
-import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.transform.GroovyASTTransformation;
-
-/**
- *
- * @author Sergei Egorov <bs...@gmail.com>
- */
-
-@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
-public class MacroTransformation extends MethodCallTransformation {
-
-    public static final String DOLLAR_VALUE = "$v";
-    public static final String MACRO_METHOD = "macro";
-
-    @Override
-    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
-        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
-    }
-}
-



[11/37] incubator-groovy git commit: more "macro" usage examples in SimpleMacroTest

Posted by cc...@apache.org.
more "macro" usage examples in SimpleMacroTest


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/01805ce6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/01805ce6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/01805ce6

Branch: refs/heads/master
Commit: 01805ce63fdc261489817fd694ec2ad6d806104c
Parents: df5fa06
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:21:15 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:05 2015 +0300

----------------------------------------------------------------------
 .../src/test/groovy/groovy/SimpleMacroTest.groovy           | 9 +++++++++
 1 file changed, 9 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/01805ce6/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index df46802..64bb1bf 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -30,6 +30,9 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.*;
  */
 @CompileStatic
 class SimpleMacroTest extends GroovyShellTestCase {
+    
+    static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
+    
     public void testMethod() {
 
         def someVariable = new VariableExpression("someVariable");
@@ -65,6 +68,12 @@ class SimpleMacroTest extends GroovyShellTestCase {
 
         assertSyntaxTree(expected, result);
     }
+    
+    public void testMethodName() {
+        // Very useful when you don't want to hardcode method or variable names
+        assertEquals("toLowerCase", TO_LOWER_CASE_METHOD_NAME)
+        assertEquals("valueOf", macro { String.valueOf() }.getMethodAsString())
+    }
 
     public void testBlock() {
 


[20/37] incubator-groovy git commit: First load of unit tests for ASTMatcher

Posted by cc...@apache.org.
First load of unit tests for ASTMatcher


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/f736c6ad
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/f736c6ad
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/f736c6ad

Branch: refs/heads/master
Commit: f736c6ad3beef8051c7c563ca5d9256cb7fbfc6b
Parents: cae1462
Author: Cedric Champeau <ce...@gmail.com>
Authored: Thu Oct 16 17:29:37 2014 +0200
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:10 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      |  80 +++++++--
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 174 +++++++++++++++++++
 2 files changed, 240 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f736c6ad/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index bce42da..cec1632 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -16,11 +16,13 @@
 package org.codehaus.groovy.macro.matcher
 
 import groovy.transform.CompileStatic
+import groovy.transform.TypeCheckingMode
 import org.codehaus.groovy.ast.*
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.*
 import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
+import org.codehaus.groovy.transform.stc.StaticTypesMarker
 
 @CompileStatic
 class ASTMatcher extends ClassCodeVisitorSupport {
@@ -288,6 +290,7 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     }
 
     @Override
+    @CompileStatic(TypeCheckingMode.SKIP)
     public void visitDeclarationExpression(final DeclarationExpression expression) {
         doWithNode(DeclarationExpression, current) {
             super.visitDeclarationExpression(expression)
@@ -416,7 +419,8 @@ class ASTMatcher extends ClassCodeVisitorSupport {
             }
             match = match && (call.methodAsString==mce.methodAsString) &&
                     (call.safe==mce.safe) &&
-                    (call.spreadSafe == mce.spreadSafe)
+                    (call.spreadSafe == mce.spreadSafe) &&
+                    (call.implicitThis == mce.implicitThis)
         }
     }
 
@@ -427,8 +431,11 @@ class ASTMatcher extends ClassCodeVisitorSupport {
 
     @Override
     public void visitConstructorCallExpression(final ConstructorCallExpression call) {
-        doWithNode(call.arguments.class, ((ConstructorCallExpression)call).arguments) {
+        def cur = (ConstructorCallExpression) current
+        doWithNode(call.arguments.class, cur.arguments) {
             call.arguments.visit(this)
+            match = match &&
+                    (call.type == cur.type)
         }
     }
 
@@ -469,18 +476,29 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     }
 
     @Override
-    public void visitShortTernaryExpression(final ElvisOperatorExpression expression) {
-        super.visitShortTernaryExpression(expression);
-    }
-
-    @Override
     public void visitPostfixExpression(final PostfixExpression expression) {
-        super.visitPostfixExpression(expression);
+        doWithNode(PostfixExpression, current) {
+            def origExpr = expression.expression
+            def curExpr = (PostfixExpression) current
+            doWithNode(origExpr.class, curExpr.expression) {
+                origExpr.visit(this)
+                match = match &&
+                        (expression.operation.type==curExpr.operation.type)
+            }
+        }
     }
 
     @Override
     public void visitPrefixExpression(final PrefixExpression expression) {
-        super.visitPrefixExpression(expression);
+        doWithNode(PrefixExpression, current) {
+            def origExpr = expression.expression
+            def curExpr = (PrefixExpression) current
+            doWithNode(origExpr.class, curExpr.expression) {
+                origExpr.visit(this)
+                match = match &&
+                        (expression.operation.type==curExpr.operation.type)
+            }
+        }
     }
 
     @Override
@@ -572,25 +590,54 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     }
 
     @Override
+    @CompileStatic(TypeCheckingMode.SKIP)
     public void visitConstantExpression(final ConstantExpression expression) {
-        super.visitConstantExpression(expression);
+        doWithNode(ConstantExpression, current) {
+            def cur = (ConstantExpression) current
+            super.visitConstantExpression(expression)
+            match = match &&
+                    (expression.type==cur.type) &&
+                    (expression.value==cur.value)
+        }
     }
 
     @Override
+    @CompileStatic(TypeCheckingMode.SKIP)
     public void visitClassExpression(final ClassExpression expression) {
-        super.visitClassExpression(expression);
+        doWithNode(ClassExpression, current) {
+            super.visitClassExpression(expression)
+            def cexp = (ClassExpression) current
+            match = match && (cexp.type == expression.type)
+        }
     }
 
     @Override
     public void visitVariableExpression(final VariableExpression expression) {
         doWithNode(VariableExpression, current) {
-            match = expression.name == ((VariableExpression) current).name
+            def curVar = (VariableExpression) current
+            match = match &&
+                    (expression.name == curVar.name) &&
+                    (expression.type == curVar.type) &&
+                    (expression.originType == curVar.originType)
         }
     }
 
     @Override
     public void visitPropertyExpression(final PropertyExpression expression) {
-        super.visitPropertyExpression(expression);
+        doWithNode(PropertyExpression, current) {
+            def currentPexp = (PropertyExpression) current
+            doWithNode(expression.objectExpression.class, currentPexp.objectExpression) {
+                expression.objectExpression.visit(this)
+            }
+            doWithNode(expression.property.class, currentPexp.property) {
+                expression.property.visit(this)
+            }
+            match = match &&
+                    (expression.propertyAsString==currentPexp.propertyAsString) &&
+                    (expression.implicitThis==currentPexp.implicitThis) &&
+                    (expression.safe==currentPexp.safe) &&
+                    (expression.spreadSafe==currentPexp.spreadSafe)
+        }
     }
 
     @Override
@@ -611,7 +658,12 @@ class ASTMatcher extends ClassCodeVisitorSupport {
     @Override
     protected void visitListOfExpressions(final List<? extends Expression> list) {
         if (list == null) return;
-        def iter = ((List<Expression>) current).iterator()
+        def currentExprs = (List<Expression>) current
+        if (currentExprs.size()!=list.size()) {
+            match = false
+            return
+        }
+        def iter = currentExprs.iterator()
         for (Expression expression : list) {
             def next = iter.next()
             if (expression instanceof SpreadExpression) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/f736c6ad/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
new file mode 100644
index 0000000..6f42859
--- /dev/null
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher
+
+import org.codehaus.groovy.ast.expr.ClassExpression
+import org.codehaus.groovy.control.CompilePhase
+
+class ASTMatcherTest extends GroovyTestCase {
+    void testMatchesSimpleVar() {
+        def ast = macro { a }
+        assert ASTMatcher.matches(ast, ast)
+    }
+    void testMatchesSimpleVarNeg() {
+        def ast = macro { a }
+        def ast2 = macro { b }
+        assert !ASTMatcher.matches(ast, ast2)
+        assert !ASTMatcher.matches(ast2, ast)
+    }
+
+    void testBinaryExpression() {
+        def ast1 = macro { a+b }
+        def ast2 = macro { a+b }
+        def ast3 = macro { b+a }
+        def ast4 = macro { a-b }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testMethodCallExpression() {
+        def ast1 = macro { foo() }
+        def ast2 = macro { foo() }
+        def ast3 = macro { this.foo() }
+        def ast4 = macro { bar() }
+        def ast5 = macro { foo(bar) }
+        def ast6 = macro { foo(bar())}
+        def ast7 = macro { foo(bar())}
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert ASTMatcher.matches(ast6, ast7)
+    }
+
+    void testPropertyExpression() {
+        def ast1 = macro { this.p }
+        def ast2 = macro { this.p }
+        def ast3 = macro { that.p }
+        def ast4 = macro { this.p2 }
+        def ast5 = macro { this?.p }
+        def ast6 = macro { this*.p }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert !ASTMatcher.matches(ast1, ast6)
+    }
+
+    void testClassExpression() {
+        def ast1 = macro(CompilePhase.SEMANTIC_ANALYSIS) { String }
+        def ast2 = macro(CompilePhase.SEMANTIC_ANALYSIS) { String }
+        def ast3 = macro(CompilePhase.SEMANTIC_ANALYSIS) { Boolean }
+        assert ast1 instanceof ClassExpression
+        assert ast2 instanceof ClassExpression
+        assert ast3 instanceof ClassExpression
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+    }
+
+    void testTernaryExpression() {
+        def ast1 = macro { a?b:c }
+        def ast2 = macro { a?b:c }
+        def ast3 = macro { b?b:c }
+        def ast4 = macro { a?a:c }
+        def ast5 = macro { a?b:a }
+        def ast6 = macro { a?(a+b):a }
+        def ast7 = macro { a?(a+b):a }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert ASTMatcher.matches(ast6, ast7)
+    }
+
+    void testElvis() {
+        def ast1 = macro { a?:c }
+        def ast2 = macro { a?:c }
+        def ast3 = macro { b?:c }
+        def ast4 = macro { a?:a }
+        def ast5 = macro { a?:(a+b) }
+        def ast6 = macro { a?:(a+b) }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+        assert ASTMatcher.matches(ast5, ast6)
+    }
+
+    void testPrefixExpression() {
+        def ast1 = macro { ++a }
+        def ast2 = macro { ++a }
+        def ast3 = macro { ++b }
+        def ast4 = macro { --a }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testPostfixExpression() {
+        def ast1 = macro { a++ }
+        def ast2 = macro { a++ }
+        def ast3 = macro { b++ }
+        def ast4 = macro { a-- }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testConstructorCall() {
+        def ast1 = macro { new Foo() }
+        def ast2 = macro { new Foo() }
+        def ast3 = macro { new Bar() }
+        def ast4 = macro { new Foo(bar) }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+    }
+
+    void testDeclaration() {
+        def ast1 = macro { def x = 1 }
+        def ast2 = macro { def x = 1 }
+        def ast3 = macro { int x = 1 }
+        def ast4 = macro { def y = 1 }
+        def ast5 = macro { def x = 2 }
+        assert ASTMatcher.matches(ast1, ast1)
+        assert ASTMatcher.matches(ast1, ast2)
+        assert ASTMatcher.matches(ast2, ast1)
+        assert !ASTMatcher.matches(ast1, ast3)
+        assert !ASTMatcher.matches(ast1, ast4)
+        assert !ASTMatcher.matches(ast1, ast5)
+    }
+}


[31/37] incubator-groovy git commit: Add ability to relax binary expression matching thanks to constraints on token type

Posted by cc...@apache.org.
Add ability to relax binary expression matching thanks to constraints on token type


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/3271e6dc
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/3271e6dc
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/3271e6dc

Branch: refs/heads/master
Commit: 3271e6dcce6a02377848640ace5de048e91c6b21
Parents: bcd68a7
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Nov 12 08:29:12 2014 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:12 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy      | 33 +++++++---
 .../macro/matcher/MatchingConstraints.groovy    | 33 +++-------
 .../macro/matcher/internal/AnyTokenMatch.groovy | 32 ++++++++++
 .../matcher/internal/ConstraintPredicate.groovy | 24 ++++++++
 .../internal/MatchingConstraintsBuilder.groovy  | 64 ++++++++++++++++++++
 .../groovy/macro/matcher/ASTMatcherTest.groovy  | 54 +++++++++++++++++
 6 files changed, 207 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index 727f39e..ab8b459 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -27,6 +27,7 @@ import org.codehaus.groovy.ast.stmt.Statement
 import org.codehaus.groovy.ast.stmt.WhileStatement
 import org.codehaus.groovy.classgen.BytecodeExpression
 import org.codehaus.groovy.control.SourceUnit
+import org.codehaus.groovy.macro.matcher.internal.MatchingConstraintsBuilder
 
 @CompileStatic
 class ASTMatcher extends ContextualClassCodeVisitor {
@@ -98,18 +99,28 @@ class ASTMatcher extends ContextualClassCodeVisitor {
         }
     }
 
-    private String findPlaceholder(Object exp) {
+    public <T> T ifConstraint(T defaultValue, @DelegatesTo(MatchingConstraints) Closure<T> code) {
         def constraints = (List<MatchingConstraints>) treeContext.getUserdata(MatchingConstraints, true)
         if (constraints) {
-            def placeholders = constraints[0].placeholders
+            def clone = (Closure<T>) code.clone()
+            clone.resolveStrategy = Closure.DELEGATE_FIRST
+            clone.delegate = constraints[0]
+            clone()
+        } else {
+            defaultValue
+        }
+    }
+
+    private String findPlaceholder(Object exp) {
+        ifConstraint(null) {
             if ((exp instanceof VariableExpression && placeholders.contains(exp.name))) {
                 return exp.name
-            }
-            if ((exp instanceof ConstantExpression && placeholders.contains(exp.value))) {
+            } else if ((exp instanceof ConstantExpression && placeholders.contains(exp.value))) {
                 return exp.value
+            } else {
+                null
             }
         }
-        null
     }
 
     private void doWithNode(Object patternNode, Object foundNode, Closure cl) {
@@ -525,7 +536,13 @@ class ASTMatcher extends ContextualClassCodeVisitor {
                 rightExpression.visit(this)
             }
             if (bin.operation.type != expression.operation.type) {
-                failIfNot(false)
+                failIfNot(ifConstraint(false) {
+                    if (tokenPredicate) {
+                        tokenPredicate.apply(bin.operation)
+                    } else {
+                        false
+                    }
+                })
             }
         }
     }
@@ -971,8 +988,8 @@ class ASTMatcher extends ContextualClassCodeVisitor {
      */
     public static ASTNode withConstraints(
             final ASTNode pattern,
-            final @DelegatesTo(value=MatchingConstraints.Builder, strategy=Closure.DELEGATE_ONLY) Closure constraintsSpec) {
-        def builder = new MatchingConstraints.Builder()
+            final @DelegatesTo(value=MatchingConstraintsBuilder, strategy=Closure.DELEGATE_ONLY) Closure constraintsSpec) {
+        def builder = new MatchingConstraintsBuilder()
         def constraints = builder.build(constraintsSpec)
         pattern.putNodeMetaData(MatchingConstraints, constraints)
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
index 82306c0..ed25d35 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
@@ -17,7 +17,10 @@
 package org.codehaus.groovy.macro.matcher
 
 import groovy.transform.CompileStatic
-import groovy.transform.PackageScope
+import groovy.transform.Immutable
+import org.codehaus.groovy.macro.matcher.internal.AnyTokenMatch
+import org.codehaus.groovy.macro.matcher.internal.ConstraintPredicate
+import org.codehaus.groovy.syntax.Token
 
 /**
  * Represents constraints in AST pattern matching.
@@ -26,31 +29,11 @@ import groovy.transform.PackageScope
  * @since 2.4.0
  */
 @CompileStatic
+@Immutable(knownImmutables = ['tokenPredicate'])
 class MatchingConstraints {
-    final Set<String> placeholders = new LinkedHashSet<>()
+    public final static ConstraintPredicate<Token> ANY_TOKEN = AnyTokenMatch.INSTANCE
 
-    @PackageScope static class Builder {
-        private final MatchingConstraints constraints = new MatchingConstraints()
+    final Set<String> placeholders
+    final ConstraintPredicate<Token> tokenPredicate
 
-        MatchingConstraints build(@DelegatesTo(value=Builder, strategy=Closure.DELEGATE_ONLY) Closure spec) {
-            def clone = (Closure) spec.clone()
-            clone.delegate = this
-            clone.resolveStrategy = Closure.DELEGATE_ONLY
-            clone()
-
-            constraints
-        }
-
-        def getProperty(String name) {
-            if ('constraints'==name) {
-                return constraints
-            }
-            name
-        }
-
-        Builder placeholder(String... names) {
-            names.each { String it -> constraints.placeholders.add(it) }
-            this
-        }
-    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
new file mode 100644
index 0000000..afc91c1
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/AnyTokenMatch.groovy
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
+
+import groovy.transform.CompileStatic
+import org.codehaus.groovy.syntax.Token
+
+@CompileStatic
+class AnyTokenMatch implements ConstraintPredicate<Token> {
+    public static final AnyTokenMatch INSTANCE = new AnyTokenMatch()
+
+    private AnyTokenMatch() {}
+
+    @Override
+    boolean apply(final Token a) {
+        true
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
new file mode 100644
index 0000000..5c4fdc8
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/ConstraintPredicate.groovy
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
+
+import groovy.transform.CompileStatic
+
+@CompileStatic
+interface ConstraintPredicate<T> {
+    boolean apply(T a)
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
new file mode 100644
index 0000000..070013b
--- /dev/null
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/internal/MatchingConstraintsBuilder.groovy
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2003-2014 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 org.codehaus.groovy.macro.matcher.internal
+
+import org.codehaus.groovy.macro.matcher.MatchingConstraints
+import org.codehaus.groovy.syntax.Token
+
+class MatchingConstraintsBuilder {
+    Set<String> placeholders = new LinkedHashSet<>()
+    ConstraintPredicate<Token> tokenPredicate
+
+
+    MatchingConstraints build(@DelegatesTo(value=MatchingConstraintsBuilder, strategy=Closure.DELEGATE_ONLY) Closure spec) {
+        def clone = (Closure) spec.clone()
+        clone.delegate = this
+        clone.resolveStrategy = Closure.DELEGATE_ONLY
+        clone()
+
+        new MatchingConstraints(
+                placeholders: Collections.unmodifiableSet(placeholders),
+                tokenPredicate: tokenPredicate)
+    }
+
+    def propertyMissing(String name) {
+        name
+    }
+
+    MatchingConstraintsBuilder placeholder(String... names) {
+        names.each { String it -> placeholders.add(it) }
+        this
+    }
+
+    MatchingConstraintsBuilder anyToken() {
+        tokenPredicate = MatchingConstraints.ANY_TOKEN
+        this
+    }
+
+    MatchingConstraintsBuilder token(@DelegatesTo(value=Token, strategy = Closure.DELEGATE_FIRST) Closure<Boolean> predicate) {
+        def clone = (Closure<Boolean>) predicate.clone()
+        clone.resolveStrategy = Closure.DELEGATE_FIRST
+        tokenPredicate = new ConstraintPredicate<Token>() {
+            @Override
+            boolean apply(final Token a) {
+                clone.delegate = a
+                clone.call(a)
+            }
+        }
+        this
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/3271e6dc/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index 9802a2a..c8ff1fc 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -18,6 +18,7 @@ package org.codehaus.groovy.macro.matcher
 
 import org.codehaus.groovy.ast.ClassNode
 import org.codehaus.groovy.ast.expr.ArrayExpression
+import org.codehaus.groovy.ast.expr.BinaryExpression
 import org.codehaus.groovy.ast.expr.BitwiseNegationExpression
 import org.codehaus.groovy.ast.expr.CastExpression
 import org.codehaus.groovy.ast.expr.ClassExpression
@@ -31,6 +32,7 @@ import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.ast.stmt.WhileStatement
 import org.codehaus.groovy.control.CompilePhase
 import org.codehaus.groovy.macro.transform.MacroClass
+import org.codehaus.groovy.syntax.Types
 
 class ASTMatcherTest extends GroovyTestCase {
     void testMatchesSimpleVar() {
@@ -654,4 +656,56 @@ class ASTMatcherTest extends GroovyTestCase {
             assert ast2.matches(pattern)
         }
     }
+
+    void testMacroCombination() {
+        use(ASTMatcher) {
+            def lhs = macro { a }
+            def rhs = macro { b }
+            def ast = macro { $v { lhs } + $v { rhs } }
+            assert ast instanceof BinaryExpression
+            assert ast.leftExpression.is(lhs)
+            assert ast.rightExpression.is(rhs)
+            def pattern = macro { a + b }
+            assert ast.matches(pattern)
+        }
+    }
+
+    void testRelaxedBinaryExpression() {
+        use(ASTMatcher) {
+            def ast1 = macro { a + b }
+            def ast2 = macro { a - b }
+            def ast3 = macro { a * b }
+            def ast4 = macro { a + c }
+            def pattern = macro {
+                a + b
+            }.withConstraints {
+                anyToken()
+            }
+            assert ast1.matches(pattern)
+            assert ast2.matches(pattern)
+            assert ast3.matches(pattern)
+            assert !ast4.matches(pattern)
+        }
+    }
+
+    void testRelaxedBinaryExpressionWithConstrainedToken() {
+        use(ASTMatcher) {
+            def ast1 = macro { a + b }
+            def ast2 = macro { a - b }
+            def ast3 = macro { a * b }
+            def ast4 = macro { a + c }
+            def pattern = macro {
+                a + b
+            }.withConstraints {
+                token {
+                    type in [Types.PLUS, Types.MINUS]
+                }
+            }
+            assert ast1.matches(pattern)
+            assert ast2.matches(pattern)
+            assert !ast3.matches(pattern)
+            assert !ast4.matches(pattern)
+        }
+    }
+
 }


[10/37] incubator-groovy git commit: fix wrong macro test case superclass

Posted by cc...@apache.org.
fix wrong macro test case superclass


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/b28460b0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/b28460b0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/b28460b0

Branch: refs/heads/master
Commit: b28460b00f371082ae132f6f0c3b23589a8dd839
Parents: 01805ce
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 22:21:58 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:05 2015 +0300

----------------------------------------------------------------------
 .../groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/b28460b0/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index 64bb1bf..ad9b15b 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -29,7 +29,7 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.*;
  * @author Sergei Egorov <bs...@gmail.com>
  */
 @CompileStatic
-class SimpleMacroTest extends GroovyShellTestCase {
+class SimpleMacroTest extends GroovyTestCase {
     
     static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
     


[28/37] incubator-groovy git commit: ASTMatcher: Fix matcher constraints ordering

Posted by cc...@apache.org.
ASTMatcher: Fix matcher constraints ordering


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/bea30424
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/bea30424
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/bea30424

Branch: refs/heads/master
Commit: bea3042479e330ee4e72b5676390d89ff425274d
Parents: 3271e6d
Author: Cedric Champeau <ce...@gmail.com>
Authored: Wed Nov 12 10:58:06 2014 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:12 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/matcher/ASTMatcher.groovy       |  4 ++--
 .../groovy/macro/matcher/ASTMatcherTest.groovy   | 19 +++++++++++++++++++
 2 files changed, 21 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bea30424/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
index ab8b459..e8d83f7 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ASTMatcher.groovy
@@ -131,17 +131,17 @@ class ASTMatcher extends ContextualClassCodeVisitor {
 
         boolean doPush = treeContext.node!=foundNode && foundNode instanceof ASTNode
         if (doPush) {
+            pushContext((ASTNode)foundNode)
             if (patternNode instanceof ASTNode) {
                 storeContraints(patternNode)
             }
-            pushContext((ASTNode)foundNode)
         }
 
         if (!isWildcardExpression(patternNode)) {
             String placeholder = findPlaceholder(patternNode)
             if (placeholder) {
                 def alreadySeenAST = treeContext.getUserdata("placeholder_$placeholder", true)
-                if (!alreadySeenAST) {
+                if (alreadySeenAST==null) {
                     treeContext.parent.putUserdata("placeholder_$placeholder", foundNode)
                 } else {
                     // during the tree inspection, placeholder already found

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/bea30424/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
index c8ff1fc..35301e4 100644
--- a/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/org/codehaus/groovy/macro/matcher/ASTMatcherTest.groovy
@@ -708,4 +708,23 @@ class ASTMatcherTest extends GroovyTestCase {
         }
     }
 
+    void testInlineMacroCombinationWithConstraints() {
+        use(ASTMatcher) {
+            def ast1 = macro { a + b }
+            def ast2 = macro { b + b }
+            def ast3 = macro { b + c }
+            def ast4 = macro { b - b }
+            def pattern = macro {
+                $v { macro { a }.withConstraints { placeholder a } } + $v { macro { b } }
+            }.withConstraints {
+                anyToken()
+            }
+            assert pattern instanceof BinaryExpression
+            assert ast1.matches(pattern)
+            assert ast2.matches(pattern)
+            assert !ast3.matches(pattern)
+            assert ast4.matches(pattern)
+        }
+    }
+
 }


[35/37] incubator-groovy git commit: Update @since tags

Posted by cc...@apache.org.
Update @since tags


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/93a42aa9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/93a42aa9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/93a42aa9

Branch: refs/heads/master
Commit: 93a42aa9b9072500d58a60bc12d359f4787e3b01
Parents: f08195f
Author: Cedric Champeau <ce...@gmail.com>
Authored: Thu Mar 12 10:45:51 2015 +0100
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:33:13 2015 +0300

----------------------------------------------------------------------
 .../codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java  | 2 +-
 .../org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/93a42aa9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
index a8f0e40..36f6105 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/ContextualClassCodeVisitor.java
@@ -59,7 +59,7 @@ import java.util.List;
  * performing some operations.
  *
  * @author Cedric Champeau
- * @since 2.4.0
+ * @since 2.5.0
  */
 public abstract class ContextualClassCodeVisitor extends ClassCodeVisitorSupport {
     private final Deque<TreeContext> treeContextStack = new ArrayDeque<TreeContext>();

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/93a42aa9/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
index ef46b58..cb30145 100644
--- a/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
+++ b/subprojects/groovy-macro/src/main/groovy/org/codehaus/groovy/macro/matcher/MatchingConstraints.groovy
@@ -27,7 +27,7 @@ import org.codehaus.groovy.syntax.Token
  * Represents constraints in AST pattern matching.
  *
  * @author Cedric Champeau
- * @since 2.4.0
+ * @since 2.5.0
  */
 @CompileStatic
 @Immutable(knownImmutableClasses = [ConstraintPredicate])


[03/37] incubator-groovy git commit: new groovy-macro subproject with code from MacroGroovy (initial contribution)

Posted by cc...@apache.org.
new groovy-macro subproject with code from MacroGroovy (initial contribution)


Project: http://git-wip-us.apache.org/repos/asf/incubator-groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-groovy/commit/20560359
Tree: http://git-wip-us.apache.org/repos/asf/incubator-groovy/tree/20560359
Diff: http://git-wip-us.apache.org/repos/asf/incubator-groovy/diff/20560359

Branch: refs/heads/master
Commit: 205603597f13606c356c18940546f6dc3f87a7e0
Parents: 6d277a0
Author: Sergey Egorov <bs...@gmail.com>
Authored: Thu Jul 3 00:46:13 2014 +0300
Committer: Sergei Egorov <bs...@gmail.com>
Committed: Mon Sep 28 14:32:04 2015 +0300

----------------------------------------------------------------------
 .../groovy/macro/runtime/MacroBuilder.java      |  16 +-
 .../macro/runtime/MacroGroovyMethods.java       |   9 -
 .../macro/transform/MacroInvocationTrap.java    | 175 ++++++++++++-------
 .../macro/transform/MacroTransformation.java    |  41 ++++-
 .../test/groovy/groovy/SimpleMacroTest.groovy   |  45 +----
 5 files changed, 155 insertions(+), 131 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/20560359/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
index ae82081..2c66f3e 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroBuilder.java
@@ -39,26 +39,14 @@ import java.util.Map;
 public enum MacroBuilder {
     INSTANCE;
 
-    public <T> T macro(String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(false, source, context, resultClass);
-    }
-
-    public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(CompilePhase.CONVERSION, asIs, source, context, resultClass);
-    }
-
-    public <T> T macro(CompilePhase compilePhase, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
-        return macro(compilePhase, false, source, context, resultClass);
-    }
-
     @SuppressWarnings("unchecked")
-    public <T> T macro(CompilePhase compilePhase, boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
+    public <T> T macro(boolean asIs, String source, final Map<MacroSubstitutionKey, Closure<Expression>> context, Class<T> resultClass) {
         final String label = "__synthesized__label__" + System.currentTimeMillis() + "__:";
         final String labelledSource = label + source;
         final int linesOffset = 1;
         final int columnsOffset = label.length() + 1; // +1 because of {
         
-        List<ASTNode> nodes = (new AstBuilder()).buildFromString(compilePhase, true, labelledSource);
+        List<ASTNode> nodes = (new AstBuilder()).buildFromString(CompilePhase.CONVERSION, true, labelledSource);
 
         for(ASTNode node : nodes) {
             if (node instanceof BlockStatement) {

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/20560359/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
index 5c41c04..578a11f 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/runtime/MacroGroovyMethods.java
@@ -17,7 +17,6 @@ package org.codehaus.groovy.macro.runtime;
 
 import groovy.lang.Closure;
 import groovy.lang.DelegatesTo;
-import org.codehaus.groovy.control.CompilePhase;
 
 /**
  *
@@ -39,12 +38,4 @@ public class MacroGroovyMethods {
     public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
         return null;
     }
-
-    public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
-
-    public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
-        return null;
-    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/20560359/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
index 127fb4b..7ac10df 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroInvocationTrap.java
@@ -15,15 +15,18 @@
  */
 package org.codehaus.groovy.macro.transform;
 
+import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.ast.CodeVisitorSupport;
-import org.codehaus.groovy.ast.MethodInvocationTrap;
 import org.codehaus.groovy.ast.expr.*;
 import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.tools.ClosureUtils;
 import org.codehaus.groovy.control.SourceUnit;
 import org.codehaus.groovy.control.io.ReaderSource;
+import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
 import org.codehaus.groovy.macro.runtime.MacroBuilder;
 import org.codehaus.groovy.macro.runtime.MacroSubstitutionKey;
+import org.codehaus.groovy.syntax.SyntaxException;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -34,107 +37,122 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.THIS_EXPRESSION;
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
-public class MacroInvocationTrap extends MethodInvocationTrap {
+public class MacroInvocationTrap {
+
+    private final ReaderSource source;
+    private final SourceUnit sourceUnit;
+
+    /**
+     * Creates the trap and captures all macro method calls.
+     *
+     * @param source         the reader source that contains source for the SourceUnit
+     * @param sourceUnit     the source unit being compiled. Used for error messages.
+     */
+    MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
+        if (source == null) throw new IllegalArgumentException("Null: source");
+        if (sourceUnit == null) throw new IllegalArgumentException("Null: sourceUnit");
+        this.source = source;
+        this.sourceUnit = sourceUnit;
+    }
 
-    public MacroInvocationTrap(ReaderSource source, SourceUnit sourceUnit) {
-        super(source, sourceUnit);
+    /**
+     * Reports an error back to the source unit.
+     *
+     * @param msg  the error message
+     * @param expr the expression that caused the error message.
+     */
+    private void addError(String msg, ASTNode expr) {
+        sourceUnit.getErrorCollector().addErrorAndContinue(
+                new SyntaxErrorMessage(new SyntaxException(msg + '\n', expr.getLineNumber(), expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()), sourceUnit)
+        );
     }
 
-    @Override
-    protected boolean handleTargetMethodCallExpression(MethodCallExpression macroCall) {
-        final ClosureExpression closureExpression = getClosureArgument(macroCall);
+    /**
+     * Attempts to find 'macro' invocations. When found, converts them into calls
+     * to the 'from string' approach.
+     *
+     * @param macroCall the method call expression that may or may not be a 'macro' invocation.
+     */
+    public void visitMethodCallExpression(final MethodCallExpression macroCall) {
 
+        if (!isBuildInvocation(macroCall, MacroTransformation.MACRO_METHOD)) {
+            return;
+        }
+
+        final ClosureExpression closureExpression = getClosureArgument(macroCall);
+        
         if(closureExpression == null) {
-            return true;
+            return;
         }
 
         if(closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
             addError("Macro closure arguments are not allowed", closureExpression);
-            return true;
         }
-
+        
         final MapExpression mapExpression = new MapExpression();
-
+        
         (new CodeVisitorSupport() {
             @Override
             public void visitMethodCallExpression(MethodCallExpression call) {
                 super.visitMethodCallExpression(call);
-
+                
                 if(isBuildInvocation(call, MacroTransformation.DOLLAR_VALUE)) {
                     ClosureExpression substitutionClosureExpression = getClosureArgument(call);
-
+                    
                     if(substitutionClosureExpression == null) {
                         return;
                     }
 
                     MacroSubstitutionKey key = new MacroSubstitutionKey(call, closureExpression.getLineNumber(), closureExpression.getColumnNumber());
-
+                    
                     mapExpression.addMapEntryExpression(key.toConstructorCallExpression(), substitutionClosureExpression);
                 }
             }
         }).visitClosureExpression(closureExpression);
-
-        String source = convertClosureToSource(closureExpression);
+        
+        String source = convertClosureToSource(this.source, closureExpression);
 
         BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();
-
+        
         Boolean asIs = false;
-
+        
         TupleExpression macroArguments = getMacroArguments(macroCall);
-
+        
         if(macroArguments == null) {
-            return true;
+            return;
         }
 
         List<Expression> macroArgumentsExpressions = macroArguments.getExpressions();
-
-        if(macroArgumentsExpressions.size() == 2 || macroArgumentsExpressions.size() == 3) {
-            Expression asIsArgumentExpression = macroArgumentsExpressions.get(macroArgumentsExpressions.size() - 2);
-            if((asIsArgumentExpression instanceof ConstantExpression)) {
-                ConstantExpression asIsConstantExpression = (ConstantExpression) asIsArgumentExpression;
-
-                if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
-                    addError("AsIs argument value should be boolean", asIsConstantExpression);
-                    return true;
-                }
-
-                asIs = (Boolean) asIsConstantExpression.getValue();
+        
+        if(macroArgumentsExpressions.size() > 1) {
+            Expression firstArgument = macroArgumentsExpressions.get(0);
+            
+            if(!(firstArgument instanceof ConstantExpression)) {
+                addError("AsIs argument value should be constant(true or false)", firstArgument);
+                return;
+            }
+            
+            ConstantExpression asIsConstantExpression = (ConstantExpression) firstArgument;
+            
+            if(!(asIsConstantExpression.getValue() instanceof Boolean)) {
+                addError("AsIs argument value should be boolean", asIsConstantExpression);
+                return;
             }
-        }
 
-        macroArgumentsExpressions.remove(macroArgumentsExpressions.size() - 1);
+            asIs = (Boolean) asIsConstantExpression.getValue();
+        }
 
-        macroArgumentsExpressions.add(new ConstantExpression(source));
-        macroArgumentsExpressions.add(mapExpression);
-        macroArgumentsExpressions.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
+        List<Expression> otherArgs = new ArrayList<Expression>();
+        otherArgs.add(new ConstantExpression(asIs));
+        otherArgs.add(new ConstantExpression(source));
+        otherArgs.add(mapExpression);
+        otherArgs.add(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)));
 
+        macroCall.setArguments(new ArgumentListExpression(otherArgs));
         macroCall.setObjectExpression(new PropertyExpression(new ClassExpression(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"));
         macroCall.setSpreadSafe(false);
         macroCall.setSafe(false);
         macroCall.setImplicitThis(false);
-        
-        return true;
-    }
-
-    @Override
-    protected boolean isBuildInvocation(MethodCallExpression call) {
-        return isBuildInvocation(call, MacroTransformation.MACRO_METHOD);
-    }
-
-    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
-        if (call == null) throw new IllegalArgumentException("Null: call");
-        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
-
-        if(!(call.getMethod() instanceof ConstantExpression)) {
-            return false;
-        }
-
-        if(!(methodName.equals(call.getMethodAsString()))) {
-            return false;
-        }
-
-        // is method object correct type?
-        return call.getObjectExpression() == THIS_EXPRESSION;
     }
     
     protected TupleExpression getMacroArguments(MethodCallExpression call) {
@@ -175,4 +193,41 @@ public class MacroInvocationTrap extends MethodInvocationTrap {
 
         return (ClosureExpression) result;
     }
+
+    /**
+     * Looks for 'macro' method calls.
+     *
+     * @param call the method call expression, may not be null
+     */
+    public static boolean isBuildInvocation(MethodCallExpression call, String methodName) {
+        if (call == null) throw new IllegalArgumentException("Null: call");
+        if(methodName == null) throw new IllegalArgumentException("Null: methodName");
+        
+        if(!(call.getMethod() instanceof ConstantExpression)) {
+            return false;
+        }
+        
+        if(!(methodName.equals(call.getMethodAsString()))) {
+            return false;
+        }
+
+        // is method object correct type?
+        return call.getObjectExpression() == THIS_EXPRESSION;
+    }
+
+    /**
+     * Converts a ClosureExpression into the String source.
+     *
+     * @param expression a closure
+     * @return the source the closure was created from
+     */
+    private String convertClosureToSource(ReaderSource source, ClosureExpression expression) {
+
+        try {
+            return ClosureUtils.convertClosureToSource(source, expression);
+        } catch (Exception e) {
+            addError(e.getMessage(), expression);
+        }
+        return null;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/20560359/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
index 65284b5..cdf0f07 100644
--- a/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
+++ b/subprojects/groovy-macro/src/main/java/org/codehaus/groovy/macro/transform/MacroTransformation.java
@@ -15,25 +15,56 @@
  */
 package org.codehaus.groovy.macro.transform;
 
-import org.codehaus.groovy.ast.*;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.ModuleNode;
+import org.codehaus.groovy.ast.expr.MethodCallExpression;
 import org.codehaus.groovy.control.CompilePhase;
 import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.transform.ASTTransformation;
 import org.codehaus.groovy.transform.GroovyASTTransformation;
 
 /**
  *
  * @author Sergei Egorov <bs...@gmail.com>
  */
-
 @GroovyASTTransformation(phase = CompilePhase.CONVERSION)
-public class MacroTransformation extends MethodCallTransformation {
+public class MacroTransformation extends ClassCodeVisitorSupport implements ASTTransformation {
 
     public static final String DOLLAR_VALUE = "$v";
     public static final String MACRO_METHOD = "macro";
 
+    SourceUnit source;
+    
+    MacroInvocationTrap transformer;
+
+    public void visit(ASTNode[] nodes, SourceUnit source) {
+        this.source = source;
+
+        transformer = new MacroInvocationTrap(source.getSource(), source);
+
+        for(ASTNode node : nodes) {
+            if(node instanceof ClassNode) {
+                visitClass((ClassNode) node);
+            } else if(node instanceof ModuleNode) {
+                ModuleNode moduleNode = (ModuleNode) node;
+                for (ClassNode classNode : moduleNode.getClasses()) {
+                    visitClass(classNode);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void visitMethodCallExpression(MethodCallExpression call) {
+        transformer.visitMethodCallExpression(call);
+        super.visitMethodCallExpression(call);
+    }
+
     @Override
-    protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, SourceUnit sourceUnit) {
-        return new MacroInvocationTrap(sourceUnit.getSource(), sourceUnit);
+    protected SourceUnit getSourceUnit() {
+        return source;
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-groovy/blob/20560359/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
index 9a29fc3..df46802 100644
--- a/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
+++ b/subprojects/groovy-macro/src/test/groovy/groovy/SimpleMacroTest.groovy
@@ -21,7 +21,6 @@ import org.codehaus.groovy.ast.VariableScope
 import org.codehaus.groovy.ast.builder.AstAssert
 import org.codehaus.groovy.ast.expr.*
 import org.codehaus.groovy.ast.stmt.*
-import org.codehaus.groovy.control.CompilePhase
 
 import static org.codehaus.groovy.ast.expr.VariableExpression.*;
 
@@ -30,10 +29,7 @@ import static org.codehaus.groovy.ast.expr.VariableExpression.*;
  * @author Sergei Egorov <bs...@gmail.com>
  */
 @CompileStatic
-class SimpleMacroTest extends GroovyTestCase {
-    
-    static final String TO_LOWER_CASE_METHOD_NAME = macro { "".toLowerCase() }.getMethodAsString()
-    
+class SimpleMacroTest extends GroovyShellTestCase {
     public void testMethod() {
 
         def someVariable = new VariableExpression("someVariable");
@@ -46,7 +42,7 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
-
+    
     public void testAsIs() {
         def expected = new BlockStatement([
                 new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
@@ -69,12 +65,6 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
-    
-    public void testMethodName() {
-        // Very useful when you don't want to hardcode method or variable names
-        assertEquals("toLowerCase", TO_LOWER_CASE_METHOD_NAME)
-        assertEquals("valueOf", macro { String.valueOf() }.getMethodAsString())
-    }
 
     public void testBlock() {
 
@@ -93,37 +83,6 @@ class SimpleMacroTest extends GroovyTestCase {
 
         assertSyntaxTree(expected, result);
     }
-
-    public void testCompilePhase() {
-
-        def result = macro(CompilePhase.FINALIZATION) {
-            println "foo"
-            println "bar"
-        }
-
-        def expected = new BlockStatement(
-                [
-                        new ExpressionStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo")))),
-                        // In FINALIZATION phase last println will be return statement
-                        new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("bar")))),
-                ] as List<Statement>,
-                new VariableScope()
-        )
-
-        assertSyntaxTree(expected, result);
-    }
-
-    public void testAsIsWithCompilePhase() {
-        def expected = new BlockStatement([
-                new ReturnStatement(new MethodCallExpression(THIS_EXPRESSION, "println", new ArgumentListExpression(new ConstantExpression("foo"))))
-        ] as List<Statement>, new VariableScope());
-
-        def result = macro(CompilePhase.FINALIZATION, true) {
-            println "foo"
-        }
-
-        assertSyntaxTree(expected, result);
-    }
     
     protected void assertSyntaxTree(Object expected, Object result) {
         AstAssert.assertSyntaxTree([expected], [result])