This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch GROOVY_2_5_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_2_5_X by this push:
new a030cc3 minor edits
a030cc3 is described below
commit a030cc3999cacfa1ae3630a966fe01f8a300c1d4
Author: Eric Milles <[email protected]>
AuthorDate: Mon Feb 14 16:39:45 2022 -0600
minor edits
---
.../java/org/codehaus/groovy/ast/ClassNode.java | 2 +-
.../java/org/codehaus/groovy/ast/ModuleNode.java | 6 +-
.../codehaus/groovy/ast/tools/GenericsUtils.java | 10 +-
.../groovy/classgen/AsmClassGenerator.java | 66 ++----
.../org/codehaus/groovy/classgen/EnumVisitor.java | 36 ++-
.../codehaus/groovy/classgen/ExtendedVerifier.java | 53 +++--
.../groovy/classgen/InnerClassVisitor.java | 2 +-
.../org/codehaus/groovy/classgen/ReturnAdder.java | 25 +--
.../org/codehaus/groovy/classgen/Verifier.java | 57 ++---
.../groovy/classgen/asm/InvocationWriter.java | 15 +-
.../classgen/asm/StatementMetaTypeChooser.java | 2 +-
.../groovy/classgen/asm/StatementWriter.java | 19 +-
.../classgen/asm/sc/StaticInvocationWriter.java | 19 +-
.../classgen/asm/sc/StaticTypesCallSiteWriter.java | 63 ++----
.../classgen/asm/sc/StaticTypesClosureWriter.java | 8 +-
.../asm/sc/StaticTypesStatementWriter.java | 2 -
.../codehaus/groovy/control/CompilationUnit.java | 89 +++-----
.../groovy/control/CompilerConfiguration.java | 242 +++++++++------------
.../codehaus/groovy/control/ProcessingUnit.java | 17 --
.../codehaus/groovy/control/ResolveVisitor.java | 29 ++-
.../org/codehaus/groovy/control/SourceUnit.java | 14 +-
.../groovy/control/StaticImportVisitor.java | 1 +
.../groovy/control/messages/LocatedMessage.java | 9 +-
23 files changed, 302 insertions(+), 484 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/ast/ClassNode.java
b/src/main/java/org/codehaus/groovy/ast/ClassNode.java
index dff7f64..dd60b78 100644
--- a/src/main/java/org/codehaus/groovy/ast/ClassNode.java
+++ b/src/main/java/org/codehaus/groovy/ast/ClassNode.java
@@ -786,7 +786,7 @@ public class ClassNode extends AnnotatedNode implements
Opcodes {
if (outer == null) {
return Collections.emptyList();
}
- List<ClassNode> result = new ArrayList<>();
+ List<ClassNode> result = new LinkedList<>();
do {
result.add(outer);
} while ((outer = outer.getOuterClass()) != null);
diff --git a/src/main/java/org/codehaus/groovy/ast/ModuleNode.java
b/src/main/java/org/codehaus/groovy/ast/ModuleNode.java
index 88d16c1..fbfe2e6 100644
--- a/src/main/java/org/codehaus/groovy/ast/ModuleNode.java
+++ b/src/main/java/org/codehaus/groovy/ast/ModuleNode.java
@@ -204,7 +204,7 @@ public class ModuleNode extends ASTNode implements Opcodes {
}
public String getPackageName() {
- return (hasPackage() ? packageNode.getName() : null);
+ return (hasPackage() ? getPackage().getName() : null);
}
public PackageNode getPackage() {
@@ -220,11 +220,11 @@ public class ModuleNode extends ASTNode implements
Opcodes {
}
public boolean hasPackageName() {
- return (packageNode != null && packageNode.getName() != null);
+ return (getPackageName() != null);
}
public boolean hasPackage() {
- return (packageNode != null);
+ return (getPackage() != null);
}
private boolean isPackageInfo() {
diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
index 7bf9c84..0248552 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
@@ -948,22 +948,20 @@ public class GenericsUtils {
}
private static Map<GenericsType, GenericsType>
makePlaceholderAndParameterizedTypeMap(ClassNode declaringClass) {
- if (null == declaringClass) {
+ if (declaringClass == null) {
return Collections.emptyMap();
}
- Map<GenericsType, GenericsType> result = new LinkedHashMap<>();
-
ClassNode redirectDeclaringClass = declaringClass.redirect();
GenericsType[] declaringGenericsTypes =
declaringClass.getGenericsTypes();
GenericsType[] redirectDeclaringGenericsTypes =
redirectDeclaringClass.getGenericsTypes();
- if (null != declaringGenericsTypes && null !=
redirectDeclaringGenericsTypes) {
- for (int i = 0, n = declaringGenericsTypes.length; i < n; i++) {
+ Map<GenericsType, GenericsType> result = new LinkedHashMap<>();
+ if (declaringGenericsTypes != null && redirectDeclaringGenericsTypes
!= null) {
+ for (int i = 0, n = declaringGenericsTypes.length; i < n; i += 1) {
result.put(redirectDeclaringGenericsTypes[i],
declaringGenericsTypes[i]);
}
}
-
return result;
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/AsmClassGenerator.java
b/src/main/java/org/codehaus/groovy/classgen/AsmClassGenerator.java
index 9f8b59e..3a9f58a 100644
--- a/src/main/java/org/codehaus/groovy/classgen/AsmClassGenerator.java
+++ b/src/main/java/org/codehaus/groovy/classgen/AsmClassGenerator.java
@@ -410,41 +410,38 @@ public class AsmClassGenerator extends ClassGenerator {
protected void visitConstructorOrMethod(MethodNode node, boolean
isConstructor) {
controller.resetLineNumber();
- Parameter[] parameters = node.getParameters();
- String methodType =
BytecodeHelper.getMethodDescriptor(node.getReturnType(), parameters);
- String signature = BytecodeHelper.getGenericsMethodSignature(node);
- int modifiers = node.getModifiers();
- if (isVargs(node.getParameters())) modifiers |= Opcodes.ACC_VARARGS;
- MethodVisitor mv = cv.visitMethod(modifiers, node.getName(),
methodType, signature, buildExceptions(node.getExceptions()));
+ Parameter[] parameters = node.getParameters();
+ MethodVisitor mv = cv.visitMethod(
+ node.getModifiers() | (isVargs(parameters) ?
Opcodes.ACC_VARARGS : 0), node.getName(),
+ BytecodeHelper.getMethodDescriptor(node.getReturnType(),
parameters),
+ BytecodeHelper.getGenericsMethodSignature(node),
+ buildExceptions(node.getExceptions()));
controller.setMethodVisitor(mv);
visitAnnotations(node, mv);
- for (int i = 0; i < parameters.length; i++) {
+ int nParameters = parameters.length;
+ for (int i = 0; i < nParameters; i += 1) {
visitParameterAnnotations(parameters[i], i, mv);
}
- // Add parameter names to the MethodVisitor (jdk8+ only)
+ // add parameter names to the MethodVisitor (JDK8+)
if (getCompileUnit().getConfig().getParameters()) {
- for (int i = 0; i < parameters.length; i++) {
- // TODO handle ACC_SYNTHETIC for enum method parameters?
- mv.visitParameter(parameters[i].getName(), 0);
+ for (int i = 0; i < nParameters; i += 1) {
+ mv.visitParameter(parameters[i].getName(),
parameters[i].getModifiers());
}
}
if (controller.getClassNode().isAnnotationDefinition() &&
!node.isStaticConstructor()) {
visitAnnotationDefault(node, mv);
} else if (!node.isAbstract()) {
- Statement code = node.getCode();
mv.visitCode();
-
+ Statement code = node.getCode();
// fast path for getter/setters etc.
if (code instanceof BytecodeSequence &&
((BytecodeSequence)code).getInstructions().size() == 1 &&
((BytecodeSequence)code).getInstructions().get(0) instanceof
BytecodeInstruction) {
((BytecodeInstruction)((BytecodeSequence)code).getInstructions().get(0)).visit(mv);
} else {
visitStdMethod(node, isConstructor, parameters, code);
}
- // we use this NOP to have a valid jump target for the various
labels
- //mv.visitInsn(NOP);
try {
mv.visitMaxs(0, 0);
} catch (Exception e) {
@@ -476,30 +473,27 @@ public class AsmClassGenerator extends ClassGenerator {
controller.getCallSiteWriter().makeSiteEntry();
MethodVisitor mv = controller.getMethodVisitor();
- final ClassNode superClass = controller.getClassNode().getSuperClass();
if (isConstructor && (code == null || !((ConstructorNode)
node).firstStatementIsSpecialConstructorCall())) {
boolean hasCallToSuper = false;
- if (code!=null && controller.getClassNode() instanceof
InnerClassNode) {
- // if the class not is an inner class node, there are chances
that the call to super is already added
- // so we must ensure not to add it twice (see GROOVY-4471)
- if (code instanceof BlockStatement) {
- for (Statement statement : ((BlockStatement)
code).getStatements()) {
- if (statement instanceof ExpressionStatement) {
- final Expression expression =
((ExpressionStatement) statement).getExpression();
- if (expression instanceof
ConstructorCallExpression) {
- ConstructorCallExpression call =
(ConstructorCallExpression) expression;
- if (call.isSuperCall()) {
- hasCallToSuper = true;
- break;
- }
+ // GROOVY-4471: do not add super ctor call twice for inner class
+ if (code instanceof BlockStatement &&
controller.getClassNode().getOuterClass() != null) {
+ for (Statement statement : ((BlockStatement)
code).getStatements()) {
+ if (statement instanceof ExpressionStatement) {
+ Expression expression = ((ExpressionStatement)
statement).getExpression();
+ if (expression instanceof ConstructorCallExpression) {
+ ConstructorCallExpression call =
(ConstructorCallExpression) expression;
+ if (call.isSuperCall()) {
+ hasCallToSuper = true;
+ break;
}
}
}
}
}
if (!hasCallToSuper) {
- // invokes the super class constructor
+ // add call to "super()"
mv.visitVarInsn(ALOAD, 0);
+ ClassNode superClass =
controller.getClassNode().getSuperClass();
mv.visitMethodInsn(INVOKESPECIAL,
BytecodeHelper.getClassInternalName(superClass), "<init>", "()V", false);
}
}
@@ -849,11 +843,6 @@ public class AsmClassGenerator extends ClassGenerator {
controller.getUnaryExpressionHelper().writeNotExpression(expression);
}
- /**
- * return a primitive boolean value of the BooleanExpression.
- *
- * @param expression
- */
public void visitBooleanExpression(BooleanExpression expression) {
controller.getCompileStack().pushBooleanExpression();
int mark = controller.getOperandStack().getStackLength();
@@ -1030,11 +1019,6 @@ public class AsmClassGenerator extends ClassGenerator {
MethodVisitor mv = controller.getMethodVisitor();
Expression objectExpression = expression.getObjectExpression();
- //TODO (blackdrag): this if branch needs a rework. There should be no
direct method calls be produced, the
- // handling of this/super could be much simplified (see
visitAttributeExpression), the field accessibility check
- // could be moved directly into the search, which would also no longer
require the GroovyBugError then
- // the outer class field access seems to be without any tests (if
there are tests for that, then the code
- // here is dead code)
if (isThisOrSuper(objectExpression)) {
// let's use the field expression if it's available
String name = expression.getPropertyAsString();
@@ -1799,11 +1783,9 @@ public class AsmClassGenerator extends ClassGenerator {
List<Expression> expressions = expression.getExpressions();
final int size = expressions.size();
// init declarations
-// LinkedList<DeclarationExpression> declarations = new
LinkedList<DeclarationExpression>();
for (int i = 0; i < size; i++) {
Expression expr = expressions.get(i);
if (expr instanceof DeclarationExpression) {
-// declarations.add((DeclarationExpression) expr);
DeclarationExpression de = (DeclarationExpression) expr;
BinaryExpression be = new BinaryExpression(
de.getLeftExpression(),
diff --git a/src/main/java/org/codehaus/groovy/classgen/EnumVisitor.java
b/src/main/java/org/codehaus/groovy/classgen/EnumVisitor.java
index cdf900b..b26fe45 100644
--- a/src/main/java/org/codehaus/groovy/classgen/EnumVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/EnumVisitor.java
@@ -53,7 +53,6 @@ import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
@@ -62,6 +61,7 @@ import org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.List;
+import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod;
import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX;
public class EnumVisitor extends ClassCodeVisitorSupport {
@@ -73,7 +73,6 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
private final SourceUnit sourceUnit;
-
public EnumVisitor(CompilationUnit cu, SourceUnit su) {
sourceUnit = su;
}
@@ -89,13 +88,13 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
private void completeEnum(ClassNode enumClass) {
boolean isAic = isAnonymousInnerClass(enumClass);
- // create MIN_VALUE and MAX_VALUE fields
+ // create MIN_VALUE, MAX_VALUE and $VALUES fields
FieldNode minValue = null, maxValue = null, values = null;
if (!isAic) {
ClassNode enumRef = enumClass.getPlainNodeReference();
-
- // create values field
+ minValue = new FieldNode("MIN_VALUE", PUBLIC_FS, enumRef,
enumClass, null);
+ maxValue = new FieldNode("MAX_VALUE", PUBLIC_FS, enumRef,
enumClass, null);
values = new FieldNode("$VALUES", PRIVATE_FS |
Opcodes.ACC_SYNTHETIC, enumRef.makeArray(), enumClass, null);
values.setSynthetic(true);
@@ -110,10 +109,6 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
addMethods(enumClass, values);
checkForAbstractMethods(enumClass);
-
- // create MIN_VALUE and MAX_VALUE fields
- minValue = new FieldNode("MIN_VALUE", PUBLIC_FS, enumRef,
enumClass, null);
- maxValue = new FieldNode("MAX_VALUE", PUBLIC_FS, enumRef,
enumClass, null);
}
addInit(enumClass, minValue, maxValue, values, isAic);
}
@@ -151,7 +146,7 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
cloneCall.setMethodTarget(values.getType().getMethod("clone",
Parameter.EMPTY_ARRAY));
code.addStatement(new ReturnStatement(cloneCall));
valuesMethod.setCode(code);
- enumClass.addMethod(valuesMethod);
+ addGeneratedMethod(enumClass, valuesMethod);
}
if (!hasNext) {
@@ -163,7 +158,7 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
// }
Token assign = Token.newSymbol(Types.ASSIGN, -1, -1);
Token ge = Token.newSymbol(Types.COMPARE_GREATER_THAN_EQUAL, -1,
-1);
- MethodNode nextMethod = new MethodNode("next", Opcodes.ACC_PUBLIC
| Opcodes.ACC_SYNTHETIC, enumRef, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY,
null);
+ MethodNode nextMethod = new MethodNode("next", Opcodes.ACC_PUBLIC,
enumRef, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
nextMethod.setSynthetic(true);
BlockStatement code = new BlockStatement();
BlockStatement ifStatement = new BlockStatement();
@@ -210,7 +205,7 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
)
);
nextMethod.setCode(code);
- enumClass.addMethod(nextMethod);
+ addGeneratedMethod(enumClass, nextMethod);
}
if (!hasPrevious) {
@@ -222,8 +217,8 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
// }
Token assign = Token.newSymbol(Types.ASSIGN, -1, -1);
Token lt = Token.newSymbol(Types.COMPARE_LESS_THAN, -1, -1);
- MethodNode nextMethod = new MethodNode("previous",
Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, enumRef, Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY, null);
- nextMethod.setSynthetic(true);
+ MethodNode prevMethod = new MethodNode("previous",
Opcodes.ACC_PUBLIC, enumRef, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY,
null);
+ prevMethod.setSynthetic(true);
BlockStatement code = new BlockStatement();
BlockStatement ifStatement = new BlockStatement();
ifStatement.addStatement(
@@ -274,8 +269,8 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
new MethodCallExpression(new
FieldExpression(values), "getAt", new VariableExpression("ordinal"))
)
);
- nextMethod.setCode(code);
- enumClass.addMethod(nextMethod);
+ prevMethod.setCode(code);
+ addGeneratedMethod(enumClass, prevMethod);
}
{
@@ -325,7 +320,7 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
BlockStatement code = new BlockStatement();
code.addStatement(new ReturnStatement(cce));
initMethod.setCode(code);
- enumClass.addMethod(initMethod);
+ addGeneratedMethod(enumClass, initMethod);
// static init
List<FieldNode> fields = enumClass.getFields();
@@ -440,11 +435,8 @@ public class EnumVisitor extends ClassCodeVisitorSupport {
enumClass.addStaticInitializerStatements(block, true);
}
- private void addError(AnnotatedNode exp, String msg) {
- sourceUnit.getErrorCollector().addErrorAndContinue(
- new SyntaxErrorMessage(
- new SyntaxException(msg + '\n', exp.getLineNumber(),
exp.getColumnNumber(), exp.getLastLineNumber(), exp.getLastColumnNumber()),
sourceUnit)
- );
+ private void addError(AnnotatedNode node, String msg) {
+ sourceUnit.addErrorAndContinue(new SyntaxException(msg + '\n', node));
}
static boolean isAnonymousInnerClass(ClassNode enumClass) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
index 58a5bc3..e3e5bda 100644
--- a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
@@ -43,7 +43,6 @@ import org.codehaus.groovy.control.AnnotationConstantsVisitor;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.ErrorCollector;
import org.codehaus.groovy.control.SourceUnit;
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.syntax.SyntaxException;
import org.objectweb.asm.Opcodes;
@@ -51,14 +50,14 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
+import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import static org.codehaus.groovy.ast.tools.GenericsUtils.createGenericsSpec;
import static
org.codehaus.groovy.ast.tools.GenericsUtils.correctToGenericsSpec;
import static
org.codehaus.groovy.ast.tools.GenericsUtils.correctToGenericsSpecRecurse;
-import static org.codehaus.groovy.ast.tools.GenericsUtils.createGenericsSpec;
/**
* A specialized Groovy AST visitor meant to perform additional verifications
upon the
@@ -77,6 +76,7 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport
{
this.source = sourceUnit;
}
+ @Override
public void visitClass(ClassNode node) {
AnnotationConstantsVisitor acv = new AnnotationConstantsVisitor();
acv.visitClass(node, this.source);
@@ -93,6 +93,7 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport
{
node.visitContents(this);
}
+ @Override
public void visitField(FieldNode node) {
visitAnnotations(node, AnnotationNode.FIELD_TARGET);
}
@@ -102,25 +103,26 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
visitAnnotations(expression, AnnotationNode.LOCAL_VARIABLE_TARGET);
}
+ @Override
public void visitConstructor(ConstructorNode node) {
visitConstructorOrMethod(node, AnnotationNode.CONSTRUCTOR_TARGET);
}
+ @Override
public void visitMethod(MethodNode node) {
visitConstructorOrMethod(node, AnnotationNode.METHOD_TARGET);
}
private void visitConstructorOrMethod(MethodNode node, int methodTarget) {
visitAnnotations(node, methodTarget);
- for (int i = 0; i < node.getParameters().length; i++) {
- Parameter parameter = node.getParameters()[i];
+ for (Parameter parameter : node.getParameters()) {
visitAnnotations(parameter, AnnotationNode.PARAMETER_TARGET);
}
if (this.currentClass.isAnnotationDefinition() &&
!node.isStaticConstructor()) {
ErrorCollector errorCollector = new
ErrorCollector(this.source.getConfiguration());
AnnotationVisitor visitor = new AnnotationVisitor(this.source,
errorCollector);
- visitor.setReportClass(currentClass);
+ visitor.setReportClass(this.currentClass);
visitor.checkReturnType(node.getReturnType(), node);
if (node.getParameters().length > 0) {
addError("Annotation members may not have parameters.",
node.getParameters()[0]);
@@ -131,7 +133,7 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
ReturnStatement code = (ReturnStatement) node.getCode();
if (code != null) {
visitor.visitExpression(node.getName(), code.getExpression(),
node.getReturnType());
- visitor.checkCircularReference(currentClass,
node.getReturnType(), code.getExpression());
+ visitor.checkCircularReference(this.currentClass,
node.getReturnType(), code.getExpression());
}
this.source.getErrorCollector().addCollectorContents(errorCollector);
}
@@ -139,9 +141,9 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
if (code != null) {
code.visit(this);
}
-
}
+ @Override
public void visitProperty(PropertyNode node) {
}
@@ -275,7 +277,7 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
ClassNode next = cNode;
outer:
while (next != null) {
- Map genericsSpec = createGenericsSpec(next);
+ Map<String, ClassNode> genericsSpec = createGenericsSpec(next);
MethodNode mn = correctToGenericsSpec(genericsSpec, method);
if (next != cNode) {
ClassNode correctedNext =
correctToGenericsSpecRecurse(genericsSpec, next);
@@ -283,20 +285,19 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
if (found != null) break;
}
List<ClassNode> ifaces = new
ArrayList<ClassNode>(Arrays.asList(next.getInterfaces()));
- Map updatedGenericsSpec = new HashMap(genericsSpec);
while (!ifaces.isEmpty()) {
ClassNode origInterface = ifaces.remove(0);
if (!origInterface.equals(ClassHelper.OBJECT_TYPE)) {
- updatedGenericsSpec = createGenericsSpec(origInterface,
updatedGenericsSpec);
- ClassNode iNode =
correctToGenericsSpecRecurse(updatedGenericsSpec, origInterface);
- MethodNode found2 =
getDeclaredMethodCorrected(updatedGenericsSpec, mn, iNode);
+ genericsSpec = createGenericsSpec(origInterface,
genericsSpec);
+ ClassNode iNode =
correctToGenericsSpecRecurse(genericsSpec, origInterface);
+ MethodNode found2 =
getDeclaredMethodCorrected(genericsSpec, mn, iNode);
if (found2 != null) break outer;
- ifaces.addAll(Arrays.asList(iNode.getInterfaces()));
+ Collections.addAll(ifaces, iNode.getInterfaces());
}
}
ClassNode superClass = next.getUnresolvedSuperClass();
if (superClass != null) {
- next = correctToGenericsSpecRecurse(updatedGenericsSpec,
superClass);
+ next = correctToGenericsSpecRecurse(genericsSpec, superClass);
} else {
next = null;
}
@@ -305,10 +306,10 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
}
private static MethodNode getDeclaredMethodCorrected(Map genericsSpec,
MethodNode mn, ClassNode correctedNext) {
- for (MethodNode orig : correctedNext.getDeclaredMethods(mn.getName()))
{
- MethodNode method = correctToGenericsSpec(genericsSpec, orig);
- if (ParameterUtils.parametersEqual(method.getParameters(),
mn.getParameters())) {
- return method;
+ for (MethodNode declared :
correctedNext.getDeclaredMethods(mn.getName())) {
+ MethodNode corrected = correctToGenericsSpec(genericsSpec,
declared);
+ if (ParameterUtils.parametersEqual(corrected.getParameters(),
mn.getParameters())) {
+ return corrected;
}
}
return null;
@@ -337,20 +338,16 @@ public class ExtendedVerifier extends
ClassCodeVisitorSupport {
return
CompilerConfiguration.isPostJDK5(this.source.getConfiguration().getTargetBytecode());
}
- public void addError(String msg, ASTNode expr) {
- this.source.getErrorCollector().addErrorAndContinue(
- new SyntaxErrorMessage(
- new SyntaxException(msg + '\n', expr.getLineNumber(),
expr.getColumnNumber(), expr.getLastLineNumber(), expr.getLastColumnNumber()),
this.source)
- );
+ public void addError(String msg, ASTNode node) {
+ getSourceUnit().addErrorAndContinue(new SyntaxException(msg + '\n',
node));
}
@Override
protected SourceUnit getSourceUnit() {
- return source;
+ return this.source;
}
- // TODO use it or lose it
+ @Deprecated
public void visitGenericType(GenericsType genericsType) {
-
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/codehaus/groovy/classgen/InnerClassVisitor.java
b/src/main/java/org/codehaus/groovy/classgen/InnerClassVisitor.java
index 635f236..1a8900a 100644
--- a/src/main/java/org/codehaus/groovy/classgen/InnerClassVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/InnerClassVisitor.java
@@ -224,7 +224,7 @@ public class InnerClassVisitor extends
InnerClassVisitorHelper implements Opcode
innerClass.addConstructor(ACC_SYNTHETIC,
parameters.toArray(Parameter.EMPTY_ARRAY), ClassNode.EMPTY_ARRAY, block);
}
- private boolean isStatic(InnerClassNode innerClass, VariableScope scope,
final ConstructorCallExpression call) {
+ private boolean isStatic(final ClassNode innerClass, final VariableScope
scope, final ConstructorCallExpression call) {
boolean isStatic = innerClass.isStaticClass();
if (!isStatic) {
if (currentMethod != null) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/ReturnAdder.java
b/src/main/java/org/codehaus/groovy/classgen/ReturnAdder.java
index 4efe9fc..628d0bd 100644
--- a/src/main/java/org/codehaus/groovy/classgen/ReturnAdder.java
+++ b/src/main/java/org/codehaus/groovy/classgen/ReturnAdder.java
@@ -198,27 +198,22 @@ public class ReturnAdder {
if (statement instanceof BlockStatement) {
BlockStatement block = (BlockStatement) statement;
-
- final List list = block.getStatements();
- if (!list.isEmpty()) {
- int idx = list.size() - 1;
- Statement last = addReturnsIfNeeded((Statement) list.get(idx),
block.getVariableScope());
+ if (block.isEmpty()) {
+ ReturnStatement returnStatement = new
ReturnStatement(ConstantExpression.NULL);
+ returnStatement.setSourcePosition(block);
+ listener.returnStatementAdded(returnStatement);
+ return returnStatement;
+ } else {
+ List<Statement> list = block.getStatements(); int idx =
list.size() - 1;
+ Statement last = addReturnsIfNeeded(list.get(idx),
block.getVariableScope());
if (doAdd) list.set(idx, last);
if (!statementReturns(last)) {
- final ReturnStatement returnStatement = new
ReturnStatement(ConstantExpression.NULL);
+ ReturnStatement returnStatement = new
ReturnStatement(ConstantExpression.NULL);
listener.returnStatementAdded(returnStatement);
if (doAdd) list.add(returnStatement);
}
- } else {
- ReturnStatement ret = new
ReturnStatement(ConstantExpression.NULL);
- ret.setSourcePosition(block);
- listener.returnStatementAdded(ret);
- return ret;
+ return block;
}
-
- BlockStatement newBlock = new BlockStatement(list,
block.getVariableScope());
- newBlock.setSourcePosition(block);
- return newBlock;
}
if (statement == null) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
index 14e6e19..f82ffff 100644
--- a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
@@ -72,7 +72,7 @@ import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -209,8 +209,8 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
public void visitClass(final ClassNode node) {
this.classNode = node;
- if (Traits.isTrait(node) // maybe possible to have this true in joint
compilation mode
- || classNode.isInterface()) {
+ if (classNode.isInterface()
+ || Traits.isTrait(node)) { // maybe possible to have this true
in joint compilation mode
//interfaces have no constructors, but this code expects one,
//so create a dummy and don't add it to the class node
ConstructorNode dummy = new ConstructorNode(0, null);
@@ -281,7 +281,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
@Override
public void variableNotAlwaysInitialized(final VariableExpression
var) {
- if (Modifier.isFinal(var.getAccessedVariable().getModifiers()))
+ if (isFinal(var.getAccessedVariable().getModifiers()))
throw new RuntimeParserException("The variable [" +
var.getName() + "] may be uninitialized", var);
}
};
@@ -341,10 +341,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
protected void addDefaultConstructor(ClassNode node) {
if (!node.getDeclaredConstructors().isEmpty()) return;
- BlockStatement empty = new BlockStatement();
- empty.setSourcePosition(node);
- ConstructorNode constructor = new ConstructorNode(ACC_PUBLIC, empty);
- constructor.setSourcePosition(node);
+ ConstructorNode constructor = new ConstructorNode(ACC_PUBLIC, new
BlockStatement());
constructor.setHasNoRealSourcePosition(true);
node.addConstructor(constructor);
markAsGenerated(node, constructor);
@@ -401,7 +398,6 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL,
"org/codehaus/groovy/reflection/ClassInfo", "getMetaClass",
"()Lgroovy/lang/MetaClass;", false);
mv.visitInsn(ARETURN);
-
}
})
);
@@ -429,7 +425,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
/*
* the code is:
* if (this.metaClass==null) {
- * this.metaClass = this.$getStaticMetaClass
+ * this.metaClass = this.$getStaticMetaClass()
* return this.metaClass
* } else {
* return this.metaClass
@@ -721,8 +717,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
if (getterBlock == null) {
MethodNode getter = classNode.getGetterMethod(getterName,
!node.isStatic());
if (getter == null && ClassHelper.boolean_TYPE == node.getType()) {
- String secondGetterName = "is" + capitalize(name);
- getter = classNode.getGetterMethod(secondGetterName);
+ getter = classNode.getGetterMethod("is" + capitalize(name));
}
if (!node.isPrivate() && methodNeedsReplacement(getter)) {
getterBlock = createGetterBlock(node, field);
@@ -740,14 +735,13 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
int getterModifiers = accessorModifiers;
// don't make static accessors final
if (node.isStatic()) {
- getterModifiers = ~Modifier.FINAL & getterModifiers;
+ getterModifiers &= ~ACC_FINAL;
}
if (getterBlock != null) {
visitGetter(node, getterBlock, getterModifiers, getterName);
- if (ClassHelper.boolean_TYPE == node.getType() ||
ClassHelper.Boolean_TYPE == node.getType()) {
- String secondGetterName = "is" + capitalize(name);
- visitGetter(node, getterBlock, getterModifiers,
secondGetterName);
+ if (ClassHelper.boolean_TYPE == node.getType() ||
ClassHelper.Boolean_TYPE.equals(node.getType())) {
+ visitGetter(node, getterBlock, getterModifiers, "is" +
capitalize(name));
}
}
if (setterBlock != null) {
@@ -760,12 +754,12 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
}
}
- private void visitGetter(PropertyNode node, Statement getterBlock, int
getterModifiers, String secondGetterName) {
- MethodNode secondGetter =
- new MethodNode(secondGetterName, getterModifiers,
node.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock);
- secondGetter.setSynthetic(true);
- addPropertyMethod(secondGetter);
- visitMethod(secondGetter);
+ private void visitGetter(PropertyNode node, Statement getterBlock, int
getterModifiers, String getterName) {
+ MethodNode getter =
+ new MethodNode(getterName, getterModifiers, node.getType(),
Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock);
+ getter.setSynthetic(true);
+ addPropertyMethod(getter);
+ visitMethod(getter);
}
protected void addPropertyMethod(MethodNode method) {
@@ -876,7 +870,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
}
addPropertyMethod(newMethod);
newMethod.setGenericsTypes(method.getGenericsTypes());
- newMethod.putNodeMetaData(DEFAULT_PARAMETER_GENERATED, true);
+ newMethod.putNodeMetaData(DEFAULT_PARAMETER_GENERATED,
Boolean.TRUE);
}
});
}
@@ -1083,12 +1077,10 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
} else {
statements.addAll(node.getObjectInitializerStatements());
}
-
BlockStatement newBlock = new BlockStatement(statements,
block.getVariableScope());
newBlock.setSourcePosition(block);
constructorNode.setCode(newBlock);
-
if (!staticStatements.isEmpty()) {
if (isEnum) {
/*
@@ -1362,7 +1354,6 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
storeMissingCovariantMethods(declaredMethods, methodsToAdd,
genericsSpec, interfacesMethods);
addCovariantMethods(anInterface, declaredMethods, abstractMethods,
methodsToAdd, genericsSpec);
}
-
}
private void storeMissingCovariantMethods(List declaredMethods, Map
methodsToAdd, Map genericsSpec, List<MethodNode> methodNodeList) {
@@ -1381,11 +1372,10 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
if (oldMethod.isPrivate()) return null;
// parameters
- boolean normalEqualParameters =
equalParametersNormal(overridingMethod, oldMethod);
- boolean genericEqualParameters =
equalParametersWithGenerics(overridingMethod, oldMethod, genericsSpec);
- if (!normalEqualParameters && !genericEqualParameters) return null;
+ boolean equalParameters = equalParametersNormal(overridingMethod,
oldMethod);
+ if (!equalParameters && !equalParametersWithGenerics(overridingMethod,
oldMethod, genericsSpec)) return null;
- //correct to method level generics for the overriding method
+ // correct to method level generics for the overriding method
genericsSpec = GenericsUtils.addMethodGenerics(overridingMethod,
genericsSpec);
// return type
@@ -1405,7 +1395,7 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
sourceOf(overridingMethod));
}
- if (equalReturnType && normalEqualParameters) return null;
+ if (equalReturnType && equalParameters) return null;
if ((oldMethod.getModifiers() & ACC_FINAL) != 0) {
throw new RuntimeParserException(
@@ -1426,12 +1416,12 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
boolean oldM =
ClassHelper.isPrimitiveType(oldMethod.getReturnType());
boolean newM =
ClassHelper.isPrimitiveType(overridingMethod.getReturnType());
if (oldM || newM) {
- String message = "";
+ String message;
if (oldM && newM) {
message = " with old and new method having different
primitive return types";
} else if (newM) {
message = " with new method having a primitive return type
and old method not";
- } else /* oldM */ {
+ } else /*oldM*/ {
message = " with old method having a primitive return type
and new method not";
}
throw new RuntimeParserException(
@@ -1658,5 +1648,4 @@ public class Verifier implements GroovyClassVisitor,
Opcodes {
}
}
}
-
}
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
index 4fc5732..62ed3cd 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
@@ -68,7 +68,6 @@ 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;
@@ -476,9 +475,6 @@ public class InvocationWriter {
public void visitDoWhileLoop(DoWhileStatement statement) {
}
- public void visitEmptyStatement(EmptyStatement statement) {
- }
-
@Override
public void visitExpressionStatement(ExpressionStatement
statement) {
}
@@ -952,17 +948,14 @@ public class InvocationWriter {
private static List<ConstructorNode>
sortConstructors(ConstructorCallExpression call, ClassNode callNode) {
// sort in a new list to prevent side effects
- List<ConstructorNode> constructors = new
ArrayList<ConstructorNode>(callNode.getDeclaredConstructors());
- Comparator comp = new Comparator() {
- public int compare(Object arg0, Object arg1) {
- ConstructorNode c0 = (ConstructorNode) arg0;
- ConstructorNode c1 = (ConstructorNode) arg1;
+ List<ConstructorNode> constructors = new
ArrayList<>(callNode.getDeclaredConstructors());
+ Collections.sort(constructors, new Comparator<ConstructorNode>() {
+ public int compare(ConstructorNode c0, ConstructorNode c1) {
String descriptor0 =
BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c0.getParameters());
String descriptor1 =
BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c1.getParameters());
return descriptor0.compareTo(descriptor1);
}
- };
- Collections.sort(constructors, comp);
+ });
return constructors;
}
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/StatementMetaTypeChooser.java
b/src/main/java/org/codehaus/groovy/classgen/asm/StatementMetaTypeChooser.java
index c02b4f3..3a74151 100644
---
a/src/main/java/org/codehaus/groovy/classgen/asm/StatementMetaTypeChooser.java
+++
b/src/main/java/org/codehaus/groovy/classgen/asm/StatementMetaTypeChooser.java
@@ -50,6 +50,6 @@ public class StatementMetaTypeChooser implements TypeChooser {
} else {
type = exp.getType();
}
- return type.redirect();
+ return type;
}
}
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
index d8b9182..500eeb0 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
@@ -65,15 +65,14 @@ import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.RETURN;
public class StatementWriter {
- // iterator
- private static final MethodCaller iteratorNextMethod =
MethodCaller.newInterface(Iterator.class, "next");
- private static final MethodCaller iteratorHasNextMethod =
MethodCaller.newInterface(Iterator.class, "hasNext");
- private final WriterController controller;
+ private static final MethodCaller iteratorHasNextMethod =
MethodCaller.newInterface(Iterator.class, "hasNext");
+ private static final MethodCaller iteratorNextMethod =
MethodCaller.newInterface(Iterator.class, "next");
public StatementWriter(WriterController controller) {
this.controller = controller;
}
+ private final WriterController controller;
protected void writeStatementLabel(Statement statement) {
String name = statement.getStatementLabel();
@@ -89,19 +88,15 @@ public class StatementWriter {
int mark = controller.getOperandStack().getStackLength();
CompileStack compileStack = controller.getCompileStack();
compileStack.pushVariableScope(block.getVariableScope());
- List<Statement> statementList = block.getStatements();
- for (Statement statement : statementList) {
+ for (Statement statement : block.getStatements()) {
statement.visit(controller.getAcg());
}
compileStack.pop();
- // GROOVY-7647
- if (block.getLastLineNumber() > 0
- && !isMethodOrConstructorNonEmptyBlock(block) // GROOVY-9126
- ) {
+ // GROOVY-7647, GROOVY-9126
+ if (block.getLastLineNumber() > 0 &&
!isMethodOrConstructorNonEmptyBlock(block)) {
MethodVisitor mv = controller.getMethodVisitor();
- Label blockEnd = new Label();
- mv.visitLabel(blockEnd);
+ Label blockEnd = new Label(); mv.visitLabel(blockEnd);
mv.visitLineNumber(block.getLastLineNumber(), blockEnd);
}
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
index a677315..1650c4d 100644
---
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
+++
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
@@ -312,8 +312,9 @@ public class StaticInvocationWriter extends
InvocationWriter {
String owner =
BytecodeHelper.getClassInternalName(node.getDeclaringClass());
String desc =
BytecodeHelper.getMethodDescriptor(target.getReturnType(), parameters);
mv.visitMethodInsn(INVOKESTATIC, owner, methodName, desc, false);
- ClassNode ret = target.getReturnType().redirect();
- if (ret == ClassHelper.VOID_TYPE) {
+
+ ClassNode ret = target.getReturnType();
+ if (ClassHelper.VOID_TYPE.equals(ret)){
ret = ClassHelper.OBJECT_TYPE;
mv.visitInsn(ACONST_NULL);
}
@@ -445,13 +446,13 @@ public class StaticInvocationWriter extends
InvocationWriter {
int argumentListSize = argumentList.size();
ClassNode lastArgType = argumentListSize > 0 ?
typeChooser.resolveType(argumentList.get(argumentListSize -1),
controller.getClassNode()):null;
- if (lastParaType.isArray()
- && ((argumentListSize > para.length)
- || ((argumentListSize == (para.length - 1)) &&
!lastParaType.equals(lastArgType))
- || ((argumentListSize == para.length && lastArgType!=null &&
!lastArgType.isArray())
- &&
(StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(lastArgType,lastParaType.getComponentType())))
- || ClassHelper.GSTRING_TYPE.equals(lastArgType) &&
ClassHelper.STRING_TYPE.equals(lastParaType.getComponentType()))
- ) {
+ if (lastParaType.isArray() && (
+ argumentListSize > para.length
+ || (argumentListSize == (para.length - 1) &&
!lastParaType.equals(lastArgType))
+ || (argumentListSize == para.length && lastArgType != null &&
!lastArgType.isArray()
+ &&
(StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(lastArgType,
lastParaType.getComponentType())
+ || ClassHelper.GSTRING_TYPE.equals(lastArgType) &&
ClassHelper.STRING_TYPE.equals(lastParaType.getComponentType())))
+ )) {
int stackLen = operandStack.getStackLength() + argumentListSize;
MethodVisitor mv = controller.getMethodVisitor();
controller.setMethodVisitor(mv);
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
index ffec796..472f9d6 100644
---
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
+++
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
@@ -18,6 +18,7 @@
*/
package org.codehaus.groovy.classgen.asm.sc;
+import org.apache.groovy.ast.tools.ClassNodeUtils;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassHelper;
@@ -368,11 +369,10 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
controller.getCompileStack().removeVar(var);
}
- @SuppressWarnings("unchecked")
private boolean makeGetPrivateFieldWithBridgeMethod(final Expression
receiver, final ClassNode receiverType, final String fieldName, final boolean
safe, final boolean implicitThis) {
FieldNode field = receiverType.getField(fieldName);
ClassNode outerClass = receiverType.getOuterClass();
- if (field==null && implicitThis && outerClass !=null &&
!receiverType.isStaticClass()) {
+ if (field == null && implicitThis && outerClass != null &&
!receiverType.isStaticClass()) {
Expression pexp;
if (controller.isInClosure()) {
MethodCallExpression mce = new MethodCallExpression(
@@ -396,15 +396,14 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
return makeGetPrivateFieldWithBridgeMethod(pexp, outerClass,
fieldName, safe, true);
}
ClassNode classNode = controller.getClassNode();
- if (field!=null && Modifier.isPrivate(field.getModifiers())
- &&
(StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(receiverType,
classNode) ||
StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(classNode,receiverType))
- && !receiverType.equals(classNode)) {
+ if (field != null && Modifier.isPrivate(field.getModifiers()) &&
!receiverType.equals(classNode)
+ &&
(StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(receiverType,
classNode) ||
StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(classNode,receiverType)))
{
Map<String, MethodNode> accessors =
receiverType.redirect().getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_FIELDS_ACCESSORS);
if (accessors!=null) {
MethodNode methodNode = accessors.get(fieldName);
if (methodNode!=null) {
MethodCallExpression mce = new
MethodCallExpression(receiver, methodNode.getName(),
- new ArgumentListExpression(field.isStatic()?new
ConstantExpression(null):receiver));
+ new ArgumentListExpression(field.isStatic() ? new
ConstantExpression(null) : receiver));
mce.setMethodTarget(methodNode);
mce.setSafe(safe);
mce.setImplicitThis(implicitThis);
@@ -463,23 +462,21 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
}
private boolean makeGetPropertyWithGetter(final Expression receiver, final
ClassNode receiverType, final String methodName, final boolean safe, final
boolean implicitThis) {
- // does a getter exists ?
String getterName = "get" + MetaClassHelper.capitalize(methodName);
MethodNode getterNode = receiverType.getGetterMethod(getterName);
- if (getterNode==null) {
+ if (getterNode == null) {
getterName = "is" + MetaClassHelper.capitalize(methodName);
getterNode = receiverType.getGetterMethod(getterName);
}
- if (getterNode!=null && receiver instanceof ClassExpression &&
!CLASS_Type.equals(receiverType) && !getterNode.isStatic()) {
+ if (getterNode != null && receiver instanceof ClassExpression &&
!CLASS_Type.equals(receiverType) && !getterNode.isStatic()) {
return false;
}
- // GROOVY-5561: if two files are compiled in the same source unit
- // and that one references the other, the getters for properties have
not been
+ // GROOVY-5561: if two files are compiled in the same source unit and
+ // one references the other, the getters for properties have not been
// generated by the compiler yet (generated by the Verifier)
PropertyNode propertyNode = receiverType.getProperty(methodName);
if (getterNode == null && propertyNode != null) {
- // it is possible to use a getter
String prefix = "get";
if (boolean_TYPE.equals(propertyNode.getOriginType())) {
prefix = "is";
@@ -487,15 +484,14 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
getterName = prefix + MetaClassHelper.capitalize(methodName);
getterNode = new MethodNode(
getterName,
- ACC_PUBLIC,
+ ACC_PUBLIC | (propertyNode.isStatic() ? ACC_STATIC : 0),
propertyNode.getOriginType(),
Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY,
EmptyStatement.INSTANCE);
getterNode.setDeclaringClass(receiverType);
- if (propertyNode.isStatic()) getterNode.setModifiers(ACC_PUBLIC +
ACC_STATIC);
}
- if (getterNode!=null) {
+ if (getterNode != null) {
MethodCallExpression call = new MethodCallExpression(
receiver,
getterName,
@@ -515,7 +511,7 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
}
}
- // check direct interfaces (GROOVY-7149)
+ // GROOVY-7149: check direct interfaces
for (ClassNode node : receiverType.getInterfaces()) {
if (makeGetPropertyWithGetter(receiver, node, methodName, safe,
implicitThis)) {
return true;
@@ -523,7 +519,7 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
}
// go upper level
ClassNode superClass = receiverType.getSuperClass();
- if (superClass !=null) {
+ if (superClass != null) {
return makeGetPropertyWithGetter(receiver, superClass, methodName,
safe, implicitThis);
}
@@ -531,7 +527,7 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
}
boolean makeGetField(final Expression receiver, final ClassNode
receiverType, final String fieldName, final boolean safe, final boolean
implicitThis) {
- FieldNode field = receiverType.getField(fieldName);
+ final FieldNode field = ClassNodeUtils.getField(receiverType,
fieldName); // GROOVY-7039, GROOVY-9791
if (field != null &&
AsmClassGenerator.isFieldDirectlyAccessible(field, controller.getClassNode())) {
CompileStack compileStack = controller.getCompileStack();
MethodVisitor mv = controller.getMethodVisitor();
@@ -572,18 +568,6 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
operandStack.replace(replacementType);
return true;
}
-
- for (ClassNode intf : receiverType.getInterfaces()) {
- // GROOVY-7039
- if (intf != receiverType && makeGetField(receiver, intf,
fieldName, safe, implicitThis)) {
- return true;
- }
- }
-
- ClassNode superClass = receiverType.getSuperClass();
- if (superClass != null) {
- return makeGetField(receiver, superClass, fieldName, safe,
implicitThis);
- }
return false;
}
@@ -608,13 +592,12 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
rType = receiver.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
if (receiver instanceof VariableExpression && rType == null) {
Variable variable = ((VariableExpression)
receiver).getAccessedVariable();
- ASTNode node = (ASTNode) variable;
- rType = node.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
+ rType = ((ASTNode)
variable).getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
}
- if (rType!=null && trySubscript(receiver, message, arguments, rType,
aType)) {
+ if (rType != null && trySubscript(receiver, message, arguments, rType,
aType)) {
return;
}
- // todo: more cases
+ // TODO: more cases
throw new GroovyBugError(
"At line " + receiver.getLineNumber() + " column " +
receiver.getColumnNumber() + "\n" +
"On receiver: " + receiver.getText() + " with message: " +
message + " and arguments: " + arguments.getText() + "\n" +
@@ -747,7 +730,7 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
int m2 = operandStack.getStackLength();
// array access
controller.getMethodVisitor().visitInsn(AALOAD);
- operandStack.replace(rType.getComponentType(), m2-m1);
+ operandStack.replace(rType.getComponentType(), m2 - m1);
}
private void writeOperatorCall(Expression receiver, Expression arguments,
String operator) {
@@ -763,7 +746,7 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
private void writePowerCall(Expression receiver, Expression arguments,
final ClassNode rType, ClassNode aType) {
OperandStack operandStack = controller.getOperandStack();
int m1 = operandStack.getStackLength();
- //slow Path
+ // slow path
prepareSiteAndReceiver(receiver, "power", false,
controller.getCompileStack().isLHS());
operandStack.doGroovyCast(getWrapper(rType));
visitBoxedArgument(arguments);
@@ -785,22 +768,22 @@ public class StaticTypesCallSiteWriter extends
CallSiteWriter implements Opcodes
}
private void writeStringPlusCall(final Expression receiver, final String
message, final Expression arguments) {
- // todo: performance would be better if we created a StringBuilder
+ // TODO: performance would be better if we created a StringBuilder
OperandStack operandStack = controller.getOperandStack();
int m1 = operandStack.getStackLength();
- //slow Path
+ // slow path
prepareSiteAndReceiver(receiver, message, false,
controller.getCompileStack().isLHS());
visitBoxedArgument(arguments);
int m2 = operandStack.getStackLength();
MethodVisitor mv = controller.getMethodVisitor();
mv.visitMethodInsn(INVOKESTATIC,
"org/codehaus/groovy/runtime/DefaultGroovyMethods", "plus",
"(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;", false);
- controller.getOperandStack().replace(STRING_TYPE, m2-m1);
+ controller.getOperandStack().replace(STRING_TYPE, m2 - m1);
}
private void writeNumberNumberCall(final Expression receiver, final String
message, final Expression arguments) {
OperandStack operandStack = controller.getOperandStack();
int m1 = operandStack.getStackLength();
- //slow Path
+ // slow path
prepareSiteAndReceiver(receiver, message, false,
controller.getCompileStack().isLHS());
controller.getOperandStack().doGroovyCast(Number_TYPE);
visitBoxedArgument(arguments);
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java
index e10c8c9..6dd546c 100644
---
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java
+++
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java
@@ -92,15 +92,15 @@ public class StaticTypesClosureWriter extends ClosureWriter
{
}
private static void addGeneratedCallMethod(ClassNode closureClass,
MethodNode doCallMethod, Expression expression, Parameter[] params) {
- MethodCallExpression doCallarg = callX(varX("this", closureClass),
"doCall", args(expression));
- doCallarg.setImplicitThis(true);
- doCallarg.setMethodTarget(doCallMethod);
+ MethodCallExpression doCallCall = callX(varX("this", closureClass),
"doCall", args(expression));
+ doCallCall.setImplicitThis(true);
+ doCallCall.setMethodTarget(doCallMethod);
MethodNode call = new MethodNode("call",
Opcodes.ACC_PUBLIC,
ClassHelper.OBJECT_TYPE,
params,
ClassNode.EMPTY_ARRAY,
- returnS(doCallarg));
+ returnS(doCallCall));
addGeneratedMethod(closureClass, call, true);
}
diff --git
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesStatementWriter.java
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesStatementWriter.java
index e1295a4..540f9b4 100644
---
a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesStatementWriter.java
+++
b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesStatementWriter.java
@@ -292,7 +292,5 @@ public class StaticTypesStatementWriter extends
StatementWriter {
mv.visitJumpInsn(GOTO, continueLabel);
mv.visitLabel(breakLabel);
-
}
-
}
diff --git a/src/main/java/org/codehaus/groovy/control/CompilationUnit.java
b/src/main/java/org/codehaus/groovy/control/CompilationUnit.java
index b02c6b6..54c77d1 100644
--- a/src/main/java/org/codehaus/groovy/control/CompilationUnit.java
+++ b/src/main/java/org/codehaus/groovy/control/CompilationUnit.java
@@ -22,7 +22,6 @@ import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyRuntimeException;
import groovy.transform.CompilationUnitAware;
import org.codehaus.groovy.GroovyBugError;
-import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.CompileUnit;
@@ -75,7 +74,6 @@ import java.util.Map;
* You can also add PhaseOperations to this compilation using the
addPhaseOperation method.
* This is commonly used when you want to wire a new AST Transformation into
the compilation.
*/
-
public class CompilationUnit extends ProcessingUnit {
//---------------------------------------------------------------------------
@@ -84,11 +82,11 @@ public class CompilationUnit extends ProcessingUnit {
protected ASTTransformationsContext astTransformationsContext; // AST
transformations state data
@Deprecated
- protected Map summariesBySourceName; // Summary of each SourceUnit
+ protected Map summariesBySourceName = new HashMap();
@Deprecated
- protected Map summariesByPublicClassName; // Summary of each
SourceUnit
+ protected Map summariesByPublicClassName = new HashMap();
@Deprecated
- protected Map classSourcesByPublicClassName; // Summary of each Class
+ protected Map classSourcesByPublicClassName = new HashMap();
protected Map<String, SourceUnit> sources; // The SourceUnits from
which this unit is built
protected List<String> names; // Names for each SourceUnit in sources.
@@ -119,7 +117,6 @@ public class CompilationUnit extends ProcessingUnit {
this(null, null, null);
}
-
/**
* Initializes the CompilationUnit with defaults except for class loader.
*/
@@ -127,7 +124,6 @@ public class CompilationUnit extends ProcessingUnit {
this(null, null, loader);
}
-
/**
* Initializes the CompilationUnit with no security considerations.
*/
@@ -160,29 +156,24 @@ public class CompilationUnit extends ProcessingUnit {
GroovyClassLoader loader, GroovyClassLoader
transformLoader) {
super(configuration, loader, null);
+ this.ast = new CompileUnit(this.classLoader, security,
this.configuration);
this.astTransformationsContext = new ASTTransformationsContext(this,
transformLoader);
- this.names = new ArrayList<String>();
- this.queuedSources = new LinkedList<SourceUnit>();
- this.sources = new HashMap<String, SourceUnit>();
- this.summariesBySourceName = new HashMap();
- this.summariesByPublicClassName = new HashMap();
- this.classSourcesByPublicClassName = new HashMap();
- this.ast = new CompileUnit(this.classLoader, security,
this.configuration);
- this.generatedClasses = new ArrayList<GroovyClass>();
+ this.names = new ArrayList<>();
+ this.sources = new HashMap<>();
+ this.queuedSources = new LinkedList<>();
+ this.generatedClasses = new ArrayList<>();
this.verifier = new Verifier();
+ this.optimizer = new OptimizerVisitor(this);
this.resolveVisitor = new ResolveVisitor(this);
this.staticImportVisitor = new StaticImportVisitor();
- this.optimizer = new OptimizerVisitor(this);
initPhaseOperations();
addPhaseOperations();
applyCompilationCustomizers(configuration);
-
- this.classgenCallback = null;
- this.classNodeResolver = new ClassNodeResolver();
+ setClassNodeResolver(new ClassNodeResolver());
}
private void initPhaseOperations() {
@@ -299,13 +290,13 @@ public class CompilationUnit extends ProcessingUnit {
/**
* Returns the class loader for loading AST transformations.
- * @return - the transform class loader
*/
public GroovyClassLoader getTransformLoader() {
- return astTransformationsContext.getTransformLoader() == null ?
getClassLoader() : astTransformationsContext.getTransformLoader();
+ GroovyClassLoader loader =
astTransformationsContext.getTransformLoader();
+ if (loader == null) loader = this.getClassLoader();
+ return loader;
}
-
public void addPhaseOperation(SourceUnitOperation op, int phase) {
validatePhase(phase);
phaseOperations[phase].add(op);
@@ -390,7 +381,7 @@ public class CompilationUnit extends ProcessingUnit {
* Convenience routine to get the named ClassNode.
*/
public ClassNode getClassNode(final String name) {
- final ClassNode[] result = new ClassNode[]{null};
+ final ClassNode[] result = new ClassNode[1];
PrimaryClassNodeOperation handler = new PrimaryClassNodeOperation() {
public void call(SourceUnit source, GeneratorContext context,
ClassNode classNode) {
if (classNode.getName().equals(name)) {
@@ -417,7 +408,6 @@ public class CompilationUnit extends ProcessingUnit {
//---------------------------------------------------------------------------
// SOURCE CREATION
-
/**
* Adds a set of file paths to the unit.
*/
@@ -427,7 +417,6 @@ public class CompilationUnit extends ProcessingUnit {
}
}
-
/**
* Adds a set of source files to the unit.
*/
@@ -437,7 +426,6 @@ public class CompilationUnit extends ProcessingUnit {
}
}
-
/**
* Adds a source file to the unit.
*/
@@ -452,7 +440,6 @@ public class CompilationUnit extends ProcessingUnit {
return addSource(new SourceUnit(url, configuration, classLoader,
getErrorCollector()));
}
-
/**
* Adds a InputStream source to the unit.
*/
@@ -478,7 +465,6 @@ public class CompilationUnit extends ProcessingUnit {
return source;
}
-
/**
* Returns an iterator on the unit's SourceUnits.
*/
@@ -501,7 +487,6 @@ public class CompilationUnit extends ProcessingUnit {
};
}
-
/**
* Adds a ClassNode directly to the unit (ie. without source).
* WARNING: the source is needed for error reporting, using
@@ -517,7 +502,6 @@ public class CompilationUnit extends ProcessingUnit {
//---------------------------------------------------------------------------
// EXTERNAL CALLBACKS
-
/**
* A callback interface you can use to "accompany" the classgen()
* code as it traverses the ClassNode tree. You will be called-back
@@ -536,6 +520,10 @@ public class CompilationUnit extends ProcessingUnit {
this.classgenCallback = visitor;
}
+ public ClassgenCallback getClassgenCallback() {
+ return classgenCallback;
+ }
+
/**
* A callback interface you can use to get a callback after every
* unit of the compile process. You will be called-back with a
@@ -543,7 +531,6 @@ public class CompilationUnit extends ProcessingUnit {
* before running compile() to set your callback.
*/
public abstract static class ProgressCallback {
-
public abstract void call(ProcessingUnit context, int phase) throws
CompilationFailedException;
}
@@ -555,10 +542,6 @@ public class CompilationUnit extends ProcessingUnit {
this.progressCallback = callback;
}
- public ClassgenCallback getClassgenCallback() {
- return classgenCallback;
- }
-
public ProgressCallback getProgressCallback() {
return progressCallback;
}
@@ -566,7 +549,6 @@ public class CompilationUnit extends ProcessingUnit {
//---------------------------------------------------------------------------
// ACTIONS
-
/**
* Synonym for compile(Phases.ALL).
*/
@@ -632,7 +614,6 @@ public class CompilationUnit extends ProcessingUnit {
recordPhaseOpsInAllOtherPhases(currPhase);
currentPhaseNewOps = newPhaseOperations[currPhase];
}
-
}
private void doPhaseOperation(Object operation) {
@@ -661,7 +642,6 @@ public class CompilationUnit extends ProcessingUnit {
}
}
-
/**
* Dequeues any source units add through addSource and resets the compiler
phase
* to initialization.
@@ -790,7 +770,6 @@ public class CompilationUnit extends ProcessingUnit {
}
};
-
/**
* Runs classgen() on a single ClassNode.
*/
@@ -799,8 +778,7 @@ public class CompilationUnit extends ProcessingUnit {
return true;
}
- public void call(final SourceUnit source, GeneratorContext context,
ClassNode classNode) throws CompilationFailedException {
-
+ public void call(final SourceUnit source, final GeneratorContext
context, final ClassNode classNode) throws CompilationFailedException {
optimizer.visitClass(classNode, source); // GROOVY-4272:
repositioned it here from staticImport
//
@@ -838,14 +816,12 @@ public class CompilationUnit extends ProcessingUnit {
// Prep the generator machinery
//
ClassVisitor classVisitor = createClassVisitor();
-
+
String sourceName = (source == null ?
classNode.getModule().getDescription() : source.getName());
// only show the file name and its extension like javac does in
its stacktraces rather than the full path
// also takes care of both \ and / depending on the host compiling
environment
if (sourceName != null)
sourceName =
sourceName.substring(Math.max(sourceName.lastIndexOf('\\'),
sourceName.lastIndexOf('/')) + 1);
- //TraceClassVisitor tracer = new TraceClassVisitor(visitor, new
PrintWriter(System.err,true));
- //AsmClassGenerator generator = new AsmClassGenerator(source,
context, tracer, sourceName);
AsmClassGenerator generator = new AsmClassGenerator(source,
context, classVisitor, sourceName);
//
@@ -859,16 +835,16 @@ public class CompilationUnit extends ProcessingUnit {
//
// Handle any callback that's been set
//
- if (CompilationUnit.this.classgenCallback != null) {
+ if (classgenCallback != null) {
classgenCallback.call(classVisitor, classNode);
}
//
// Recurse for inner classes
//
- LinkedList innerClasses = generator.getInnerClasses();
+ LinkedList<ClassNode> innerClasses = generator.getInnerClasses();
while (!innerClasses.isEmpty()) {
- classgen.call(source, context, (ClassNode)
innerClasses.removeFirst());
+ classgen.call(source, context, innerClasses.removeFirst());
}
}
};
@@ -876,8 +852,7 @@ public class CompilationUnit extends ProcessingUnit {
protected ClassVisitor createClassVisitor() {
CompilerConfiguration config = getConfiguration();
int computeMaxStackAndFrames = ClassWriter.COMPUTE_MAXS;
- if (CompilerConfiguration.isPostJDK7(config.getTargetBytecode())
- ||
Boolean.TRUE.equals(config.getOptimizationOptions().get("indy"))) {
+ if (CompilerConfiguration.isPostJDK7(config.getTargetBytecode()) ||
config.isIndyEnabled()) {
computeMaxStackAndFrames += ClassWriter.COMPUTE_FRAMES;
}
return new ClassWriter(computeMaxStackAndFrames) {
@@ -905,14 +880,13 @@ public class CompilationUnit extends ProcessingUnit {
}
@Override
protected String getCommonSuperClass(String arg1, String arg2) {
- ClassNode a = getClassNode(arg1.replace('/', '.'));
+ ClassNode a = getClassNode(arg1.replace('/', '.'));
ClassNode b = getClassNode(arg2.replace('/', '.'));
return getCommonSuperClassNode(a,b).getName().replace('.','/');
}
-
};
}
-
+
//---------------------------------------------------------------------------
// PHASE HANDLING
@@ -923,7 +897,6 @@ public class CompilationUnit extends ProcessingUnit {
applyToSourceUnits(mark);
}
-
/**
* Marks a single SourceUnit with the current phase,
* if it isn't already there yet.
@@ -943,7 +916,6 @@ public class CompilationUnit extends ProcessingUnit {
//---------------------------------------------------------------------------
// LOOP SIMPLIFICATION FOR SourceUnit OPERATIONS
-
/**
* An callback interface for use in the applyToSourceUnits loop driver.
*/
@@ -951,7 +923,6 @@ public class CompilationUnit extends ProcessingUnit {
public abstract void call(SourceUnit source) throws
CompilationFailedException;
}
-
/**
* A loop driver for applying operations to all SourceUnits.
* Automatically skips units that have already been processed
@@ -976,14 +947,12 @@ public class CompilationUnit extends ProcessingUnit {
}
}
-
getErrorCollector().failIfErrors();
}
//---------------------------------------------------------------------------
// LOOP SIMPLIFICATION FOR PRIMARY ClassNode OPERATIONS
-
/**
* An callback interface for use in the applyToPrimaryClassNodes loop
driver.
*/
@@ -1086,7 +1055,7 @@ public class CompilationUnit extends ProcessingUnit {
} catch (CompilationFailedException e) {
// fall through, getErrorReporter().failIfErrors() will trigger
} catch (NullPointerException npe) {
- GroovyBugError gbe = new GroovyBugError("unexpected
NullpointerException", npe);
+ GroovyBugError gbe = new GroovyBugError("unexpected
NullPointerException", npe);
changeBugText(gbe, context);
throw gbe;
} catch (GroovyBugError e) {
@@ -1149,14 +1118,12 @@ public class CompilationUnit extends ProcessingUnit {
private void changeBugText(GroovyBugError e, SourceUnit context) {
e.setBugText("exception in phase '" + getPhaseDescription() + "' in
source unit '" + ((context != null) ? context.getName() : "?") + "' " +
e.getBugText());
}
-
+
public ClassNodeResolver getClassNodeResolver() {
return classNodeResolver;
}
-
public void setClassNodeResolver(ClassNodeResolver classNodeResolver) {
this.classNodeResolver = classNodeResolver;
}
-
}
diff --git
a/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
b/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
index b649f17..4e2db2c 100644
--- a/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
+++ b/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java
@@ -38,6 +38,7 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
+import static org.apache.groovy.util.SystemUtil.getBooleanSafe;
import static org.apache.groovy.util.SystemUtil.getSystemPropertySafe;
import static org.codehaus.groovy.runtime.StringGroovyMethods.isAtLeast;
@@ -46,7 +47,7 @@ import static
org.codehaus.groovy.runtime.StringGroovyMethods.isAtLeast;
*/
public class CompilerConfiguration {
- /** This (<code>"indy"</code>) is the Optimization Option value for
enabling <code>invokedynamic</code> compilation. */
+ /** Optimization Option for enabling <code>invokedynamic</code>
compilation. */
public static final String INVOKEDYNAMIC = "indy";
/** This (<code>"1.4"</code>) is the value for targetBytecode to compile
for a JDK 1.4. */
@@ -79,7 +80,7 @@ public class CompilerConfiguration {
* @deprecated
*/
@Deprecated
- public static final String POST_JDK5 = JDK5; // for backwards compatibility
+ public static final String POST_JDK5 = JDK5;
/**
* This constant is for comparing targetBytecode to ensure it is set to an
earlier value than JDK 1.5.
@@ -89,15 +90,15 @@ public class CompilerConfiguration {
public static final String PRE_JDK5 = JDK4;
/**
- * JDK version to bytecode version mapping
+ * JDK version to bytecode version mapping.
*/
public static final Map<String, Integer> JDK_TO_BYTECODE_VERSION_MAP =
Maps.of(
- JDK4, Opcodes.V1_4,
- JDK5, Opcodes.V1_5,
- JDK6, Opcodes.V1_6,
- JDK7, Opcodes.V1_7,
- JDK8, Opcodes.V1_8,
- JDK9, Opcodes.V9,
+ JDK4, Opcodes.V1_4,
+ JDK5, Opcodes.V1_5,
+ JDK6, Opcodes.V1_6,
+ JDK7, Opcodes.V1_7,
+ JDK8, Opcodes.V1_8,
+ JDK9, Opcodes.V9,
JDK10, Opcodes.V10,
JDK11, Opcodes.V11,
JDK12, Opcodes.V12,
@@ -106,17 +107,14 @@ public class CompilerConfiguration {
JDK15, Opcodes.V15
);
- private static final String[] EMPTY_STRING_ARRAY = new String[0];
+ /** The valid targetBytecode values. */
+ public static final String[] ALLOWED_JDKS =
JDK_TO_BYTECODE_VERSION_MAP.keySet().toArray(new
String[JDK_TO_BYTECODE_VERSION_MAP.size()]);
- /** An array of the valid targetBytecode values */
- public static final String[] ALLOWED_JDKS =
JDK_TO_BYTECODE_VERSION_MAP.keySet().toArray(EMPTY_STRING_ARRAY);
+ public static final int ASM_API_VERSION = Opcodes.ASM8;
@Deprecated
- public static final String CURRENT_JVM_VERSION = getMinBytecodeVersion();
+ public static final String CURRENT_JVM_VERSION = JDK7;
- /**
- * The default source encoding
- */
public static final String DEFAULT_SOURCE_ENCODING = "UTF-8";
/**
@@ -138,11 +136,15 @@ public class CompilerConfiguration {
@Override
public Set<String> getDisabledGlobalASTTransformations() {
- return Collections.emptySet();
+ Set<String> defaults = super.getDisabledGlobalASTTransformations();
+ if (defaults != null) return Collections.unmodifiableSet(defaults);
+ return null;
}
@Override
public Map<String, Object> getJointCompilationOptions() {
+ Map<String, Object> defaults = super.getJointCompilationOptions();
+ if (defaults != null) return Collections.unmodifiableMap(defaults);
return null;
}
@@ -300,7 +302,7 @@ public class CompilerConfiguration {
/**
* Classpath for use during compilation
*/
- private LinkedList<String> classpath;
+ private List<String> classpath;
/**
* If true, the compiler should produce action information
@@ -315,7 +317,7 @@ public class CompilerConfiguration {
/**
* If true, generates metadata for reflection on method parameters
*/
- private boolean parameters = false;
+ private boolean parameters;
/**
* The number of non-fatal errors to allow before bailing
@@ -337,7 +339,7 @@ public class CompilerConfiguration {
/**
* extensions used to find a groovy files
*/
- private Set<String> scriptExtensions = new LinkedHashSet<String>();
+ private Set<String> scriptExtensions = new LinkedHashSet<>();
/**
* if set to true recompilation is enabled
@@ -369,7 +371,7 @@ public class CompilerConfiguration {
*/
private Map<String, Boolean> optimizationOptions;
- private final List<CompilationCustomizer> compilationCustomizers = new
LinkedList<CompilationCustomizer>();
+ private final List<CompilationCustomizer> compilationCustomizers = new
LinkedList<>();
/**
* Global AST transformations which should not be loaded even if they are
@@ -380,8 +382,6 @@ public class CompilerConfiguration {
private BytecodeProcessor bytecodePostprocessor;
- public static final int ASM_API_VERSION = Opcodes.ASM8;
-
/**
* Sets the compiler flags/settings to default values.
*
@@ -395,7 +395,6 @@ public class CompilerConfiguration {
* <tr><td><code>groovy.target.directory</code></td><td>{@link
#getTargetDirectory}</td></tr>
* <tr><td><code>groovy.parameters</code></td><td>{@link
#getParameters()}</td></tr>
* <tr><td><code>groovy.preview.features</code></td><td>{@link
#isPreviewFeatures}</td></tr>
- * <tr><td><code>groovy.script.base</code></td><td>{@link
#getScriptBaseClass}</td></tr>
* <tr><td><code>groovy.default.scriptExtension</code></td><td>{@link
#getDefaultScriptExtension}</td></tr>
* </table>
* </blockquote>
@@ -410,38 +409,22 @@ public class CompilerConfiguration {
* </blockquote>
*/
public CompilerConfiguration() {
- // Set in safe defaults
- warningLevel = WarningMessage.LIKELY_ERRORS;
- classpath = new LinkedList<String>();
- parameters = getSystemPropertySafe("groovy.parameters") != null;
+ classpath = new LinkedList<>();
+
tolerance = 10;
minimumRecompilationInterval = 100;
-
-
setTargetBytecodeIfValid(getSystemPropertySafe("groovy.target.bytecode",
getMinBytecodeVersion()));
-
- previewFeatures = getSystemPropertySafe("groovy.preview.features") !=
null;
- defaultScriptExtension =
getSystemPropertySafe("groovy.default.scriptExtension", ".groovy");
-
- // Source file encoding
- String encoding = getSystemPropertySafe("file.encoding",
DEFAULT_SOURCE_ENCODING);
- encoding = getSystemPropertySafe("groovy.source.encoding", encoding);
- setSourceEncodingOrDefault(encoding);
-
+ warningLevel = WarningMessage.LIKELY_ERRORS;
+ parameters = getBooleanSafe("groovy.parameters");
+ previewFeatures = getBooleanSafe("groovy.preview.features");
+ sourceEncoding = getSystemPropertySafe("groovy.source.encoding",
+ getSystemPropertySafe("file.encoding", DEFAULT_SOURCE_ENCODING));
setTargetDirectorySafe(getSystemPropertySafe("groovy.target.directory"));
+
setTargetBytecodeIfValid(getSystemPropertySafe("groovy.target.bytecode", JDK7));
+ defaultScriptExtension =
getSystemPropertySafe("groovy.default.scriptExtension", ".groovy");
optimizationOptions = new HashMap<>(4);
- handleOptimizationOption(optimizationOptions, INVOKEDYNAMIC,
"groovy.target.indy");
- }
-
- private void handleOptimizationOption(Map<String, Boolean> options, String
optionName, String sysOptionName) {
- String propValue = getSystemPropertySafe(sysOptionName);
- boolean optionEnabled = propValue == null
- ? (DEFAULT == null ? false :
Boolean.TRUE.equals(DEFAULT.getOptimizationOptions().get(optionName)))
- : Boolean.valueOf(propValue);
-
- if (optionEnabled) {
- options.put(optionName, Boolean.TRUE);
- }
+ if (getBooleanSafe("groovy.target.indy"))
+ optimizationOptions.put(INVOKEDYNAMIC, Boolean.TRUE);
}
/**
@@ -460,10 +443,10 @@ public class CompilerConfiguration {
*
* @param configuration The configuration to copy.
*/
- public CompilerConfiguration(CompilerConfiguration configuration) {
+ public CompilerConfiguration(final CompilerConfiguration configuration) {
setWarningLevel(configuration.getWarningLevel());
setTargetDirectory(configuration.getTargetDirectory());
- setClasspathList(new LinkedList<String>(configuration.getClasspath()));
+ setClasspathList(new LinkedList<>(configuration.getClasspath()));
setVerbose(configuration.getVerbose());
setDebug(configuration.getDebug());
setParameters(configuration.getParameters());
@@ -479,13 +462,11 @@ public class CompilerConfiguration {
if (jointCompilationOptions != null) {
jointCompilationOptions = new HashMap<String,
Object>(jointCompilationOptions);
}
- // TODO GROOVY-9585: add line below once gradle build issues fixed
-//
compilationCustomizers.addAll(configuration.getCompilationCustomizers());
setJointCompilationOptions(jointCompilationOptions);
setPluginFactory(configuration.getPluginFactory());
setDisabledGlobalASTTransformations(configuration.getDisabledGlobalASTTransformations());
- setScriptExtensions(new
LinkedHashSet<String>(configuration.getScriptExtensions()));
- setOptimizationOptions(new HashMap<String,
Boolean>(configuration.getOptimizationOptions()));
+ setScriptExtensions(new
LinkedHashSet<>(configuration.getScriptExtensions()));
+ setOptimizationOptions(new
HashMap<>(configuration.getOptimizationOptions()));
setBytecodePostprocessor(configuration.getBytecodePostprocessor());
}
@@ -540,7 +521,7 @@ public class CompilerConfiguration {
*
* @param configuration The properties to get flag values from.
*/
- public CompilerConfiguration(Properties configuration) throws
ConfigurationException {
+ public CompilerConfiguration(final Properties configuration) throws
ConfigurationException {
this();
configure(configuration);
}
@@ -590,7 +571,7 @@ public class CompilerConfiguration {
* For a list of available properties look at {@link
#CompilerConfiguration(Properties)}.
* @param configuration The properties to get flag values from.
*/
- public void configure(Properties configuration) throws
ConfigurationException {
+ public void configure(final Properties configuration) throws
ConfigurationException {
String text;
int numeric;
@@ -674,7 +655,7 @@ public class CompilerConfiguration {
text =
configuration.getProperty("groovy.disabled.global.ast.transformations");
if (text != null) {
String[] classNames = text.split(",\\s*}");
- Set<String> disabledTransforms = new
HashSet<String>(Arrays.asList(classNames));
+ Set<String> disabledTransforms = new
HashSet<>(Arrays.asList(classNames));
setDisabledGlobalASTTransformations(disabledTransforms);
}
}
@@ -690,11 +671,10 @@ public class CompilerConfiguration {
/**
* Sets the warning level. See {@link WarningMessage} for level details.
*/
- public void setWarningLevel(int level) {
+ public void setWarningLevel(final int level) {
if (level < WarningMessage.NONE || level > WarningMessage.PARANOIA) {
this.warningLevel = WarningMessage.LIKELY_ERRORS;
- }
- else {
+ } else {
this.warningLevel = level;
}
}
@@ -709,13 +689,8 @@ public class CompilerConfiguration {
/**
* Sets the encoding to be used when reading source files.
*/
- public void setSourceEncoding(String encoding) {
- setSourceEncodingOrDefault(encoding);
- }
-
- private void setSourceEncodingOrDefault(String encoding) {
- if (encoding == null) encoding = DEFAULT_SOURCE_ENCODING;
- this.sourceEncoding = encoding;
+ public void setSourceEncoding(final String encoding) {
+ this.sourceEncoding = (encoding != null ? encoding :
DEFAULT_SOURCE_ENCODING);
}
/**
@@ -732,12 +707,8 @@ public class CompilerConfiguration {
* @deprecated not used anymore, has no effect
*/
@Deprecated
- public void setOutput(PrintWriter output) {
- if (output == null) {
- this.output = new PrintWriter(NullWriter.DEFAULT);
- } else {
- this.output = output;
- }
+ public void setOutput(final PrintWriter output) {
+ this.output = (output != null ? output : new
PrintWriter(NullWriter.DEFAULT));
}
/**
@@ -750,11 +721,18 @@ public class CompilerConfiguration {
/**
* Sets the target directory.
*/
- public void setTargetDirectory(String directory) {
+ public void setTargetDirectory(final File directory) {
+ this.targetDirectory = directory;
+ }
+
+ /**
+ * Sets the target directory.
+ */
+ public void setTargetDirectory(final String directory) {
setTargetDirectorySafe(directory);
}
- private void setTargetDirectorySafe(String directory) {
+ private void setTargetDirectorySafe(final String directory) {
if (directory != null && directory.length() > 0) {
this.targetDirectory = new File(directory);
} else {
@@ -763,13 +741,6 @@ public class CompilerConfiguration {
}
/**
- * Sets the target directory.
- */
- public void setTargetDirectory(File directory) {
- this.targetDirectory = directory;
- }
-
- /**
* @return the classpath
*/
public List<String> getClasspath() {
@@ -779,8 +750,8 @@ public class CompilerConfiguration {
/**
* Sets the classpath.
*/
- public void setClasspath(String classpath) {
- this.classpath = new LinkedList<String>();
+ public void setClasspath(final String classpath) {
+ this.classpath = new LinkedList<>();
StringTokenizer tokenizer = new StringTokenizer(classpath,
File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
this.classpath.add(tokenizer.nextToken());
@@ -791,8 +762,8 @@ public class CompilerConfiguration {
* sets the classpath using a list of Strings
* @param parts list of strings containing the classpath parts
*/
- public void setClasspathList(List<String> parts) {
- this.classpath = new LinkedList<String>(parts);
+ public void setClasspathList(final List<String> parts) {
+ this.classpath = new LinkedList<>(parts);
}
/**
@@ -805,7 +776,7 @@ public class CompilerConfiguration {
/**
* Turns verbose operation on or off.
*/
- public void setVerbose(boolean verbose) {
+ public void setVerbose(final boolean verbose) {
this.verbose = verbose;
}
@@ -819,7 +790,7 @@ public class CompilerConfiguration {
/**
* Turns debugging operation on or off.
*/
- public void setDebug(boolean debug) {
+ public void setDebug(final boolean debug) {
this.debug = debug;
}
@@ -833,7 +804,7 @@ public class CompilerConfiguration {
/**
* Turns parameter metadata generation on or off.
*/
- public void setParameters(boolean parameters) {
+ public void setParameters(final boolean parameters) {
this.parameters = parameters;
}
@@ -849,7 +820,7 @@ public class CompilerConfiguration {
* non-fatal errors (per unit) that should be tolerated before
* compilation is aborted.
*/
- public void setTolerance(int tolerance) {
+ public void setTolerance(final int tolerance) {
this.tolerance = tolerance;
}
@@ -865,7 +836,7 @@ public class CompilerConfiguration {
* Sets the name of the base class for scripts. It must be a subclass
* of Script.
*/
- public void setScriptBaseClass(String scriptBaseClass) {
+ public void setScriptBaseClass(final String scriptBaseClass) {
this.scriptBaseClass = scriptBaseClass;
}
@@ -876,25 +847,23 @@ public class CompilerConfiguration {
return pluginFactory;
}
- public void setPluginFactory(ParserPluginFactory pluginFactory) {
+ public void setPluginFactory(final ParserPluginFactory pluginFactory) {
this.pluginFactory = pluginFactory;
}
- public void setScriptExtensions(Set<String> scriptExtensions) {
- if(scriptExtensions == null) scriptExtensions = new
LinkedHashSet<String>();
- this.scriptExtensions = scriptExtensions;
+ public void setScriptExtensions(final Set<String> scriptExtensions) {
+ this.scriptExtensions = (scriptExtensions != null ? scriptExtensions :
new LinkedHashSet<String>());
}
public Set<String> getScriptExtensions() {
- if(scriptExtensions == null || scriptExtensions.isEmpty()) {
+ if (scriptExtensions == null || scriptExtensions.isEmpty()) {
/*
* this happens
* * when groovyc calls FileSystemCompiler in forked mode, or
* * when FileSystemCompiler is run from the command line
directly, or
* * when groovy was not started using groovyc or
FileSystemCompiler either
*/
- scriptExtensions = SourceExtensionHandler.getRegisteredExtensions(
- this.getClass().getClassLoader());
+ scriptExtensions =
SourceExtensionHandler.getRegisteredExtensions(getClass().getClassLoader());
}
return scriptExtensions;
}
@@ -903,55 +872,53 @@ public class CompilerConfiguration {
return defaultScriptExtension;
}
-
- public void setDefaultScriptExtension(String defaultScriptExtension) {
+ public void setDefaultScriptExtension(final String defaultScriptExtension)
{
this.defaultScriptExtension = defaultScriptExtension;
}
- public void setRecompileGroovySource(boolean recompile) {
+ public boolean getRecompileGroovySource() {
+ return recompileGroovySource;
+ }
+
+ public void setRecompileGroovySource(final boolean recompile) {
recompileGroovySource = recompile;
}
- public boolean getRecompileGroovySource(){
- return recompileGroovySource;
+ public int getMinimumRecompilationInterval() {
+ return minimumRecompilationInterval;
}
- public void setMinimumRecompilationInterval(int time) {
+ public void setMinimumRecompilationInterval(final int time) {
minimumRecompilationInterval = Math.max(0,time);
}
- public int getMinimumRecompilationInterval() {
- return minimumRecompilationInterval;
+ /**
+ * Returns the compiler bytecode compatibility level. Defaults to the
minimum
+ * officially supported bytecode version for any particular Groovy version.
+ *
+ * @return bytecode compatibility level
+ */
+ public String getTargetBytecode() {
+ return targetBytecode;
}
/**
- * Allow setting the bytecode compatibility level. The parameter can take
- * one of the values in {@link #ALLOWED_JDKS}.
+ * Sets the bytecode compatibility level. The parameter can take one of the
+ * values in {@link #ALLOWED_JDKS}.
*
* @param version the bytecode compatibility level
*/
- public void setTargetBytecode(String version) {
+ public void setTargetBytecode(final String version) {
setTargetBytecodeIfValid(version);
}
- private void setTargetBytecodeIfValid(String version) {
- if (JDK_TO_BYTECODE_VERSION_MAP.keySet().contains(version)) {
+ private void setTargetBytecodeIfValid(final String version) {
+ if (JDK_TO_BYTECODE_VERSION_MAP.containsKey(version)) {
this.targetBytecode = version;
}
}
/**
- * Retrieves the compiler bytecode compatibility level.
- * Defaults to the minimum officially supported bytecode
- * version for any particular Groovy version.
- *
- * @return bytecode compatibility level
- */
- public String getTargetBytecode() {
- return this.targetBytecode;
- }
-
- /**
* Whether the bytecode version has preview features enabled (JEP 12)
*
* @return preview features
@@ -965,14 +932,10 @@ public class CompilerConfiguration {
*
* @param previewFeatures whether to support preview features
*/
- public void setPreviewFeatures(boolean previewFeatures) {
+ public void setPreviewFeatures(final boolean previewFeatures) {
this.previewFeatures = previewFeatures;
}
- private static String getMinBytecodeVersion() {
- return JDK7;
- }
-
/**
* Gets the joint compilation options for this configuration.
* @return the options
@@ -986,7 +949,7 @@ public class CompilerConfiguration {
* Using null will disable joint compilation.
* @param options the options
*/
- public void setJointCompilationOptions(Map<String, Object> options) {
+ public void setJointCompilationOptions(final Map<String, Object> options) {
jointCompilationOptions = options;
}
@@ -1006,7 +969,7 @@ public class CompilerConfiguration {
* @param options the options.
* @throws IllegalArgumentException if the options are null
*/
- public void setOptimizationOptions(Map<String, Boolean> options) {
+ public void setOptimizationOptions(final Map<String, Boolean> options) {
if (options == null) throw new IllegalArgumentException("provided
option map must not be null");
optimizationOptions = options;
}
@@ -1017,9 +980,9 @@ public class CompilerConfiguration {
* @param customizers the list of customizers to be added
* @return this configuration instance
*/
- public CompilerConfiguration
addCompilationCustomizers(CompilationCustomizer... customizers) {
+ public CompilerConfiguration addCompilationCustomizers(final
CompilationCustomizer... customizers) {
if (customizers == null) throw new IllegalArgumentException("provided
customizers list must not be null");
- compilationCustomizers.addAll(Arrays.asList(customizers));
+ Collections.addAll(compilationCustomizers, customizers);
return this;
}
@@ -1066,16 +1029,9 @@ public class CompilerConfiguration {
}
/**
- * Check whether invoke dynamic enabled
- * @return the result
+ * Checks if invoke dynamic is enabled.
*/
public boolean isIndyEnabled() {
- Boolean indyEnabled = this.getOptimizationOptions().get(INVOKEDYNAMIC);
-
- if (null == indyEnabled) {
- return false;
- }
-
- return indyEnabled;
+ return
Boolean.TRUE.equals(getOptimizationOptions().get(INVOKEDYNAMIC));
}
}
diff --git a/src/main/java/org/codehaus/groovy/control/ProcessingUnit.java
b/src/main/java/org/codehaus/groovy/control/ProcessingUnit.java
index c279363..ed196db 100644
--- a/src/main/java/org/codehaus/groovy/control/ProcessingUnit.java
+++ b/src/main/java/org/codehaus/groovy/control/ProcessingUnit.java
@@ -65,7 +65,6 @@ public abstract class ProcessingUnit {
configure(getConfiguration());
}
-
/**
* Reconfigures the ProcessingUnit.
*/
@@ -73,16 +72,10 @@ public abstract class ProcessingUnit {
setConfiguration(configuration);
}
- /**
- * Get the CompilerConfiguration for this ProcessingUnit.
- */
public CompilerConfiguration getConfiguration() {
return configuration;
}
- /**
- * Sets the CompilerConfiguration for this ProcessingUnit.
- */
public final void setConfiguration(CompilerConfiguration configuration) {
this.configuration = configuration;
}
@@ -90,16 +83,13 @@ public abstract class ProcessingUnit {
/**
* Returns the class loader in use by this ProcessingUnit.
*/
-
public GroovyClassLoader getClassLoader() {
return classLoader;
}
-
/**
* Sets the class loader for use by this ProcessingUnit.
*/
-
public void setClassLoader(final GroovyClassLoader loader) {
// ClassLoaders should only be created inside a doPrivileged block in
case
// this method is invoked by code that does not have security
permissions.
@@ -112,7 +102,6 @@ public abstract class ProcessingUnit {
});
}
-
/**
* Errors found during the compilation should be reported through the
ErrorCollector.
*/
@@ -123,16 +112,13 @@ public abstract class ProcessingUnit {
/**
* Returns the current phase.
*/
-
public int getPhase() {
return phase;
}
-
/**
* Returns the description for the current phase.
*/
-
public String getPhaseDescription() {
return Phases.getDescription(phase);
}
@@ -144,13 +130,11 @@ public abstract class ProcessingUnit {
/**
* Marks the current phase complete and processes any errors.
*/
-
public void completePhase() throws CompilationFailedException {
errorCollector.failIfErrors();
phaseComplete = true;
}
-
/**
* A synonym for <code>gotoPhase(getPhase() + 1)</code>.
*/
@@ -158,7 +142,6 @@ public abstract class ProcessingUnit {
gotoPhase(phase + 1);
}
-
/**
* Wraps up any pending operations for the current phase and switches to
the given phase.
*/
diff --git a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
index d2cc9d7..719fd43 100644
--- a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
+++ b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
@@ -59,7 +59,6 @@ import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.Statement;
-import org.codehaus.groovy.control.ClassNodeResolver.LookupResult;
import org.codehaus.groovy.runtime.memoize.ConcurrentCommonCache;
import org.codehaus.groovy.runtime.memoize.EvictableCache;
import org.codehaus.groovy.syntax.Types;
@@ -107,13 +106,13 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
private VariableScope currentScope;
private boolean isTopLevelProperty = true;
- private boolean inPropertyExpression = false;
- private boolean inClosure = false;
+ private boolean inPropertyExpression;
+ private boolean inClosure;
private Map<GenericsTypeName, GenericsType> genericParameterNames = new
HashMap<GenericsTypeName, GenericsType>();
private final Set<FieldNode> fieldTypesChecked = new HashSet<FieldNode>();
- private boolean checkingVariableTypeInDeclaration = false;
- private ImportNode currImportNode = null;
+ private boolean checkingVariableTypeInDeclaration;
+ private ImportNode currImportNode;
private MethodNode currentMethod;
private ClassNodeResolver classNodeResolver;
@@ -146,8 +145,6 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
}
}
-
-
private static String replacePoints(String name) {
return name.replace('.','$');
}
@@ -186,7 +183,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
}
}
- /**
+ /**
* we use LowerCaseClass to limit the resolving the compiler
* does for vanilla names starting with a lower case letter. The idea
* that if we use a vanilla name with a lower case letter, that this
@@ -850,7 +847,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
if (currentClass.getModule().hasPackageName() && name.indexOf('.') ==
-1) return false;
- LookupResult lr = classNodeResolver.resolveName(name, compilationUnit);
+ ClassNodeResolver.LookupResult lr =
classNodeResolver.resolveName(name, compilationUnit);
if (lr != null) {
if (lr.isSourceUnit()) {
SourceUnit su = lr.getSourceUnit();
@@ -1096,14 +1093,14 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
visitAnnotations(ve);
Variable v = ve.getAccessedVariable();
- if(!(v instanceof DynamicVariable) &&
!checkingVariableTypeInDeclaration) {
+ if (!(v instanceof DynamicVariable) &&
!checkingVariableTypeInDeclaration) {
/*
* GROOVY-4009: when a normal variable is simply being used,
there is no need to try to
* resolve its type. Variable type resolve should proceed only if
the variable is being declared.
*/
return ve;
}
- if (v instanceof DynamicVariable){
+ if (v instanceof DynamicVariable) {
String name = ve.getName();
ClassNode t = ClassHelper.make(name);
// asking isResolved here allows to check if a primitive
@@ -1260,7 +1257,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
private static String getDescription(ClassNode node) {
return (node.isInterface() ? "interface" : "class") + " '" +
node.getName() + "'";
}
-
+
protected Expression transformMethodCallExpression(MethodCallExpression
mce) {
Expression args = transform(mce.getArguments());
Expression method = transform(mce.getMethod());
@@ -1277,7 +1274,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
result.setMethodTarget(mce.getMethodTarget());
return result;
}
-
+
protected Expression transformDeclarationExpression(DeclarationExpression
de) {
visitAnnotations(de);
Expression oldLeft = de.getLeftExpression();
@@ -1298,6 +1295,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
newDeclExpr.setDeclaringClass(de.getDeclaringClass());
fixDeclaringClass(newDeclExpr);
newDeclExpr.setSourcePosition(de);
+ newDeclExpr.copyNodeMetaData(de);
newDeclExpr.addAnnotations(de.getAnnotations());
return newDeclExpr;
}
@@ -1312,7 +1310,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
protected Expression
transformAnnotationConstantExpression(AnnotationConstantExpression ace) {
AnnotationNode an = (AnnotationNode) ace.getValue();
ClassNode type = an.getClassNode();
- resolveOrFail(type, ", unable to find class for annotation", an);
+ resolveOrFail(type, " for annotation", an);
for (Map.Entry<String, Expression> member :
an.getMembers().entrySet()) {
member.setValue(transform(member.getValue()));
}
@@ -1328,7 +1326,7 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
// skip built-in properties
if (an.isBuiltIn()) continue;
annType = an.getClassNode();
- resolveOrFail(annType, ", unable to find class for annotation",
an);
+ resolveOrFail(annType, " for annotation", an);
for (Map.Entry<String, Expression> member :
an.getMembers().entrySet()) {
Expression newValue = transform(member.getValue());
Expression adjusted = transformInlineConstants(newValue);
@@ -1370,7 +1368,6 @@ public class ResolveVisitor extends
ClassCodeExpressionTransformer {
for (Map.Entry<String, Expression> member :
an.getMembers().entrySet()) {
member.setValue(transformInlineConstants(member.getValue()));
}
-
}
} else {
return ExpressionUtils.transformInlineConstants(exp);
diff --git a/src/main/java/org/codehaus/groovy/control/SourceUnit.java
b/src/main/java/org/codehaus/groovy/control/SourceUnit.java
index 66c1c73..29736ac 100644
--- a/src/main/java/org/codehaus/groovy/control/SourceUnit.java
+++ b/src/main/java/org/codehaus/groovy/control/SourceUnit.java
@@ -121,7 +121,6 @@ public class SourceUnit extends ProcessingUnit {
return name;
}
-
/**
* Returns the Concrete Syntax Tree produced during parse()ing.
*/
@@ -137,7 +136,6 @@ public class SourceUnit extends ProcessingUnit {
return this.ast;
}
-
/**
* Convenience routine, primarily for use by the InteractiveShell,
* that returns true if parse() failed with an unexpected EOF.
@@ -173,11 +171,9 @@ public class SourceUnit extends ProcessingUnit {
return token.getType() == antlr.Token.EOF_TYPE;
}
-
//---------------------------------------------------------------------------
// FACTORIES
-
/**
* A convenience routine to create a standalone SourceUnit on a String
* with defaults for almost everything that is configurable.
@@ -189,7 +185,6 @@ public class SourceUnit extends ProcessingUnit {
return new SourceUnit(name, source, configuration, null, new
ErrorCollector(configuration));
}
-
/**
* A convenience routine to create a standalone SourceUnit on a String
* with defaults for almost everything that is configurable.
@@ -249,7 +244,7 @@ public class SourceUnit extends ProcessingUnit {
this.ast.setDescription(this.name);
} catch (SyntaxException e) {
if (this.ast == null) {
- // Create a dummy ModuleNode to represent a failed parse - in
case a later phase attempts to use the ast
+ // create an empty ModuleNode to represent a failed parse, in
case a later phase attempts to use the AST
this.ast = new ModuleNode(this);
}
getErrorCollector().addError(new SyntaxErrorMessage(e, this));
@@ -270,7 +265,8 @@ public class SourceUnit extends ProcessingUnit {
XStreamUtils.serialize(name, ast);
}
-
//---------------------------------------------------------------------------
// SOURCE SAMPLING
+
//---------------------------------------------------------------------------
+ // SOURCE SAMPLING
/**
* Returns a sampling of the source at the specified line and column,
@@ -329,5 +325,7 @@ public class SourceUnit extends ProcessingUnit {
getErrorCollector().addErrorAndContinue(se, this);
}
- public ReaderSource getSource() { return source; }
+ public ReaderSource getSource() {
+ return source;
+ }
}
diff --git a/src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java
b/src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java
index 173bbee..c469731 100644
--- a/src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java
+++ b/src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java
@@ -189,6 +189,7 @@ public class StaticImportVisitor extends
ClassCodeExpressionTransformer {
if (left instanceof StaticMethodCallExpression) {
StaticMethodCallExpression smce = (StaticMethodCallExpression)
left;
StaticMethodCallExpression result = new
StaticMethodCallExpression(smce.getOwnerType(), smce.getMethod(), right);
+ result.copyNodeMetaData(smce);
setSourcePosition(result, be);
return result;
}
diff --git
a/src/main/java/org/codehaus/groovy/control/messages/LocatedMessage.java
b/src/main/java/org/codehaus/groovy/control/messages/LocatedMessage.java
index 98c0c5f..959c3f6 100644
--- a/src/main/java/org/codehaus/groovy/control/messages/LocatedMessage.java
+++ b/src/main/java/org/codehaus/groovy/control/messages/LocatedMessage.java
@@ -24,7 +24,6 @@ import org.codehaus.groovy.syntax.CSTNode;
import java.io.PrintWriter;
-
/**
* A base class for compilation messages.
*/
@@ -36,7 +35,6 @@ public class LocatedMessage extends SimpleMessage {
this.context = context;
}
-
public LocatedMessage(String message, Object data, CSTNode context,
SourceUnit source) {
super(message, data, source);
this.context = context;
@@ -53,7 +51,7 @@ public class LocatedMessage extends SimpleMessage {
String sample = source.getSample(line, column, janitor);
if (sample != null) {
- writer.println(source.getSample(line, column, janitor));
+ writer.println(sample);
}
writer.println(name + ": " + line + ": " + this.message);
@@ -63,9 +61,4 @@ public class LocatedMessage extends SimpleMessage {
writer.println("");
}
}
-
}
-
-
-
-