Skip to content

Commit

Permalink
GROOVY-11046
Browse files Browse the repository at this point in the history
  • Loading branch information
eric-milles committed Dec 21, 2023
1 parent ccec657 commit 403f3fc
Show file tree
Hide file tree
Showing 10 changed files with 718 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,15 @@ public void testGrab() {
"Test.groovy",
"@Grab('joda-time:joda-time:2.12.5;transitive=false')\n" +
"import org.joda.time.DateTime\n" +
"void printDate() {\n" +
" def now = new DateTime()\n" +
"}\n" +
"printDate()\n",
"def now = new DateTime()\n",
};
//@formatter:on

runNegativeTest(sources, "");
}

/**
* This program has a broken grab. Without changes we get a 'general error'
* recorded on the first line of the source file:
* This program has a broken grab. Without changes we get a 'general error' recorded on the first line of the source file:
* <tt>General error during conversion: Error grabbing Grapes -- [unresolved dependency: org.aspectj#aspectjweaver;1.x: not found]</tt>
* <p>
* With grab improvements we get two errors: the missing dependency and the missing type (which is at the right version of that dependency!)
Expand All @@ -58,13 +54,6 @@ public void testGrab() {
public void testGrabError() {
//@formatter:off
String[] sources = {
"Main.java",
"public class Main {\n" +
" public static void main(String[] args) {\n" +
// not concerned with execution
" }\n" +
"}\n",

"Test.groovy",
"@Grapes([\n" +
" @Grab('joda-time:joda-time:2.12.5;transitive=false'),\n" +
Expand Down Expand Up @@ -94,6 +83,25 @@ public void testGrabError() {
"----------\n");
}

@Test // GROOVY-11046
public void testGrabError2() {
//@formatter:off
String[] sources = {
"Main.groovy",
"@Grab('org.apache.logging.log4j:log4j-core:2.22.0')\n" +
"org.apache.logging.log4j.core.async.AsyncLogger log\n",
};
//@formatter:on

runNegativeTest(sources,
"----------\n" +
"1. ERROR in Main.groovy (at line 2)\n" +
"\torg.apache.logging.log4j.core.async.AsyncLogger log\n" +
"\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Groovy:unable to define class org.apache.logging.log4j.core.async.AsyncLogger : com/lmax/disruptor/EventTranslatorVararg\n" +
"----------\n");
}

@Test // GRECLIPSE-1432
public void testGrabConfig() {
//@formatter:off
Expand Down
1 change: 1 addition & 0 deletions base/org.codehaus.groovy30/.checkstyle
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
<file-match-pattern match-pattern="groovy/control/CompilationUnit.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/CompilerConfiguration.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ErrorCollector.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/GenericsVisitor.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ProcessingUnit.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ResolveVisitor.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/SourceUnit.java" include-pattern="false" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.control;

import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.transform.trait.Traits;

import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isUnboundedWildcard;

/**
* Verify correct usage of generics.
* This includes:
* <ul>
* <li>class header (class and superclass declaration)</li>
* <li>arity of type parameters for fields, parameters, local variables</li>
* <li>invalid diamond {@code <>} usage</li>
* </ul>
*/
public class GenericsVisitor extends ClassCodeVisitorSupport {

private final SourceUnit source;

@Override
protected SourceUnit getSourceUnit() {
return source;
}

public GenericsVisitor(final SourceUnit source) {
this.source = source;
}

//--------------------------------------------------------------------------

@Override
public void visitClass(final ClassNode node) {
ClassNode sn = node.getUnresolvedSuperClass(false);
if (checkWildcard(sn)) return;

boolean isAIC = node instanceof InnerClassNode && ((InnerClassNode) node).isAnonymous();
checkGenericsUsage(sn, node.getSuperClass(), isAIC ? Boolean.TRUE : null);
for (ClassNode face : node.getInterfaces()) {
checkGenericsUsage(face);
}

visitObjectInitializerStatements(node);
node.visitContents(this);
}

@Override
public void visitField(final FieldNode node) {
checkGenericsUsage(node.getType());

super.visitField(node);
}

@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
for (Parameter p : node.getParameters()) {
checkGenericsUsage(p.getType());
}
if (!isConstructor) {
checkGenericsUsage(node.getReturnType());
}

super.visitConstructorOrMethod(node, isConstructor);
}

@Override
public void visitConstructorCallExpression(final ConstructorCallExpression expression) {
ClassNode type = expression.getType();
boolean isAIC = type instanceof InnerClassNode
&& ((InnerClassNode) type).isAnonymous();
checkGenericsUsage(type, type.redirect(), isAIC);

super.visitConstructorCallExpression(expression);
}

@Override
public void visitDeclarationExpression(final DeclarationExpression expression) {
if (expression.isMultipleAssignmentDeclaration()) {
for (Expression e : expression.getTupleExpression()) {
checkGenericsUsage(((VariableExpression) e).getOriginType());
}
} else {
checkGenericsUsage(expression.getVariableExpression().getOriginType());
}

super.visitDeclarationExpression(expression);
}

@Override
public void visitArrayExpression(final ArrayExpression expression) {
checkGenericsUsage(expression.getType());

super.visitArrayExpression(expression);
}

@Override
public void visitCastExpression(final CastExpression expression) {
checkGenericsUsage(expression.getType());

super.visitCastExpression(expression);
}

//--------------------------------------------------------------------------

private boolean checkWildcard(final ClassNode sn) {
boolean wildcard = false;
if (sn.getGenericsTypes() != null) {
for (GenericsType gt : sn.getGenericsTypes()) {
if (gt.isWildcard()) {
addError("A supertype may not specify a wildcard type", sn);
wildcard = true;
}
}
}
return wildcard;
}

private void checkGenericsUsage(ClassNode cn) {
while (cn.isArray())
cn = cn.getComponentType();
checkGenericsUsage(cn, cn.redirect(), null);
}

private void checkGenericsUsage(final ClassNode cn, final ClassNode rn, final Boolean isAIC) {
if (cn.isGenericsPlaceHolder()) return;
GenericsType[] cnTypes = cn.getGenericsTypes();
// raw type usage is always allowed
if (cnTypes == null) return;
GenericsType[] rnTypes = rn.getGenericsTypes();
// you can't parameterize a non-generified type
if (rnTypes == null) {
String message = "The class " + cn.toString(false) + " (supplied with " + plural("type parameter", cnTypes.length) +
") refers to the class " + rn.toString(false) + " which takes no parameters";
if (cnTypes.length == 0) {
message += " (invalid Diamond <> usage?)";
}
addError(message, cn);
return;
}
// parameterize a type by using all of the parameters only
if (cnTypes.length != rnTypes.length) {
if (Boolean.FALSE.equals(isAIC) && cnTypes.length == 0) {
return; // allow Diamond for non-AIC cases from CCE
}
String message;
if (Boolean.TRUE.equals(isAIC) && cnTypes.length == 0) {
message = "Cannot use diamond <> with anonymous inner classes";
} else {
message = "The class " + cn.toString(false) + " (supplied with " + plural("type parameter", cnTypes.length) +
") refers to the class " + rn.toString(false) + " which takes " + plural("parameter", rnTypes.length);
if (cnTypes.length == 0) {
message += " (invalid Diamond <> usage?)";
}
}
addError(message, cn);
return;
}
for (int i = 0; i < cnTypes.length; i++) {
ClassNode cnType = cnTypes[i].getType();
ClassNode rnType = rnTypes[i].getType();
// check nested type parameters
checkGenericsUsage(cnType);
// check bounds: unbounded wildcard (aka "?") is universal substitute
if (!isUnboundedWildcard(cnTypes[i])) {
// check upper bound(s)
ClassNode[] bounds = rnTypes[i].getUpperBounds();

// first can be class or interface
boolean valid = cnType.isDerivedFrom(rnType) || ((rnType.isInterface() || Traits.isTrait(rnType)) && cnType.implementsInterface(rnType));

// subsequent bounds if present can be interfaces
if (valid && bounds != null && bounds.length > 1) {
for (int j = 1; j < bounds.length; j++) {
ClassNode bound = bounds[j];
if (!cnType.implementsInterface(bound)) {
valid = false;
break;
}
}
}

if (!valid) {
addError("The type " + cnTypes[i].getName() + " is not a valid substitute for the bounded parameter <" + rnTypes[i] + ">", cnTypes[i]);
}
}
}
}

private static String plural(final String string, final int count) {
return "" + count + " " + (count == 1 ? string : string + "s");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@
import static org.codehaus.groovy.ast.tools.ClosureUtils.getParametersSafe;

/**
* Visitor to resolve Types and convert VariableExpression to
* Visitor to resolve types and convert VariableExpression to
* ClassExpressions if needed. The ResolveVisitor will try to
* find the Class for a ClassExpression and prints an error if
* it fails to do so. Constructions like C[], foo as C, (C) foo
* will force creation of a ClassExpression for C
* <p>
* Note: the method to start the resolving is startResolving(ClassNode, SourceUnit).
* Note: the method to start the resolving is {@link #startResolving(ClassNode,SourceUnit)}.
*/
public class ResolveVisitor extends ClassCodeExpressionTransformer {
// note: BigInteger and BigDecimal are also imported by default
Expand Down Expand Up @@ -347,12 +347,12 @@ private void resolveOrFail(final ClassNode type, final String msg, final ASTNode
}

private void resolveOrFail(final ClassNode type, final String msg, final ASTNode node, final boolean preferImports) {
if (preferImports) {
if (preferImports && !type.isResolved() && !type.isPrimaryClassNode()) {
resolveGenericsTypes(type.getGenericsTypes());
if (resolveAliasFromModule(type)) return;
}
if (resolve(type)) return;
/* GRECLIPSE edit
if (resolve(type)) return;
if (resolveToInner(type)) return;
if (resolveToOuterNested(type)) return;
Expand All @@ -362,6 +362,13 @@ private void resolveOrFail(final ClassNode type, final String msg, final ASTNode
while (temp.isArray())//GROOVY-8715
temp = temp.getComponentType();
final String name = temp.getName();
try {
if (resolve(type)) return;
} catch (LinkageError e) {
String message = "unable to define class " + name + msg + " : " + e.getLocalizedMessage();
addError(message, temp.getEnd() > 0 ? temp : node);
return;
}
String nameAsType = name.replace('.', '$');
ModuleNode module = currentClass.getModule();
if (!name.equals(nameAsType) && module.hasPackageName()) {
Expand Down
1 change: 1 addition & 0 deletions base/org.codehaus.groovy40/.checkstyle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<file-match-pattern match-pattern="groovy/control/CompilationUnit.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/CompilerConfiguration.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ErrorCollector.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/GenericsVisitor.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ProcessingUnit.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/ResolveVisitor.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/SourceUnit.java" include-pattern="false" />
Expand Down
Loading

0 comments on commit 403f3fc

Please sign in to comment.