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
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ public class GroovyLanguageServer extends AbstractInProcessLanguageServer {
private static final Pattern IMPORT = Pattern.compile(
"^\\s*import\\s+(static\\s+)?([\\w$.]*)$");

/**
* A declaration's keyword, e.g. "class " or "def ": what follows is the
* name of the new type, method or variable.
*/
private static final Pattern DECLARATION = Pattern.compile(
"(?<![\\w$.@])(def|class|interface|@interface|enum|trait|record)\\s+$");

/** The identifier (possibly empty) being typed at the caret. */
private static final Pattern IDENTIFIER = Pattern.compile("[\\w$]*$");

Expand Down Expand Up @@ -157,6 +164,11 @@ protected CompletionList complete(final Document doc, final int caret) {
.isEmpty() || Character.isDigit(prefix.charAt(0)));
final boolean member = before.trim().endsWith(".") && !before.trim()
.endsWith("..") && !decimal;
if (!member && DECLARATION.matcher(before).find()) {
// A name being declared, e.g. "class Fo" or "def fo": it's new, so
// there is nothing to complete it with.
return list(doc, caret, caret, none);
}
// If it's not a member, there are two cases with less work to do:
if (!member && prefix.isEmpty()) {
// Nothing typed yet: only a call's arguments are worth offering, e.g.
Expand All @@ -181,6 +193,8 @@ protected CompletionList complete(final Document doc, final int caret) {
if (member) items.addAll(memberCompletions(ast, before, prefix));
else {
items.addAll(variableCompletions(ast.variablesAtCaret(), prefix));
items.addAll(functionCompletions(functionsAtCaret(ast, text,
replaceStart, caret), prefix));
items.addAll(keywordCompletions(prefix));
items.addAll(classCompletions(doc, prefix));
}
Expand Down Expand Up @@ -450,28 +464,38 @@ private List<CompletionItem> scriptClassMembers(
final boolean staticOnly)
{
final List<CompletionItem> out = new ArrayList<>();
for (final PropertyNode p : type.getProperties()) {
if (staticOnly && !p.isStatic() || !matches(p.getName(), prefix)) {
continue;
// Its properties and public fields, and those it inherits.
final Set<String> names = new HashSet<>();
for (ClassNode t = type; t != null; t = t.getSuperClass() == null ? null
: t.getSuperClass().redirect())
{
final List<PropertyNode> properties;
final List<FieldNode> fields;
try {
properties = t.getProperties();
fields = t.getFields();
}
catch (final RuntimeException | LinkageError exc) {
break; // NB: An unloadable class; its members are unknown.
}
for (final PropertyNode p : properties) {
if (staticOnly && !p.isStatic() || !matches(p.getName(), prefix) ||
!names.add(p.getName())) continue;
out.add(field(p.getName(), p.getType().toString(false)));
}
for (final FieldNode f : fields) {
if (!f.isPublic() || f.isSynthetic() || staticOnly && !f.isStatic() ||
!matches(f.getName(), prefix) || !names.add(f.getName())) continue;
out.add(field(f.getName(), f.getType().toString(false)));
}
out.add(field(p.getName(), p.getType().toString(false)));
}
for (final FieldNode f : type.getFields()) {
if (!f.isPublic() || f.isSynthetic() || staticOnly && !f.isStatic() ||
!matches(f.getName(), prefix) || type.getProperty(f
.getName()) != null) continue;
out.add(field(f.getName(), f.getType().toString(false)));
}
for (final Overload m : scriptMethods(type, prefix, staticOnly, false)) {
// Its public methods, and those it inherits.
for (final Overload m : classMethods(ast, type, prefix, staticOnly,
false))
{
out.add(m.toItem());
}
final List<CompletionItem> sorted = sorted(out);
// Plus what it inherits from (compiled) superclasses.
final Class<?> superclass = ast.toClass(type.getSuperClass());
if (superclass != null && superclass != Object.class) {
sorted.addAll(sorted(members(superclass, prefix, staticOnly)));
}
return sorted;
return sorted(out);
}

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

/** Methods of a class defined in the script: by prefix, or exact name. */
private static List<Overload> scriptMethods(final ClassNode type,
final String name, final boolean staticOnly, final boolean exact)
/**
* Public methods of a class defined in the script, including those it
* inherits (see {@link TypedAST#methodsOf}): by prefix, or exact name.
*/
private static List<Overload> classMethods(final TypedAST ast,
final ClassNode type, final String name, final boolean staticOnly,
final boolean exact)
{
final List<Overload> out = new ArrayList<>();
for (final MethodNode m : type.getMethods()) {
if (!m.isPublic() || m.isSynthetic() || staticOnly && !m.isStatic() || m
.getName().contains("$")) continue;
for (final MethodNode m : ast.methodsOf(type)) {
if (!m.isPublic() || staticOnly && !m.isStatic()) continue;
if (exact ? !m.getName().equals(name) : !matches(m.getName(), name)) {
continue;
}
Expand Down Expand Up @@ -557,6 +584,39 @@ private static List<CompletionItem> variableCompletions(
return out;
}

/**
* The {@link MethodNode}s callable without a receiver at the caret (see
* {@link TypedAST#methodsAtCaret()}): as the whole script declares them,
* with the caret marked, if it parses (as they may be declared after the
* caret); else as declared before the caret.
*/
private List<MethodNode> functionsAtCaret(final TypedAST before,
final String text, final int replaceStart, final int caret)
{
// NB: A newline ends the text, in case it ends with a line comment.
final String code = TypedAST.closeBrackets(TypedAST.markCaret(text
.substring(0, replaceStart)) + text.substring(caret) + "\n");
if (code != null) {
final TypedAST whole = TypedAST.of(code, loader());
if (whole.isParsed()) return whole.methodsAtCaret();
}
return before.methodsAtCaret();
}

private static List<CompletionItem> functionCompletions(
final List<MethodNode> functions, final String prefix)
{
final List<CompletionItem> out = new ArrayList<>();
for (final MethodNode m : functions) {
// NB: An exact match is kept: its snippet still adds the call's
// parentheses and arguments.
if (!matches(m.getName(), prefix)) continue;
out.add(methodNode(m.getName(), m).detail(m.getTypeDescriptor())
.toItem());
}
return sorted(out);
}

/** Groovy's keywords */
private static Set<String> keywords() {
// NB: The lexer literals don't contain primitives - we add those ourselves
Expand Down Expand Up @@ -680,9 +740,10 @@ else if (type.isPrimaryClassNode()) {
final String name = e.getMethodAsString();
if (name == null) return out;
if (e.isImplicitThis()) {
// A function defined in the script, or a GDK method such as println.
for (final MethodNode m : ast.scriptMethods(name)) {
out.add(methodNode(name, m));
// A method callable at the caret, e.g. a function the script defines;
// or a GDK method such as println.
for (final MethodNode m : ast.methodsAtCaret()) {
if (m.getName().equals(name)) out.add(methodNode(name, m));
}
out.addAll(named(gdkMethods(Object.class, name), name));
return out;
Expand All @@ -692,7 +753,7 @@ else if (type.isPrimaryClassNode()) {
if (type == null) return out;
final boolean staticOnly = receiver instanceof ClassExpression;
if (type.redirect().isPrimaryClassNode()) {
return scriptMethods(type.redirect(), name, staticOnly, true);
return classMethods(ast, type.redirect(), name, staticOnly, true);
}
final Class<?> c = Types.box(ast.toClass(type));
if (c == null) return out;
Expand Down
167 changes: 142 additions & 25 deletions scijava-lsp-groovy/src/main/java/org/scijava/lsp/groovy/TypedAST.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,14 @@
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import groovy.lang.Script;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
import org.codehaus.groovy.ast.ClassNode;
Expand Down Expand Up @@ -623,14 +627,100 @@ String typeName(final Expression e) {
return name == null ? c.getName() : name;
}

/** Gets the script's own methods (e.g. {@code def area(w, h)}) by name. */
List<MethodNode> scriptMethods(final String name) {
final List<MethodNode> methods = new ArrayList<>();
if (module == null) return methods;
for (final ClassNode c : module.getClasses()) {
if (c.isScript()) methods.addAll(c.getMethods(name));
/**
* Gets the methods callable without a receiver (e.g. {@code area(3, 4)}) at
* the caret.
*/
List<MethodNode> methodsAtCaret() {
if (module == null) return Collections.emptyList();
final ClassNode enclosing = caretClass();
if (enclosing == null) return module.getMethods();
final List<MethodNode> out = new ArrayList<>();
// NB: An inner class's method hides an outer class's of the same
// signature.
final Set<String> signatures = new HashSet<>();
for (ClassNode c = enclosing; c != null; c = c.getOuterClass()) {
for (final MethodNode m : methodsOf(c)) {
if (signatures.add(signature(m))) out.add(m);
}
}
return out;
}

/**
* Gets the methods of a type, namely:
* <ol>
* <li>those it declares</li>
* <li>public members inherited from superclasses</li>
* </ol>
* but not:
* <ol>
* <li>superclass members overridden by subclasses</li>
* <li>synthetic methods</li>
* </ol>
*/
List<MethodNode> methodsOf(final ClassNode type) {
final List<MethodNode> out = new ArrayList<>();
final Set<String> signatures = new HashSet<>();
final Set<ClassNode> visited = new HashSet<>();
boolean own = true;
for (ClassNode t = type.redirect(); t != null && visited.add(t); t =
superclass(t))
{
final List<MethodNode> methods;
try {
methods = t.getMethods();
}
catch (final RuntimeException | LinkageError exc) {
break; // NB: An unloadable class; its methods are unknown.
}
// NB: The script class's methods include those Groovy generates for it
// (e.g. run and main); the module has only those the script declares.
final Set<MethodNode> declared = Collections.newSetFromMap(
new IdentityHashMap<>());
declared.addAll(isScriptClass(t) ? module.getMethods() : methods);
for (final MethodNode m : methods) {
if (m.getName().startsWith("<") || m.isSynthetic() || m.getName()
.contains("$") || !own && m.isPrivate()) continue;
if (signatures.add(signature(m)) && declared.contains(m)) out.add(m);
}
own = false;
}
return out;
}

/**
* True iff the type is the class Groovy generates for the script, i.e. the
* one whose {@code run} method holds the script's top-level code. NB: Not
* {@link ClassNode#isScript()}, which is also true of
* {@code groovy.lang.Script} and its other subclasses.
*/
private boolean isScriptClass(final ClassNode type) {
if (module == null || !type.isPrimaryClassNode()) return false;
for (final MethodNode m : type.getDeclaredMethods("run")) {
if (m.isScriptBody()) return true;
}
return false;
}

/** A type's superclass, or null if it has none or it is unknown. */
private static ClassNode superclass(final ClassNode type) {
try {
final ClassNode s = type.getSuperClass();
return s == null ? null : s.redirect();
}
catch (final RuntimeException | LinkageError exc) {
return null;
}
return methods;
}

/** A method's name and parameter types, e.g. {@code add,java.lang.Object}. */
private static String signature(final MethodNode m) {
final StringBuilder signature = new StringBuilder(m.getName());
for (final Parameter p : m.getParameters()) {
signature.append(',').append(p.getType().getName());
}
return signature.toString();
}

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

/** Gets the node of the caret marker. */
private ASTNode caretNode() {
final ASTNode[] found = { null };
visit(new Visitor() {
final CaretFinder finder = new CaretFinder();
visit(finder);
return finder.found;
}

@Override
public void visitVariableExpression(final VariableExpression e) {
if (CARET.equals(e.getName())) found[0] = e;
super.visitVariableExpression(e);
/**
* Gets the class whose code contains the caret: the script class (for the
* script's body and functions), or a class the script declares; or null if
* the caret is not found.
*/
private ClassNode caretClass() {
if (module == null) return null;
// NB: A class's visit skips the classes nested in it, so the first class
// found containing the caret is the innermost.
for (final ClassNode c : module.getClasses()) {
final CaretFinder finder = new CaretFinder();
try {
finder.visitClass(c);
}

@Override
public void visitPropertyExpression(final PropertyExpression e) {
if (CARET.equals(e.getPropertyAsString())) found[0] = e.getProperty();
super.visitPropertyExpression(e);
catch (final RuntimeException exc) {
continue; // NB: Malformed tree; skip this class.
}
if (finder.found != null) return c;
}
return null;
}

@Override
public void visitMethodCallExpression(final MethodCallExpression e) {
if (CARET.equals(e.getMethodAsString())) found[0] = e.getMethod();
super.visitMethodCallExpression(e);
}
});
return found[0];
/** Finds the node of the caret marker. */
private class CaretFinder extends Visitor {

private ASTNode found;

@Override
public void visitVariableExpression(final VariableExpression e) {
if (CARET.equals(e.getName())) found = e;
super.visitVariableExpression(e);
}

@Override
public void visitPropertyExpression(final PropertyExpression e) {
if (CARET.equals(e.getPropertyAsString())) found = e.getProperty();
super.visitPropertyExpression(e);
}

@Override
public void visitMethodCallExpression(final MethodCallExpression e) {
if (CARET.equals(e.getMethodAsString())) found = e.getMethod();
super.visitMethodCallExpression(e);
}
}

/** Visits every class (including the script itself) of the source. */
Expand Down
Loading
Loading