jdaugherty commented on code in PR #433: URL: https://github.com/apache/grails-intellij-plugin/pull/433#discussion_r4175989251
########## plugin/src/main/java/org/apache/grails/intellij/plugin/references/domain/detachedCriteria/WhereQueryClosureMemberContributor.java: ########## @@ -0,0 +1,143 @@ +/* + * 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 + * + * https://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.apache.grails.intellij.plugin.references.domain.detachedCriteria; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.ResolveState; +import com.intellij.psi.scope.ElementClassHint; +import com.intellij.psi.scope.PsiScopeProcessor; +import com.intellij.psi.util.PsiTreeUtil; +import org.apache.grails.intellij.plugin.references.domain.DomainDescriptor; +import org.apache.grails.intellij.plugin.util.GrailsArtifact; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; +import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils; +import org.jetbrains.plugins.groovy.lang.resolve.ClosureMemberContributor; +import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; + +import java.util.Set; + +/** + * Resolves the bare property names of a GORM where query ({@code Person.where { active == true && age >= 18 }}) + * to the persistent properties of the queried domain class. + * <p> + * The GORM 5+ {@code GormEntity} trait declares {@code where(@DelegatesTo(DetachedCriteria) Closure)}: the delegate + * is a raw {@code DetachedCriteria}, which has no such properties, because GORM rewrites the closure at compile time + * (DetachedCriteriaTransformer) into criteria calls. Without this contributor the properties stay unresolved, which + * {@code @CompileStatic}/{@code @GrailsCompileStatic} code reports as an error although it compiles. + */ +final class WhereQueryClosureMemberContributor extends ClosureMemberContributor { + + // See DetachedCriteriaTransformer: the methods whose closure argument is transformed into a where query. + private static final Set<String> WHERE_METHODS = Set.of("where", "whereAny", "whereLazy", "find", "findAll"); + + private static final Set<String> IMPLICIT_PROPERTIES = Set.of("id", "version"); + + @Override + protected void processMembers(@NotNull GrClosableBlock closure, + @NotNull PsiScopeProcessor processor, + @NotNull PsiElement place, + @NotNull ResolveState state) { + String nameHint = ResolveUtil.getNameHint(processor); + if (nameHint == null) return; + + if (!(place instanceof GrReferenceExpression refExpr) || refExpr.isQualified()) return; + if (closure != PsiTreeUtil.getParentOfType(place, GrClosableBlock.class)) return; + + ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); + boolean processProperties = ResolveUtil.shouldProcessProperties(classHint); + boolean processMethods = ResolveUtil.shouldProcessMethods(classHint); + if (!processProperties && !processMethods) return; + + PsiClass domainClass = getQueriedDomainClass(closure); + if (domainClass == null) return; + + // A Groovy property is a private field plus accessors, and from outside its class it is read through the + // getter: resolving to the field itself is an access violation under @CompileStatic. So the property is + // contributed as its getter, which the reference resolves to via the accessor processor and which + // navigates to (and renames with) the field. Only fields that can be read directly - e.g. the light + // fields injected for hasMany, id and version - are handed to the property processor. + if (processMethods) { + PsiMethod getter = findGetter(domainClass, nameHint); + if (getter != null && !processor.execute(getter, state)) return; + } + + if (processProperties) { + PsiField field = findReadableField(domainClass, nameHint); + if (field != null) processor.execute(field, state); + } + } + + private static @Nullable PsiClass getQueriedDomainClass(@NotNull GrClosableBlock closure) { + PsiElement parent = closure.getParent(); + if (parent instanceof GrArgumentList) parent = parent.getParent(); + if (!(parent instanceof GrMethodCall call)) return null; + + if (!(call.getInvokedExpression() instanceof GrReferenceExpression invoked)) return null; + if (!WHERE_METHODS.contains(invoked.getReferenceName())) return null; + + GrExpression qualifier = invoked.getQualifierExpression(); + if (qualifier == null) { + // An unqualified call from within the domain class itself. + PsiClass containingClass = PsiTreeUtil.getParentOfType(call, PsiClass.class); + return GrailsArtifact.DOMAIN.isInstance(containingClass) ? containingClass : null; + } + + if (qualifier instanceof GrReferenceExpression qualifierRef && qualifierRef.resolve() instanceof PsiClass qualifierClass) { + return GrailsArtifact.DOMAIN.isInstance(qualifierClass) ? qualifierClass : null; + } + + // Composing an existing query: criteria.where { ... } + return DetachedCriteriaUtil.getDomainClassByDetachedCriteriaExpression(qualifier.getType()); Review Comment: This misses a criteria held in a method parameter or a field. `getDomainClassByDetachedCriteriaExpression` only accepts a `PsiImmediateClassType`, which is what an inferred type is, but a declared `DetachedCriteria<Person>` is a `PsiClassReferenceType`. Both of these still report `Cannot resolve symbol 'age'` under `@CompileStatic`: ```groovy def find(DetachedCriteria<Person> q) { q.where { age > 1 } } ``` ```groovy DetachedCriteria<Person> base = Person.where { active == true } def find() { base.where { age > 1 } } ``` GORM transforms both (the `var.getType()` generics branch in `DetachedCriteriaTransformer#visitMethodCallExpression`). The composed query in `testCompileStaticWhereQueryHasNoErrors` only passes because a local variable's type is narrowed to its initializer's. Accepting any `PsiClassType` in the helper fixes it: ```java if (!(type instanceof PsiClassType classType)) return null; PsiClass detachedCriteriaClass = classType.resolve(); if (detachedCriteriaClass == null || !DETACHED_CRITERIA_CLASS.equals(detachedCriteriaClass.getQualifiedName())) { return null; } PsiType[] parameters = classType.getParameters(); ``` With that change both cases resolve, and `GormDetachedCriteriaTest` and `GormWhereQueryTest` still pass. The helper's other two callers (`DetachedCriteriaMemberProvider`, `GormDynamicFinderCompletionProvider`) gain the same support for dynamic finders on declared types. Please add a test covering the parameter and field cases. ########## plugin/src/test/java/org/apache/grails/intellij/plugin/domain/GormWhereQueryTest.java: ########## @@ -0,0 +1,241 @@ +/* + * 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 + * + * https://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.apache.grails.intellij.plugin.domain; + +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.testFramework.UsefulTestCase; +import org.apache.grails.intellij.lib.testFramework.GrailsTestCase; +import org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GrUnresolvedAccessInspection; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; + +/** + * Where queries ({@code Person.where { active == true }}) refer to the domain properties by their bare names. The + * GORM 5+ {@code GormEntity} trait only gives the closure a raw {@code DetachedCriteria} delegate, so those names + * are resolved by WhereQueryClosureMemberContributor. The GORM the other tests run against is older than that, + * hence the stubs below. + */ +public class GormWhereQueryTest extends GrailsTestCase { + private PsiFile myDomainFile; + + /** GormTraitContributor only picks GormEntity when {@code org.hibernate.Hibernate} is on the classpath. */ + @Override + protected boolean needHibernate() { + return true; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + myFixture.addFileToProject("src/groovy/grails/gorm/DetachedCriteria.groovy", """ + package grails.gorm + + class DetachedCriteria<T> { + DetachedCriteria(Class<T> targetClass) {} + DetachedCriteria<T> build(@DelegatesTo(DetachedCriteria) Closure callable) { this } + DetachedCriteria<T> where(@DelegatesTo(DetachedCriteria) Closure callable) { this } + DetachedCriteria<T> eq(String propertyName, Object value) { this } + List<T> list(Map args) { null } + } + """); + + // The Groovy the tests run against predates @CompileStatic; the Groovy plugin keys off the annotation name only. + myFixture.addFileToProject("src/java/groovy/transform/CompileStatic.java", """ + package groovy.transform; + + public @interface CompileStatic { + } + """); + + // GormVersion.IS_5 is the lowest version GormTraitContributor injects the trait for. + myFixture.addFileToProject("src/java/grails/gorm/annotation/Entity.java", """ + package grails.gorm.annotation; + + public @interface Entity { + } + """); + + // #CHECK# org.grails.datastore.gorm.GormEntity + myFixture.addFileToProject("src/groovy/org/grails/datastore/gorm/GormEntity.groovy", """ + package org.grails.datastore.gorm + + import grails.gorm.DetachedCriteria + + trait GormEntity<D> { + static DetachedCriteria<D> where(@DelegatesTo(DetachedCriteria) Closure callable) { null } + static DetachedCriteria<D> whereAny(@DelegatesTo(DetachedCriteria) Closure callable) { null } + static D find(@DelegatesTo(DetachedCriteria) Closure callable) { null } + static List<D> findAll(@DelegatesTo(DetachedCriteria) Closure callable) { null } + } + """); + + myDomainFile = addDomain(""" + + class Pessoa { Review Comment: Nit: the rest of the test suite uses English identifiers. Could you rename `Pessoa`/`nome`/`idade`/`ativo`/`buscar…` and the rest to English (e.g. `Person`/`name`/`age`/`active`) so these read like the other tests? ########## plugin/src/main/java/org/apache/grails/intellij/plugin/references/domain/detachedCriteria/WhereQueryClosureMemberContributor.java: ########## @@ -0,0 +1,143 @@ +/* + * 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 + * + * https://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.apache.grails.intellij.plugin.references.domain.detachedCriteria; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.ResolveState; +import com.intellij.psi.scope.ElementClassHint; +import com.intellij.psi.scope.PsiScopeProcessor; +import com.intellij.psi.util.PsiTreeUtil; +import org.apache.grails.intellij.plugin.references.domain.DomainDescriptor; +import org.apache.grails.intellij.plugin.util.GrailsArtifact; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; +import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils; +import org.jetbrains.plugins.groovy.lang.resolve.ClosureMemberContributor; +import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; + +import java.util.Set; + +/** + * Resolves the bare property names of a GORM where query ({@code Person.where { active == true && age >= 18 }}) + * to the persistent properties of the queried domain class. + * <p> + * The GORM 5+ {@code GormEntity} trait declares {@code where(@DelegatesTo(DetachedCriteria) Closure)}: the delegate + * is a raw {@code DetachedCriteria}, which has no such properties, because GORM rewrites the closure at compile time + * (DetachedCriteriaTransformer) into criteria calls. Without this contributor the properties stay unresolved, which + * {@code @CompileStatic}/{@code @GrailsCompileStatic} code reports as an error although it compiles. + */ +final class WhereQueryClosureMemberContributor extends ClosureMemberContributor { + + // See DetachedCriteriaTransformer: the methods whose closure argument is transformed into a where query. + private static final Set<String> WHERE_METHODS = Set.of("where", "whereAny", "whereLazy", "find", "findAll"); + + private static final Set<String> IMPLICIT_PROPERTIES = Set.of("id", "version"); + + @Override + protected void processMembers(@NotNull GrClosableBlock closure, + @NotNull PsiScopeProcessor processor, + @NotNull PsiElement place, + @NotNull ResolveState state) { + String nameHint = ResolveUtil.getNameHint(processor); + if (nameHint == null) return; Review Comment: Returning here when there's no name hint means completion never sees the domain properties: `Person.where { ag<caret> }` doesn't offer `age`. `CriteriaClosureMemberContributor` handles the `nameHint == null` case by iterating its candidates. Doing the same here (the persistent properties plus `id`/`version`, each through its getter or readable field) would round the feature out. Fine as a follow-up if you'd rather keep this PR focused. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
