[
https://issues.apache.org/jira/browse/GROOVY-11916?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18148524#comment-18148524
]
ASF GitHub Bot commented on GROOVY-11916:
-----------------------------------------
daniellansun commented on code in PR #3227:
URL: https://github.com/apache/groovy/pull/3227#discussion_r4650396252
##########
src/main/java/org/codehaus/groovy/control/ResolveVisitor.java:
##########
@@ -791,6 +807,187 @@ private void ambiguousClass(final ClassNode type, final
ClassNode iType, final S
}
}
+ /**
+ * Binds a simple name from on-demand imports.
+ * <p>
+ * A source import shadows every default import, including implicit
+ * {@code java.lang.*} and star imports added by a compilation customizer.
+ * Source static-import-on-demand, source type-import-on-demand, and the
+ * packages expanded from one source {@code import module} are walked in
+ * source order. The packages of a single module import are one statement:
+ * the first accessible type among them is bound, and an inaccessible type
+ * in an earlier exported package does not hide a later package of that
+ * same statement.
+ * <p>
+ * Separate source statements are not a fallback for each other. The first
+ * statement that finds the type claims it. An accessible type is bound.
+ * That is the long-standing rule: {@code import java.util.*} before
+ * {@code import java.sql.*} selects {@code java.util.Date}, and the
+ * reverse selects {@code java.sql.Date}. Two accessible source stars are
+ * not an ambiguity. An inaccessible type also claims the name, so a later
+ * source statement does not bind a different type that would be displaced
+ * if the earlier type became visible. The name then falls through to
+ * customizer on-demand imports and the language defaults. A non-static
+ * member type is not claimed, because a type star does not import it.
+ * <p>
+ * Customizer on-demand imports have no source location. They are tried
+ * when no source statement bound the name, including when one claimed
+ * an inaccessible type, and before the language defaults, so a
+ * configured star can still supply {@code Date} or {@code String}.
+ * Within that tier an inaccessible type is skipped. Static stars
+ * precede package stars because the two are stored separately. An
+ * explicit single-type import is resolved earlier and therefore wins
+ * over every on-demand import.
+ *
+ * @return {@code true} if the name was bound
+ */
+ private boolean resolveFromOnDemandImports(final ClassNode type, final
String name, final ModuleNode module) {
+ OnDemandImports order = onDemandImports(module);
+ if (bindOnDemandTier(type, name, order.declared, true)) return true;
+ return bindOnDemandTier(type, name, order.customizer, false);
+ }
+
+ /**
+ * @param claim when {@code true}, a group that finds the type but cannot
+ * access it stops later groups in this tier. Customizer
+ * imports pass {@code false} and skip that group.
+ * @return {@code true} if a type was bound
+ */
+ private boolean bindOnDemandTier(final ClassNode type, final String name,
final List<List<ImportNode>> groups, final boolean claim) {
+ for (List<ImportNode> group : groups) {
+ OnDemandHit hit = bindOnDemandGroup(type, name, group);
+ if (hit == OnDemandHit.BOUND) return true;
+ if (claim && hit == OnDemandHit.BLOCKED) return false;
+ }
+ return false;
+ }
+
+ private OnDemandHit bindOnDemandGroup(final ClassNode type, final String
name, final List<ImportNode> group) {
+ boolean blocked = false;
+ for (ImportNode importNode : group) {
+ OnDemandHit hit = bindOnDemand(type, name, importNode);
+ if (hit == OnDemandHit.BOUND) return OnDemandHit.BOUND;
+ if (hit == OnDemandHit.BLOCKED) blocked = true;
+ }
+ return blocked ? OnDemandHit.BLOCKED : OnDemandHit.MISS;
+ }
+
+ private OnDemandHit bindOnDemand(final ClassNode type, final String name,
final ImportNode importNode) {
+ ClassNode outer = importNode.getType();
+ if (outer != null) {
+ // The star named a type: "import static Type.*" (the parser sets
+ // the type) or "import Type.*" (visitClass sets it when the name
+ // resolves to a class). Both import member types of that type,
+ // and only a static member type is in scope, the same rule as a
+ // single static import. A non-static inner class is not, and it
+ // does not claim the name. A member type of an interface is
+ // implicitly static, so Map.Entry still matches.
+ ClassNode tmp = new ConstructedNestedClass(outer, name);
+ if (!resolve(tmp, false, false, true) ||
!Modifier.isStatic(tmp.getModifiers())) {
+ return OnDemandHit.MISS;
+ }
+ if (!isStarImportAccessible(tmp, outer)) return
OnDemandHit.BLOCKED;
+ type.setRedirect(tmp.redirect());
+ return OnDemandHit.BOUND;
+ }
+ String packageName = importNode.getPackageName();
+ if (packageName == null) return OnDemandHit.MISS;
+ ClassNode tmp = new ConstructedClassWithPackage(packageName, name);
+ if (!resolve(tmp, false, false, true)) return OnDemandHit.MISS;
+ if (!isStarImportAccessible(tmp, null)) return OnDemandHit.BLOCKED;
+ type.setRedirect(tmp.redirect());
+ return OnDemandHit.BOUND;
+ }
+
+ /**
+ * Source on-demand imports in source order, grouped by statement, then
+ * customizer on-demand imports. Recomputed when needed: the lists are
+ * small, and storing them as module metadata would keep them for the
+ * rest of compilation.
+ * <p>
+ * {@code import module} expands to one star per exported package, but only
+ * the last of those nodes carries the statement's line and column. The
+ * packages before it have no position of their own and must inherit that
+ * position, in export order, as one statement. Sorting separate nodes by
+ * the line numbers they actually store would place those packages, and
+ * every customizer import (line <= 0), ahead of the source imports.
+ * {@code List.sort} is stable, so statements that share a position keep
+ * the order they were added.
+ */
+ private static OnDemandImports onDemandImports(final ModuleNode module) {
+ List<PositionedImport> positioned = new ArrayList<>();
+ for (ImportNode node : module.getStaticStarImports().values()) {
+ if (node.getLineNumber() > 0) positioned.add(single(node));
+ }
+ for (ImportNode node : module.getStarImports()) {
+ if (node.getLineNumber() > 0) positioned.add(single(node));
+ }
+ List<ImportNode> pendingModule = new ArrayList<>();
+ for (ImportNode node : module.getModuleStarImports()) {
+ pendingModule.add(node);
+ if (node.getLineNumber() > 0) {
+ positioned.add(new PositionedImport(node.getLineNumber(),
node.getColumnNumber(), List.copyOf(pendingModule)));
+ pendingModule.clear();
+ }
+ }
+ positioned.sort((a, b) -> {
+ int byLine = Integer.compare(a.line, b.line);
+ if (byLine != 0) return byLine;
+ return Integer.compare(a.column, b.column);
Review Comment:
Hi Jochen,
Agreed — line numbers are only a stand-in. Source on-demand imports live in
three lists, and `import module` stamps the statement position only on the last
expanded package, so the current walk sorts by that position and treats line <=
0 as a customizer import. A proper fix would record declaration order and
origin when the import is added, rather than recovering them from the AST
coordinates. I would rather not hold this change for that, as you said, and can
follow up separately if you would like that cleaned up.
> Star imports should not resolve package-private types
> -----------------------------------------------------
>
> Key: GROOVY-11916
> URL: https://issues.apache.org/jira/browse/GROOVY-11916
> Project: Groovy
> Issue Type: Bug
> Reporter: Paul King
> Priority: Major
>
> Groovy's star import resolution (e.g., import java.util.*) currently includes
> package-private classes in name resolution. On modern JDKs (9+) with the
> module system, these classes cannot actually be used — attempts result in
> IllegalAccessError at runtime. This can lead to confusing errors and
> inconsistency with Java's behaviour where star imports only resolve public
> types.
> For example, import java.util.* allows def cls = TimSort to compile
> (resolving the package-private java.util.TimSort), but any actual usage
> (instanceof, construction, method calls) fails at runtime with
> IllegalAccessError.
> {code:groovy}
> import java.util.*
> assert String.modifiers == 17
> def cls = TimSort // fine
> assert cls.modifiers == 0
> println cls // => class java.util.TimSort
> println Class.forName('java.util.TimSort') // => class java.util.TimSort
> println new Object() instanceof TimSort // IllegalAccessError
> {code}
> Having said that, as a counter example, is it really any different than being
> able to get the class via Class.forName?
> If the Java behavior is deemed correct, the fix would be to filter non-public
> classes during star import resolution in ResolveVisitor, producing a clean
> compile-time error instead of a runtime error. This is technically a breaking
> change but only affects code that was already failing at runtime on modular
> JDKs.
> This also benefits the import module feature (GROOVY-11896), which expands to
> star imports — filtering at the resolution level means module imports
> correctly include only public types, matching Java's import module semantics.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)