This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch groovyism/core-leaves in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 5b611a90c053cdd6e4a5e7aad1dbd71a447ff91b Author: Walter Duque de Estrada <[email protected]> AuthorDate: Fri Oct 16 15:45:37 2026 -0500 refactor(async-core,beans-dsl,common): make converted sources idiomatic Idiomatic-Groovy pass over the Java-to-Groovy conversion output for grails-async/core, grails-beans-dsl, and grails-common. No behaviour or public API change. Applied - Null-safe navigation / Elvis for null checks: AutoConfigurationImportsWriter (handAuthored?.isFile(), directory?.parentFile, name?.toString()?...), OnGrailsEnvCondition (context.environment property, name?.toString()) - Groovy truth for non-falsy object types: !className, directory loop guard - `in` for Collection.contains: AutoConfigurationImportsWriter (3 sites) - `==`/`!=` for String.equals: DelegateAsyncTransformation (VOID check), AutoConfigurationImportsWriter (entries/kept/onDisk Set comparisons, 'build'/'target' directory name checks) - property syntax for simple getters with no isX()/getX() collision: OnGrailsEnvCondition (classLoader, environment), RegistrableTypes (Type.sort/elementType/internalName/descriptor, Handle.owner/desc, ConstantDynamic.bootstrapMethod/bootstrapMethodArgumentCount) - flow typing instead of instanceof + explicit cast (locals only, per skill section 4.2): RegistrableTypes$ReferenceCollector#addConstant - trailing-closure syntax for removeIf/computeIfAbsent, findAll instead of a for loop that only builds a Set, null-safe `.each` instead of a null-guarded for loop: AutoConfigurationImportsWriter, RegistrableTypes - `.every` instead of a for loop with an early-exit failure return (allMatch shape): RegistrableTypes#referencesLoad, ReflectionUtils #isApplicationClass - GString instead of String + Object concatenation landing in a String-typed slot: AutoConfigurationImportsWriter (warn message, write failure message) - `'.' as char` instead of `'.'.charAt(0)`: AutoConfigurationImportsWriter #isGeneratedHere - Arrays.asList(array) -> array.toList(): DelegateAsyncTransformation (error-message formatting only) Deliberately left (Tier C / too risky) - DelegateAsyncTransformation and GrailsBeansASTTransformation: left every ClassNode/AST-node `.equals()`/identity comparison as-is (e.g. OBJECT_CLASS_NODE.equals(returnType), candidate.redirect().equals(...), ClassHelper.CLOSURE_TYPE.equals(...), Boolean.FALSE.equals(...) against an Object-typed AST constant value). These compare AST nodes or possibly-mismatched-type values where `==` risks either changing identity semantics or throwing via a Comparable/compareTo path that `.equals()` does not. Per the task's own caution, left as-is rather than guessed at. - GrailsBeansASTTransformation.groovy (3,514 lines) otherwise untouched in its entirety: dense with the same AST-identity-sensitive `.equals()` calls interleaved with Map/Set construction used as mutable state across a multi-pass traversal. A mechanical idiom pass across that surface carries more risk than the verification budget here can rule out; flagging the whole file as a Tier-C skip rather than cherry-picking changes whose downstream effects on codegen I could not fully trace. - grails-async: DelegateAsyncTransactionalMethodTransformer.groovy (interface) already minimal; all 6 test specs plus DefaultDelegateAsyncTransactionalMethodTransformer.groovy already idiomatic (property syntax, .is(), trailing closures, `in`, switch expressions) with no Java-shaped leftovers to fix - no test source changes needed. - AheadOfTimeProcessing.groovy, ConditionalOnGrailsEnv.groovy, GrailsBeans.groovy: trivial/annotation-only, nothing to convert. Verification - grails-async-core, grails-beans-dsl, grails-common: compileGroovy and compileTestGroovy clean; full `test` green (async-core 96/0, beans-dsl 449/0, common 68/0); codenarcMain/codenarcTest/checkstyleMain clean (0 violations; checkstyle NO-SOURCE, no Java main sources) - javap dynamic-dispatch audit on every changed class (including the ReferenceCollector flow-typing change): only initMetaClass and compareEqual/compareNotEqual, no setGroovyObjectProperty/ getGroovyObjectProperty/invokeMethod/invokeMethodN - downstream compileGroovy green: grails-datamapping-async, grails-async-{rxjava,rxjava2,rxjava3,gpars,groovy-concurrent}, grails-async, grails-datastore-async, grails-test-examples-beans-dsl, grails-rest-transforms, grails-web-databinding, grails-databinding-core, grails-redis, grails-views-gson, grails-views-core, grails-data-mongodb-core, grails-domain-class Co-Authored-By: Claude Sonnet 5 <[email protected]> --- .../internal/DelegateAsyncTransformation.groovy | 4 +- .../beans/AutoConfigurationImportsWriter.groovy | 44 ++++++++++---------- .../compiler/beans/OnGrailsEnvCondition.groovy | 8 ++-- .../grails/common/aot/RegistrableTypes.groovy | 48 ++++++++-------------- .../grails/common/reflect/ReflectionUtils.groovy | 7 +--- 5 files changed, 44 insertions(+), 67 deletions(-) diff --git a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.groovy b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.groovy index db61aff39f..f1fe08c53a 100644 --- a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.groovy +++ b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.groovy @@ -72,7 +72,7 @@ class DelegateAsyncTransformation implements ASTTransformation, TransformWithPri @Override void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { - throw new GroovyBugError('Internal error: expecting [AnnotationNode, AnnotatedNode] but got: ' + Arrays.asList(nodes)) + throw new GroovyBugError('Internal error: expecting [AnnotationNode, AnnotatedNode] but got: ' + nodes.toList()) } AnnotatedNode parent = (AnnotatedNode) nodes[1] @@ -116,7 +116,7 @@ class DelegateAsyncTransformation implements ASTTransformation, TransformWithPri if (existingMethod == null) { ClassNode promiseNode = ClassHelper.make(Promise).getPlainNodeReference() ClassNode originalReturnType = m.getReturnType() - if (!VOID.equals(originalReturnType.getNameWithoutPackage())) { + if (VOID != originalReturnType.getNameWithoutPackage()) { ClassNode returnType if (ClassHelper.isPrimitiveType(originalReturnType.redirect())) { returnType = ClassHelper.getWrapper(originalReturnType.redirect()) diff --git a/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/AutoConfigurationImportsWriter.groovy b/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/AutoConfigurationImportsWriter.groovy index f390088079..b81d13fc6b 100644 --- a/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/AutoConfigurationImportsWriter.groovy +++ b/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/AutoConfigurationImportsWriter.groovy @@ -97,18 +97,18 @@ final class AutoConfigurationImportsWriter { * @return {@code true} when the file was written */ static boolean register(String className, File targetDirectory, SourceUnit source, Object compilation) { - if (className == null || className.isEmpty() || targetDirectory == null) { + if (!className || targetDirectory == null) { return false } File sourceDirectory = findSourceDirectory(targetDirectory) File handAuthored = sourceDirectory == null ? null : new File(sourceDirectory, SOURCE_IMPORTS_LOCATION) - if (handAuthored != null && handAuthored.isFile()) { + if (handAuthored?.isFile()) { Set<String> handAuthoredEntries = new TreeSet<>() readEntries(handAuthored, handAuthoredEntries) - if (!handAuthoredEntries.contains(className)) { - warn(source, className + ' is generated from a beans closure but is not listed in ' + - SOURCE_IMPORTS_LOCATION + ', so Spring Boot will not read it. Add it there, or delete ' + + if (!(className in handAuthoredEntries)) { + warn(source, "$className is generated from a beans closure but is not listed in " + + "$SOURCE_IMPORTS_LOCATION, so Spring Boot will not read it. Add it there, or delete " + 'that file once it holds nothing that is not generated and it will be written for you.') } write(new File(targetDirectory, IMPORTS_LOCATION), Collections.emptySet(), source) @@ -127,12 +127,12 @@ final class AutoConfigurationImportsWriter { // auto-configuration it cannot load. Anything this compilation registered is kept regardless: // its class file is written in a later phase than this one runs in. Set<String> entries = new TreeSet<>(onDisk) - entries.removeIf({ entry -> !registeredHere.contains(entry) && !isGeneratedHere(targetDirectory, entry) }) + entries.removeIf { entry -> !(entry in registeredHere) && !isGeneratedHere(targetDirectory, entry) } entries.addAll(registeredHere) // Against what is on disk rather than against the pruned set: a call that only drops a stale // entry adds nothing, and comparing the two would leave the entry it just decided to drop. - if (entries.equals(onDisk) && importsFile.isFile()) { + if (entries == onDisk && importsFile.isFile()) { return false } @@ -149,14 +149,14 @@ final class AutoConfigurationImportsWriter { if (entries.isEmpty()) { return Files.deleteIfExists(importsFile.toPath()) } - Files.createDirectories(importsFile.toPath().getParent()) + Files.createDirectories(importsFile.toPath().parent) // Sorted and newline-terminated, so recompiling the same sources rewrites the same bytes. Files.write(importsFile.toPath(), (String.join('\n', entries) + '\n') .getBytes(StandardCharsets.UTF_8)) return true } catch (IOException notWritable) { - String message = 'Could not write generated auto-configuration imports at ' + importsFile + String message = "Could not write generated auto-configuration imports at $importsFile" if (source != null) { source.addErrorAndContinue(new SyntaxException(message, 1, 1)) } @@ -189,7 +189,7 @@ final class AutoConfigurationImportsWriter { File importsFile = new File(targetDirectory, IMPORTS_LOCATION) File sourceDirectory = findSourceDirectory(targetDirectory) File handAuthored = sourceDirectory == null ? null : new File(sourceDirectory, SOURCE_IMPORTS_LOCATION) - if (handAuthored != null && handAuthored.isFile()) { + if (handAuthored?.isFile()) { return write(importsFile, Collections.emptySet(), source) } if (!importsFile.isFile()) { @@ -200,13 +200,10 @@ final class AutoConfigurationImportsWriter { Set<String> entries = new TreeSet<>() readEntries(importsFile, entries) Set<String> registeredHere = registeredBy(compilation) - Set<String> kept = new TreeSet<>() - for (String entry in entries) { - if (registeredHere.contains(entry) || isGeneratedHere(targetDirectory, entry)) { - kept.add(entry) - } - } - if (kept.equals(entries)) { + Set<String> kept = new TreeSet<>(entries.findAll { String entry -> + entry in registeredHere || isGeneratedHere(targetDirectory, entry) + }) + if (kept == entries) { return false } return write(importsFile, kept, source) @@ -218,13 +215,14 @@ final class AutoConfigurationImportsWriter { // then rests entirely on which class files are present, which is right for a single one. return Collections.synchronizedSet(new TreeSet<>()) } - return REGISTERED_BY_COMPILATION.computeIfAbsent(compilation, - { key -> Collections.synchronizedSet(new TreeSet<>()) }) + return REGISTERED_BY_COMPILATION.computeIfAbsent(compilation) { Object key -> + Collections.synchronizedSet(new TreeSet<>()) + } } /** Whether {@code className} is still a class this module generates into its own output. */ private static boolean isGeneratedHere(File targetDirectory, String className) { - return new File(targetDirectory, className.replace('.'.charAt(0), File.separatorChar) + CLASS_FILE_EXTENSION).isFile() + return new File(targetDirectory, className.replace('.' as char, File.separatorChar) + CLASS_FILE_EXTENSION).isFile() } private static void warn(SourceUnit source, String message) { @@ -247,10 +245,10 @@ final class AutoConfigurationImportsWriter { } } File directory = targetDirectory - while (directory != null && !('build'.equals(directory.getName()) || 'target'.equals(directory.getName()))) { - directory = directory.getParentFile() + while (directory && !(directory.name == 'build' || directory.name == 'target')) { + directory = directory.parentFile } - return directory == null ? null : directory.getParentFile() + return directory?.parentFile } /** Adds the names in {@code file}, skipping blanks and the {@code #} comments Spring Boot skips. */ diff --git a/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/OnGrailsEnvCondition.groovy b/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/OnGrailsEnvCondition.groovy index f0e1481abd..db16cf2c5d 100644 --- a/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/OnGrailsEnvCondition.groovy +++ b/grails-beans-dsl/src/main/groovy/org/grails/compiler/beans/OnGrailsEnvCondition.groovy @@ -59,7 +59,7 @@ class OnGrailsEnvCondition implements Condition { if (current == null) { return false } - for (String candidate in (String[]) value) { + for (String candidate in value) { if (current.equalsIgnoreCase(candidate)) { return true } @@ -68,11 +68,11 @@ class OnGrailsEnvCondition implements Condition { } private String currentEnvironmentName(ConditionContext context) { - String fromGrails = currentEnvironmentNameFromGrails(context.getClassLoader()) + String fromGrails = currentEnvironmentNameFromGrails(context.classLoader) if (fromGrails != null) { return fromGrails } - context.getEnvironment().getProperty(ENVIRONMENT_PROPERTY) + context.environment.getProperty(ENVIRONMENT_PROPERTY) } private String currentEnvironmentNameFromGrails(ClassLoader classLoader) { @@ -89,7 +89,7 @@ class OnGrailsEnvCondition implements Condition { } Method getName = environmentClass.getMethod('getName') Object name = getName.invoke(current) - return name == null ? null : name.toString().toLowerCase(Locale.ENGLISH) + return name?.toString()?.toLowerCase(Locale.ENGLISH) } catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) { // Not a Grails application, or an Environment that cannot answer - fall back to the diff --git a/grails-common/src/main/groovy/org/apache/grails/common/aot/RegistrableTypes.groovy b/grails-common/src/main/groovy/org/apache/grails/common/aot/RegistrableTypes.groovy index 106539a5bf..2d50b05446 100644 --- a/grails-common/src/main/groovy/org/apache/grails/common/aot/RegistrableTypes.groovy +++ b/grails-common/src/main/groovy/org/apache/grails/common/aot/RegistrableTypes.groovy @@ -86,12 +86,7 @@ final class RegistrableTypes { catch (IOException | RuntimeException ex) { return false } - for (String name in referenced) { - if (!ClassUtils.isPresent(name, classLoader)) { - return false - } - } - return true + return referenced.every { String name -> ClassUtils.isPresent(name, classLoader) } } /** Collects the types a class names, in its own declaration and in the bodies of its methods. */ @@ -126,11 +121,11 @@ final class RegistrableTypes { return } Type element = type - while (element.getSort() == Type.ARRAY) { - element = element.getElementType() + while (element.sort == Type.ARRAY) { + element = element.elementType } - if (element.getSort() == Type.OBJECT) { - add(element.getInternalName()) + if (element.sort == Type.OBJECT) { + add(element.internalName) } } @@ -148,25 +143,22 @@ final class RegistrableTypes { /** Adds whichever constant carries a type: a class literal, a handle, or a method type. */ private void addConstant(@Nullable Object constant) { if (constant instanceof Type) { - Type type = (Type) constant - if (type.getSort() == Type.METHOD) { - addMethodDescriptor(type.getDescriptor()) + if (constant.sort == Type.METHOD) { + addMethodDescriptor(constant.descriptor) } else { - addType(type) + addType(constant) } } else if (constant instanceof Handle) { - Handle handle = (Handle) constant - add(handle.getOwner()) - addMethodDescriptor(handle.getDesc()) + add(constant.owner) + addMethodDescriptor(constant.desc) } else if (constant instanceof ConstantDynamic) { - ConstantDynamic dynamic = (ConstantDynamic) constant - addType(Type.getType(dynamic.getDescriptor())) - add(dynamic.getBootstrapMethod().getOwner()) - for (int i = 0; i < dynamic.getBootstrapMethodArgumentCount(); i++) { - addConstant(dynamic.getBootstrapMethodArgument(i)) + addType(Type.getType(constant.descriptor)) + add(constant.bootstrapMethod.owner) + for (int i = 0; i < constant.bootstrapMethodArgumentCount; i++) { + addConstant(constant.getBootstrapMethodArgument(i)) } } } @@ -175,11 +167,7 @@ final class RegistrableTypes { void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { add(superName) - if (interfaces != null) { - for (String each in interfaces) { - add(each) - } - } + interfaces?.each { String each -> add(each) } } @Override @@ -193,11 +181,7 @@ final class RegistrableTypes { MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { addMethodDescriptor(descriptor) - if (exceptions != null) { - for (String each in exceptions) { - add(each) - } - } + exceptions?.each { String each -> add(each) } return new MethodVisitor(SpringAsmInfo.ASM_VERSION) { @Override void visitTypeInsn(int opcode, String type) { diff --git a/grails-common/src/main/groovy/org/apache/grails/common/reflect/ReflectionUtils.groovy b/grails-common/src/main/groovy/org/apache/grails/common/reflect/ReflectionUtils.groovy index e067912c4d..6aea6e8a54 100644 --- a/grails-common/src/main/groovy/org/apache/grails/common/reflect/ReflectionUtils.groovy +++ b/grails-common/src/main/groovy/org/apache/grails/common/reflect/ReflectionUtils.groovy @@ -187,12 +187,7 @@ final class ReflectionUtils { return false } String name = clazz.name - for (String prefix : NON_APPLICATION_PACKAGES) { - if (name.startsWith(prefix)) { - return false - } - } - return true + return NON_APPLICATION_PACKAGES.every { String prefix -> !name.startsWith(prefix) } } }
