Skip to content

Commit b54f62c

Browse files
gselzerclaude
andcommitted
lsp-groovy: complete the methods visible at the caret
A script's functions are methods of the script class, so the classes it declares cannot call them. Rather than offering them everywhere, offer the methods callable without a receiver at the caret: those of the class whose code contains it, of the classes it is nested in, and those they inherit from their superclasses (declared in the script or compiled, Object and groovy.lang.Script included). The methods Groovy generates for the script class (run, main) are still left out. Member completion and signature help on instances of classes defined in the script now include inherited members too, however far up. Also, offer nothing for a name being declared (after def, class, interface, enum, trait, record or @interface). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 82a2056 commit b54f62c

3 files changed

Lines changed: 319 additions & 62 deletions

File tree

‎scijava-lsp-groovy/src/main/java/org/scijava/lsp/groovy/GroovyLanguageServer.java‎

Lines changed: 61 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ public class GroovyLanguageServer extends AbstractInProcessLanguageServer {
100100
private static final Pattern IMPORT = Pattern.compile(
101101
"^\\s*import\\s+(static\\s+)?([\\w$.]*)$");
102102

103+
/**
104+
* A declaration's keyword, e.g. "class " or "def ": what follows is the
105+
* name of the new type, method or variable.
106+
*/
107+
private static final Pattern DECLARATION = Pattern.compile(
108+
"(?<![\\w$.@])(def|class|interface|@interface|enum|trait|record)\\s+$");
109+
103110
/** The identifier (possibly empty) being typed at the caret. */
104111
private static final Pattern IDENTIFIER = Pattern.compile("[\\w$]*$");
105112

@@ -157,6 +164,11 @@ protected CompletionList complete(final Document doc, final int caret) {
157164
.isEmpty() || Character.isDigit(prefix.charAt(0)));
158165
final boolean member = before.trim().endsWith(".") && !before.trim()
159166
.endsWith("..") && !decimal;
167+
if (!member && DECLARATION.matcher(before).find()) {
168+
// A name being declared, e.g. "class Fo" or "def fo": it's new, so
169+
// there is nothing to complete it with.
170+
return list(doc, caret, caret, none);
171+
}
160172
// If it's not a member, there are two cases with less work to do:
161173
if (!member && prefix.isEmpty()) {
162174
// Nothing typed yet: only a call's arguments are worth offering, e.g.
@@ -181,7 +193,7 @@ protected CompletionList complete(final Document doc, final int caret) {
181193
if (member) items.addAll(memberCompletions(ast, before, prefix));
182194
else {
183195
items.addAll(variableCompletions(ast.variablesAtCaret(), prefix));
184-
items.addAll(functionCompletions(scriptFunctions(ast, text,
196+
items.addAll(functionCompletions(functionsAtCaret(ast, text,
185197
replaceStart, caret), prefix));
186198
items.addAll(keywordCompletions(prefix));
187199
items.addAll(classCompletions(doc, prefix));
@@ -452,28 +464,38 @@ private List<CompletionItem> scriptClassMembers(
452464
final boolean staticOnly)
453465
{
454466
final List<CompletionItem> out = new ArrayList<>();
455-
for (final PropertyNode p : type.getProperties()) {
456-
if (staticOnly && !p.isStatic() || !matches(p.getName(), prefix)) {
457-
continue;
467+
// Its properties and public fields, and those it inherits.
468+
final Set<String> names = new HashSet<>();
469+
for (ClassNode t = type; t != null; t = t.getSuperClass() == null ? null
470+
: t.getSuperClass().redirect())
471+
{
472+
final List<PropertyNode> properties;
473+
final List<FieldNode> fields;
474+
try {
475+
properties = t.getProperties();
476+
fields = t.getFields();
477+
}
478+
catch (final RuntimeException | LinkageError exc) {
479+
break; // NB: An unloadable class; its members are unknown.
480+
}
481+
for (final PropertyNode p : properties) {
482+
if (staticOnly && !p.isStatic() || !matches(p.getName(), prefix) ||
483+
!names.add(p.getName())) continue;
484+
out.add(field(p.getName(), p.getType().toString(false)));
485+
}
486+
for (final FieldNode f : fields) {
487+
if (!f.isPublic() || f.isSynthetic() || staticOnly && !f.isStatic() ||
488+
!matches(f.getName(), prefix) || !names.add(f.getName())) continue;
489+
out.add(field(f.getName(), f.getType().toString(false)));
458490
}
459-
out.add(field(p.getName(), p.getType().toString(false)));
460-
}
461-
for (final FieldNode f : type.getFields()) {
462-
if (!f.isPublic() || f.isSynthetic() || staticOnly && !f.isStatic() ||
463-
!matches(f.getName(), prefix) || type.getProperty(f
464-
.getName()) != null) continue;
465-
out.add(field(f.getName(), f.getType().toString(false)));
466491
}
467-
for (final Overload m : classMethods(type, prefix, staticOnly, false)) {
492+
// Its public methods, and those it inherits.
493+
for (final Overload m : classMethods(ast, type, prefix, staticOnly,
494+
false))
495+
{
468496
out.add(m.toItem());
469497
}
470-
final List<CompletionItem> sorted = sorted(out);
471-
// Plus what it inherits from (compiled) superclasses.
472-
final Class<?> superclass = ast.toClass(type.getSuperClass());
473-
if (superclass != null && superclass != Object.class) {
474-
sorted.addAll(sorted(members(superclass, prefix, staticOnly)));
475-
}
476-
return sorted;
498+
return sorted(out);
477499
}
478500

479501
/** A compiled class's members, as reached through it or an instance. */
@@ -484,14 +506,17 @@ private static List<CompletionItem> members(final Class<?> c,
484506
: CompletionItems.instanceMembers(c, prefix);
485507
}
486508

487-
/** Methods of a class defined in the script: by prefix, or exact name. */
488-
private static List<Overload> classMethods(final ClassNode type,
489-
final String name, final boolean staticOnly, final boolean exact)
509+
/**
510+
* Public methods of a class defined in the script, including those it
511+
* inherits (see {@link TypedAST#methodsOf}): by prefix, or exact name.
512+
*/
513+
private static List<Overload> classMethods(final TypedAST ast,
514+
final ClassNode type, final String name, final boolean staticOnly,
515+
final boolean exact)
490516
{
491517
final List<Overload> out = new ArrayList<>();
492-
for (final MethodNode m : type.getMethods()) {
493-
if (!m.isPublic() || m.isSynthetic() || staticOnly && !m.isStatic() || m
494-
.getName().contains("$")) continue;
518+
for (final MethodNode m : ast.methodsOf(type)) {
519+
if (!m.isPublic() || staticOnly && !m.isStatic()) continue;
495520
if (exact ? !m.getName().equals(name) : !matches(m.getName(), name)) {
496521
continue;
497522
}
@@ -560,20 +585,22 @@ private static List<CompletionItem> variableCompletions(
560585
}
561586

562587
/**
563-
* {@link MethodNode}s defined in a script: in the whole script, with the
564-
* caret marked, if it parses; else before the caret.
588+
* The {@link MethodNode}s callable without a receiver at the caret (see
589+
* {@link TypedAST#methodsAtCaret()}): as the whole script declares them,
590+
* with the caret marked, if it parses (as they may be declared after the
591+
* caret); else as declared before the caret.
565592
*/
566-
private List<MethodNode> scriptFunctions(final TypedAST before,
593+
private List<MethodNode> functionsAtCaret(final TypedAST before,
567594
final String text, final int replaceStart, final int caret)
568595
{
569596
// NB: A newline ends the text, in case it ends with a line comment.
570597
final String code = TypedAST.closeBrackets(TypedAST.markCaret(text
571598
.substring(0, replaceStart)) + text.substring(caret) + "\n");
572599
if (code != null) {
573600
final TypedAST whole = TypedAST.of(code, loader());
574-
if (whole.isParsed()) return whole.scriptMethods();
601+
if (whole.isParsed()) return whole.methodsAtCaret();
575602
}
576-
return before.scriptMethods();
603+
return before.methodsAtCaret();
577604
}
578605

579606
private static List<CompletionItem> functionCompletions(
@@ -713,8 +740,9 @@ else if (type.isPrimaryClassNode()) {
713740
final String name = e.getMethodAsString();
714741
if (name == null) return out;
715742
if (e.isImplicitThis()) {
716-
// A function defined in the script, or a GDK method such as println.
717-
for (final MethodNode m : ast.scriptMethods()) {
743+
// A method callable at the caret, e.g. a function the script defines;
744+
// or a GDK method such as println.
745+
for (final MethodNode m : ast.methodsAtCaret()) {
718746
if (m.getName().equals(name)) out.add(methodNode(name, m));
719747
}
720748
out.addAll(named(gdkMethods(Object.class, name), name));
@@ -725,7 +753,7 @@ else if (type.isPrimaryClassNode()) {
725753
if (type == null) return out;
726754
final boolean staticOnly = receiver instanceof ClassExpression;
727755
if (type.redirect().isPrimaryClassNode()) {
728-
return classMethods(type.redirect(), name, staticOnly, true);
756+
return classMethods(ast, type.redirect(), name, staticOnly, true);
729757
}
730758
final Class<?> c = Types.box(ast.toClass(type));
731759
if (c == null) return out;

‎scijava-lsp-groovy/src/main/java/org/scijava/lsp/groovy/TypedAST.java‎

Lines changed: 141 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,14 @@
3737
import java.util.Collections;
3838
import java.util.Deque;
3939
import java.util.HashMap;
40+
import java.util.HashSet;
41+
import java.util.IdentityHashMap;
4042
import java.util.LinkedHashMap;
4143
import java.util.List;
4244
import java.util.Map;
45+
import java.util.Set;
4346

47+
import groovy.lang.Script;
4448
import org.codehaus.groovy.ast.ASTNode;
4549
import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
4650
import org.codehaus.groovy.ast.ClassNode;
@@ -624,12 +628,99 @@ String typeName(final Expression e) {
624628
}
625629

626630
/**
627-
* Gets all the methods the script itself declares (e.g.
628-
* {@code def area(w, h)}), leaving out those Groovy generates for it, such
629-
* as {@code run} and {@code main}.
631+
* Gets the methods callable without a receiver (e.g. {@code area(3, 4)}) at
632+
* the caret.
630633
*/
631-
List<MethodNode> scriptMethods() {
632-
return module == null ? Collections.emptyList() : module.getMethods();
634+
List<MethodNode> methodsAtCaret() {
635+
if (module == null) return Collections.emptyList();
636+
final ClassNode enclosing = caretClass();
637+
if (enclosing == null) return module.getMethods();
638+
final List<MethodNode> out = new ArrayList<>();
639+
// NB: An inner class's method hides an outer class's of the same
640+
// signature.
641+
final Set<String> signatures = new HashSet<>();
642+
for (ClassNode c = enclosing; c != null; c = c.getOuterClass()) {
643+
for (final MethodNode m : methodsOf(c)) {
644+
if (signatures.add(signature(m))) out.add(m);
645+
}
646+
}
647+
return out;
648+
}
649+
650+
/**
651+
* Gets the methods of a type, namely:
652+
* <ol>
653+
* <li>those it declares</li>
654+
* <li>public members inherited from superclasses</li>
655+
* </ol>
656+
* but not:
657+
* <ol>
658+
* <li>superclass members overridden by subclasses</li>
659+
* <li>synthetic methods</li>
660+
* </ol>
661+
*/
662+
List<MethodNode> methodsOf(final ClassNode type) {
663+
final List<MethodNode> out = new ArrayList<>();
664+
final Set<String> signatures = new HashSet<>();
665+
final Set<ClassNode> visited = new HashSet<>();
666+
boolean own = true;
667+
for (ClassNode t = type.redirect(); t != null && visited.add(t); t =
668+
superclass(t))
669+
{
670+
final List<MethodNode> methods;
671+
try {
672+
methods = t.getMethods();
673+
}
674+
catch (final RuntimeException | LinkageError exc) {
675+
break; // NB: An unloadable class; its methods are unknown.
676+
}
677+
// NB: The script class's methods include those Groovy generates for it
678+
// (e.g. run and main); the module has only those the script declares.
679+
final Set<MethodNode> declared = Collections.newSetFromMap(
680+
new IdentityHashMap<>());
681+
declared.addAll(isScriptClass(t) ? module.getMethods() : methods);
682+
for (final MethodNode m : methods) {
683+
if (m.getName().startsWith("<") || m.isSynthetic() || m.getName()
684+
.contains("$") || !own && m.isPrivate()) continue;
685+
if (signatures.add(signature(m)) && declared.contains(m)) out.add(m);
686+
}
687+
own = false;
688+
}
689+
return out;
690+
}
691+
692+
/**
693+
* True iff the type is the class Groovy generates for the script, i.e. the
694+
* one whose {@code run} method holds the script's top-level code. NB: Not
695+
* {@link ClassNode#isScript()}, which is also true of
696+
* {@code groovy.lang.Script} and its other subclasses.
697+
*/
698+
private boolean isScriptClass(final ClassNode type) {
699+
if (module == null || !type.isPrimaryClassNode()) return false;
700+
for (final MethodNode m : type.getDeclaredMethods("run")) {
701+
if (m.isScriptBody()) return true;
702+
}
703+
return false;
704+
}
705+
706+
/** A type's superclass, or null if it has none or it is unknown. */
707+
private static ClassNode superclass(final ClassNode type) {
708+
try {
709+
final ClassNode s = type.getSuperClass();
710+
return s == null ? null : s.redirect();
711+
}
712+
catch (final RuntimeException | LinkageError exc) {
713+
return null;
714+
}
715+
}
716+
717+
/** A method's name and parameter types, e.g. {@code add,java.lang.Object}. */
718+
private static String signature(final MethodNode m) {
719+
final StringBuilder signature = new StringBuilder(m.getName());
720+
for (final Parameter p : m.getParameters()) {
721+
signature.append(',').append(p.getType().getName());
722+
}
723+
return signature.toString();
633724
}
634725

635726
/** True iff the expression is, or contains, the caret marker. */
@@ -700,28 +791,55 @@ static Class<?> load(final String name, final ClassLoader loader) {
700791

701792
/** Gets the node of the caret marker. */
702793
private ASTNode caretNode() {
703-
final ASTNode[] found = { null };
704-
visit(new Visitor() {
794+
final CaretFinder finder = new CaretFinder();
795+
visit(finder);
796+
return finder.found;
797+
}
705798

706-
@Override
707-
public void visitVariableExpression(final VariableExpression e) {
708-
if (CARET.equals(e.getName())) found[0] = e;
709-
super.visitVariableExpression(e);
799+
/**
800+
* Gets the class whose code contains the caret: the script class (for the
801+
* script's body and functions), or a class the script declares; or null if
802+
* the caret is not found.
803+
*/
804+
private ClassNode caretClass() {
805+
if (module == null) return null;
806+
// NB: A class's visit skips the classes nested in it, so the first class
807+
// found containing the caret is the innermost.
808+
for (final ClassNode c : module.getClasses()) {
809+
final CaretFinder finder = new CaretFinder();
810+
try {
811+
finder.visitClass(c);
710812
}
711-
712-
@Override
713-
public void visitPropertyExpression(final PropertyExpression e) {
714-
if (CARET.equals(e.getPropertyAsString())) found[0] = e.getProperty();
715-
super.visitPropertyExpression(e);
813+
catch (final RuntimeException exc) {
814+
continue; // NB: Malformed tree; skip this class.
716815
}
816+
if (finder.found != null) return c;
817+
}
818+
return null;
819+
}
717820

718-
@Override
719-
public void visitMethodCallExpression(final MethodCallExpression e) {
720-
if (CARET.equals(e.getMethodAsString())) found[0] = e.getMethod();
721-
super.visitMethodCallExpression(e);
722-
}
723-
});
724-
return found[0];
821+
/** Finds the node of the caret marker. */
822+
private class CaretFinder extends Visitor {
823+
824+
private ASTNode found;
825+
826+
@Override
827+
public void visitVariableExpression(final VariableExpression e) {
828+
if (CARET.equals(e.getName())) found = e;
829+
super.visitVariableExpression(e);
830+
}
831+
832+
@Override
833+
public void visitPropertyExpression(final PropertyExpression e) {
834+
if (CARET.equals(e.getPropertyAsString())) found = e.getProperty();
835+
super.visitPropertyExpression(e);
836+
}
837+
838+
@Override
839+
public void visitMethodCallExpression(final MethodCallExpression e) {
840+
if (CARET.equals(e.getMethodAsString())) found = e.getMethod();
841+
super.visitMethodCallExpression(e);
842+
}
725843
}
726844

727845
/** Visits every class (including the script itself) of the source. */

0 commit comments

Comments
 (0)