Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/antlr/GroovyLexer.g4
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ INT : 'int';
fragment
LONG : 'long';

MODULE : 'module';
NATIVE : 'native';
NEW : 'new';
NON_SEALED : 'non-sealed';
Expand Down
2 changes: 2 additions & 0 deletions src/antlr/GroovyParser.g4
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ packageDeclaration

importDeclaration
: annotationsOpt IMPORT STATIC? qualifiedName (DOT MUL | AS alias=identifier)?
| annotationsOpt IMPORT MODULE qualifiedName
;


Expand Down Expand Up @@ -1243,6 +1244,7 @@ identifier
| AWAIT
| DEFER
| IN
| MODULE
| PERMITS
| RECORD
| SEALED
Expand Down
61 changes: 61 additions & 0 deletions src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.ModuleImportHelper;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.transform.AsyncTransformHelper;
Expand All @@ -140,15 +141,18 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -338,6 +342,11 @@ public PackageNode visitPackageDeclaration(final PackageDeclarationContext ctx)
public ImportNode visitImportDeclaration(final ImportDeclarationContext ctx) {
List<AnnotationNode> annotations = this.visitAnnotationsOpt(ctx.annotationsOpt());

if (asBoolean(ctx.MODULE())) {
String moduleName = this.visitQualifiedName(ctx.qualifiedName());
return expandModuleImport(moduleName, annotations, ctx);
}

Comment on lines 343 to +349
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When MODULE is present, hasStar / hasAlias are currently ignored. If those forms are meant to be illegal (recommended for alignment with the documented module-import syntax), detect them here and throw a parsing error; otherwise, implement consistent semantics for import module ... .* / as ....

Copilot uses AI. Check for mistakes.
boolean hasStatic = asBoolean(ctx.STATIC());
boolean hasStar = asBoolean(ctx.MUL());
boolean hasAlias = asBoolean(ctx.alias);
Expand Down Expand Up @@ -388,6 +397,58 @@ public ImportNode visitImportDeclaration(final ImportDeclarationContext ctx) {
return configureAST(importNode, ctx);
}

/**
* Expands {@code import module java.base} into star imports for all
* packages exported (unqualified) by the named module and, recursively,
* by any modules it {@code requires transitive} (per JEP 476).
* Packages already covered by Groovy's default imports or existing
* star imports are skipped to avoid redundant resolution work.
* <p>
* Modules are located from system modules (JDK) first, then from
* modular JARs on the compilation classpath. Automatic modules
* (JARs with an {@code Automatic-Module-Name} manifest entry but no
* {@code module-info.class}) are supported — all packages in the JAR
* are imported since automatic modules have no explicit exports.
* <p>
* As per JLS 6.4.1, explicit single-type imports and type-on-demand (star)
* imports take priority over module-expanded imports. Ambiguous class names
* from multiple module imports produce a compile-time error (JLS 7.5.5).
* <p>
* Known difference from Java: Groovy's star imports (including module-expanded
* ones) can resolve package-private types, whereas Java only exposes public
* types from exported packages (see GROOVY-11916).
*/
private ImportNode expandModuleImport(final String moduleName, final List<AnnotationNode> annotations, final ImportDeclarationContext ctx) {
var finder = ModuleImportHelper.moduleFinder(sourceUnit);
List<String> packageNames;
try {
packageNames = ModuleImportHelper.resolveModulePackages(moduleName, finder);
} catch (IllegalArgumentException e) {
throw createParsingFailedException(e.getMessage(), ctx);
}
Set<String> skip = new HashSet<>(Arrays.asList(
org.codehaus.groovy.control.ResolveVisitor.DEFAULT_IMPORTS));
moduleNode.getStarImports().stream().map(ImportNode::getPackageName).forEach(skip::add);
moduleNode.getModuleStarImports().stream().map(ImportNode::getPackageName).forEach(skip::add);
ImportNode lastImport = null;
for (String pkg : packageNames) {
String packageName = pkg + DOT_STR;
if (!skip.contains(packageName)) {
// Separate list so resolution can apply JLS 6.4.1 shadowing:
// a user-written `import foo.*` beats a module-expanded `foo.*`.
moduleNode.addModuleStarImport(packageName, annotations);
lastImport = last(moduleNode.getModuleStarImports());
skip.add(packageName);
}
}
if (lastImport == null) {
// All exported packages were already covered by existing imports
List<ImportNode> existing = moduleNode.getModuleStarImports();
lastImport = !existing.isEmpty() ? last(existing) : last(moduleNode.getStarImports());
Comment thread
paulk-asert marked this conversation as resolved.
}
return configureAST(lastImport, ctx);
}

private static AnnotationNode makeAnnotationNode(final Class<? extends Annotation> type) {
AnnotationNode node = new AnnotationNode(ClassHelper.make(type));
// TODO: source offsets
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/org/codehaus/groovy/ast/ModuleNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public class ModuleNode extends ASTNode {
private final List<MethodNode> methods = new ArrayList<>();
private final List<ImportNode> imports = new ArrayList<>();
private final List<ImportNode> starImports = new ArrayList<>();
private final List<ImportNode> moduleStarImports = new ArrayList<>();
private final Map<String, ImportNode> staticImports = new LinkedHashMap<>();
private final Map<String, ImportNode> staticStarImports = new LinkedHashMap<>();
private CompileUnit unit;
Expand Down Expand Up @@ -183,6 +184,23 @@ public void addStarImport(final String packageName, final List<AnnotationNode> a
storeLastAddedImportNode(importNode);
}

/**
* @return star imports that originated from {@code import module M} declarations.
* Separate from {@link #getStarImports()} so that resolution can apply
* JLS 6.4.1 shadowing (type-import-on-demand shadows module-import).
*/
public List<ImportNode> getModuleStarImports() {
return moduleStarImports;
}

public void addModuleStarImport(final String packageName, final List<AnnotationNode> annotations) {
ImportNode importNode = new ImportNode(packageName);
importNode.addAnnotations(annotations);
moduleStarImports.add(importNode);

storeLastAddedImportNode(importNode);
}

public void addStaticImport(final ClassNode type, final String memberName, final String simpleName) {
addStaticImport(type, memberName, simpleName, Collections.emptyList());
}
Expand Down
145 changes: 145 additions & 0 deletions src/main/java/org/codehaus/groovy/control/ModuleImportHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.control;

import java.lang.module.FindException;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
* Shared utilities for expanding JPMS module imports into package-level
* star imports. Used by both the parser ({@code AstBuilder}) and the
* {@link org.codehaus.groovy.control.customizers.ImportCustomizer}.
*
* @since 6.0.0
*/
public final class ModuleImportHelper {

private ModuleImportHelper() { }

/**
* Builds a {@link ModuleFinder} that combines the system module finder
* with one scanning the compilation classpath for modular JARs.
*
* @param source the source unit providing classpath and classloader
* @return a composite module finder
*/
public static ModuleFinder moduleFinder(final SourceUnit source) {
return ModuleFinder.compose(ModuleFinder.ofSystem(), classpathModuleFinder(source));
}

/**
* Collects the exported package names from the given module and,
* recursively, from any modules it {@code requires transitive}.
* This implements the transitive readability semantics specified
* by JEP 476.
*
* @param moduleRef the module to inspect
* @param finder the finder used to resolve transitive dependencies
* @param packageNames accumulator for discovered package names
* @param visited set of already-visited module names (to avoid cycles)
*/
public static void collectModuleExports(final ModuleReference moduleRef, final ModuleFinder finder,
final List<String> packageNames, final Set<String> visited) {
ModuleDescriptor descriptor = moduleRef.descriptor();
if (!visited.add(descriptor.name())) return;
// Automatic modules have no exports — use packages() instead
if (descriptor.isAutomatic()) {
packageNames.addAll(descriptor.packages());
} else {
descriptor.exports().stream()
.filter(e -> !e.isQualified())
.map(ModuleDescriptor.Exports::source)
.forEach(packageNames::add);
}
// Recursively process transitive dependencies (JEP 476)
for (ModuleDescriptor.Requires req : descriptor.requires()) {
if (req.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
finder.find(req.name()).ifPresent(ref ->
collectModuleExports(ref, finder, packageNames, visited));
}
}
}

/**
* Resolves a module by name and collects its exported packages
* (including transitive dependencies).
*
* @param moduleName the JPMS module name
* @param finder the module finder to use
* @return the list of exported package names
* @throws IllegalArgumentException if the module is not found
*/
public static List<String> resolveModulePackages(final String moduleName, final ModuleFinder finder) {
ModuleReference moduleRef = finder.find(moduleName).orElse(null);
if (moduleRef == null) {
throw new IllegalArgumentException("Unknown module: " + moduleName);
}
List<String> packageNames = new ArrayList<>();
collectModuleExports(moduleRef, finder, packageNames, new HashSet<>());
return packageNames;
}

/**
* Builds a {@link ModuleFinder} that scans the compilation classpath
* for modular JARs (those containing {@code module-info.class}).
* Collects paths from both the compiler configuration classpath and
* any URLClassLoaders in the classloader hierarchy.
*/
private static ModuleFinder classpathModuleFinder(final SourceUnit source) {
Set<Path> paths = new LinkedHashSet<>();
for (String entry : source.getConfiguration().getClasspath()) {
Path p = Path.of(entry);
if (Files.exists(p)) {
paths.add(p);
}
}
ClassLoader cl = source.getClassLoader();
while (cl != null) {
if (cl instanceof URLClassLoader) {
for (URL url : ((URLClassLoader) cl).getURLs()) {
try {
Path p = Path.of(url.toURI());
if (Files.exists(p)) {
paths.add(p);
}
} catch (URISyntaxException ignore) {
}
}
}
cl = cl.getParent();
}
try {
return ModuleFinder.of(paths.toArray(Path[]::new));
} catch (FindException e) {
return ModuleFinder.of();
}
}
}
25 changes: 25 additions & 0 deletions src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,31 @@ protected boolean resolveFromModule(final ClassNode type, final boolean testModu
}
}
}
// Module-expanded star imports — lowest precedence per JLS 6.4.1.
// Only consulted if nothing above resolved the type, and ambiguity
// between two module-expanded packages is a compile-time error
// (matching Java's behavior per JLS 7.5.5 Example 7.5.5-3).
ClassNode moduleMatch = null;
String moduleMatchPkg = null;
for (ImportNode importNode : module.getModuleStarImports()) {
ClassNode tmp = new ConstructedClassWithPackage(importNode.getPackageName(), name);
if (resolve(tmp, false, false, true)) {
ClassNode resolved = tmp.redirect();
if (moduleMatch != null && !moduleMatch.getName().equals(resolved.getName())) {
addError("reference to " + name + " is ambiguous, both "
+ moduleMatch.getName() + " (from " + moduleMatchPkg + ")"
+ " and " + resolved.getName()
+ " (from " + importNode.getPackageName() + ") match", type);
return true;
}
moduleMatch = resolved;
moduleMatchPkg = importNode.getPackageName();
}
}
if (moduleMatch != null) {
type.setRedirect(moduleMatch);
return true;
}
}

return false;
Expand Down
Loading
Loading