Improve autocomplete for method reference contexts

- trigger completion after :: and detect method-reference receiver chains

- restrict suggestions to methods (plus constructor refs) in method-reference mode

- insert method names without parentheses when completing method references
This commit is contained in:
bigguy345 committed 2026-02-18 05:21:55 +02:00
1 parent e2b35d6d54
commit 430ff7c3a8
5 files changed
+326 -56

No files matched your search

@@ -85,15 +85,27 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
* Create from a Java MethodInfo.
*/
public static AutocompleteItem fromMethod(MethodInfo method) {
return fromMethod(method, false);
}
/**
* Create from a Java MethodInfo, optionally for method reference context.
* @param method The method info
* @param forMethodReference If true, insert text will NOT include parentheses
*/
public static AutocompleteItem fromMethod(MethodInfo method, boolean forMethodReference) {
String name = method.getName();
StringBuilder insertText = new StringBuilder(name);
insertText.append("(");
// Add placeholders for parameters if any
if (method.getParameterCount() > 0) {
// Just add () - user will fill in params
// For method references, don't add () since it's ::methodName not ::methodName()
if (!forMethodReference) {
insertText.append("(");
// Add placeholders for parameters if any
if (method.getParameterCount() > 0) {
// Just add () - user will fill in params
}
insertText.append(")");
}
insertText.append(")");
String returnType = method.getReturnType() != null ?
getName(method.getReturnType()) : "void";
@@ -208,7 +220,7 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
* Create from a JavaScript JSMethodInfo.
*/
public static AutocompleteItem fromJSMethod(JSMethodInfo method) {
return fromJSMethod(method, null, 0);
return fromJSMethod(method, null, 0, false);
}
/**
@@ -217,7 +229,7 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
* @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.)
*/
public static AutocompleteItem fromJSMethod(JSMethodInfo method, int inheritanceDepth) {
return fromJSMethod(method, null, inheritanceDepth);
return fromJSMethod(method, null, inheritanceDepth, false);
}
/**
@@ -227,10 +239,25 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
* @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.)
*/
public static AutocompleteItem fromJSMethod(JSMethodInfo method, TypeInfo contextType, int inheritanceDepth) {
return fromJSMethod(method, contextType, inheritanceDepth, false);
}
/**
* Create from a JavaScript JSMethodInfo with type parameter resolution for display.
* @param method The method info
* @param contextType The TypeInfo context for resolving type parameters (e.g., IPlayer to resolve T → EntityPlayerMP)
* @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.)
* @param forMethodReference If true, insert text will NOT include parentheses
*/
public static AutocompleteItem fromJSMethod(JSMethodInfo method, TypeInfo contextType, int inheritanceDepth, boolean forMethodReference) {
String name = method.getName();
StringBuilder insertText = new StringBuilder(name);
insertText.append("(");
insertText.append(")");
// For method references, don't add () since it's ::methodName not ::methodName()
if (!forMethodReference) {
insertText.append("(");
insertText.append(")");
}
// Build display name with resolved parameter types
StringBuilder displayName = new StringBuilder(name);
@@ -338,10 +365,27 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
public static AutocompleteItem fromSyntheticMethod(
SyntheticMethod method,
TypeInfo containingType) {
return fromSyntheticMethod(method, containingType, false);
}
/**
* Create from a synthetic method (e.g., Nashorn built-in like Java.type).
* @param method The synthetic method
* @param containingType The containing type info
* @param forMethodReference If true, insert text will NOT include parentheses
*/
public static AutocompleteItem fromSyntheticMethod(
SyntheticMethod method,
TypeInfo containingType,
boolean forMethodReference) {
String name = method.name;
StringBuilder insertText = new StringBuilder(name);
insertText.append("(");
insertText.append(")");
// For method references, don't add () since it's ::methodName not ::methodName()
if (!forMethodReference) {
insertText.append("(");
insertText.append(")");
}
// Build display name with parameters - use simple names for types
StringBuilder displayName = new StringBuilder(name);
@@ -177,6 +177,21 @@ public class AutocompleteManager {
return;
}
// Check if this completes a :: (method reference)
if (c == ':') {
// Normalize cursor position - some callers pass pre-insert position
int effectiveCursor = cursorPosition;
if (effectiveCursor >= 0 && effectiveCursor < text.length() && text.charAt(effectiveCursor) == c) {
effectiveCursor = effectiveCursor + 1;
}
// Check if the previous character is also :
if (effectiveCursor >= 2 && text.charAt(effectiveCursor - 2) == ':') {
triggerAfterMethodReference(text, effectiveCursor);
return;
}
}
// Check if we're typing an identifier
if (Character.isJavaIdentifierPart(c)) {
// GuiScriptTextArea passes a cursor position captured BEFORE insertion while `text`
@@ -324,7 +339,100 @@ public class AutocompleteManager {
prefixStartPosition = prefixStart;
currentPrefix = prefix;
showSuggestions(text, caretPos, prefix, prefixStartPosition, true, receiverExpr);
showSuggestions(text, caretPos, prefix, prefixStartPosition, true, receiverExpr, false);
}
/**
* Trigger autocomplete after :: is typed (method reference).
* Shows only method suggestions filtered for method references.
*/
private void triggerAfterMethodReference(String text, int cursorPosition) {
int doubleColonPos = cursorPosition - 2;
// Find the receiver expression before ::
String receiverExpr = findMethodRefReceiverExpression(text, doubleColonPos);
if (receiverExpr == null || receiverExpr.isEmpty()) return;
// Skip whitespace after :: when establishing prefix start position
int prefixStart = cursorPosition;
while (prefixStart < text.length() && Character.isWhitespace(text.charAt(prefixStart))) {
prefixStart++;
}
String prefix = "";
prefixStartPosition = prefixStart;
currentPrefix = prefix;
// Show suggestions filtered for methods only
showSuggestions(text, cursorPosition, prefix, prefixStart, true, receiverExpr, true);
}
/**
* Find the receiver expression before :: for method references.
* Similar to findReceiverExpression but stops at ::
*/
private String findMethodRefReceiverExpression(String text, int doubleColonPos) {
if (text == null || doubleColonPos <= 0) return "";
int pos = doubleColonPos - 1;
// Skip whitespace immediately left of ::
while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--;
if (pos < 0) return "";
int end = pos + 1;
// Walk left across a dotted receiver chain
while (pos >= 0) {
char c = text.charAt(pos);
if (Character.isWhitespace(c)) {
pos--;
continue;
}
if (c == ')') {
int open = findMatchingBackward(text, pos, '(', ')');
if (open < 0) break;
pos = open - 1;
continue;
}
if (c == ']') {
int open = findMatchingBackward(text, pos, '[', ']');
if (open < 0) break;
pos = open - 1;
continue;
}
if (Character.isJavaIdentifierPart(c)) {
// Consume identifier
while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--;
// If preceded by a dot, keep going
int checkPos = pos;
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) {
checkPos--;
}
if (checkPos >= 0 && text.charAt(checkPos) == '.') {
pos = checkPos - 1;
continue;
}
break;
}
// Anything else terminates the receiver
break;
}
int start = pos + 1;
if (start < 0) start = 0;
if (end > text.length()) end = text.length();
if (start >= end) return "";
String expr = text.substring(start, end).replaceAll("\\s+", " ").trim();
return expr;
}
/**
@@ -347,7 +455,7 @@ public class AutocompleteManager {
prefixStartPosition = prefixStart;
currentPrefix = prefix;
showSuggestions(text, cursorPosition, prefix, prefixStart, false, null);
showSuggestions(text, cursorPosition, prefix, prefixStart, false, null, false);
}
/**
@@ -370,17 +478,58 @@ public class AutocompleteManager {
currentPrefix = newPrefix;
// Check if this is a method reference context (after ::)
boolean isMethodReference = isAfterMethodReference(text, prefixStartPosition);
// Check if after dot (skipping whitespace)
int dotPos = findDotBeforeWhitespace(text, prefixStartPosition - 1);
boolean isMemberAccess = dotPos >= 0;
boolean isMemberAccess = dotPos >= 0 || isMethodReference;
String receiverExpr = null;
if (isMemberAccess) {
if (isMethodReference) {
// Find :: position
int doubleColonPos = findDoubleColonBefore(text, prefixStartPosition);
if (doubleColonPos >= 0) {
receiverExpr = findMethodRefReceiverExpression(text, doubleColonPos);
}
} else if (isMemberAccess) {
receiverExpr = findReceiverExpression(text, dotPos);
}
showSuggestions(text, cursorPosition, currentPrefix, prefixStartPosition,
isMemberAccess, receiverExpr);
isMemberAccess, receiverExpr, isMethodReference);
}
/**
* Check if position is after :: (method reference).
*/
private boolean isAfterMethodReference(String text, int pos) {
int checkPos = pos - 1;
// Skip whitespace
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) {
checkPos--;
}
// Check for ::
if (checkPos >= 1 && text.charAt(checkPos) == ':' && text.charAt(checkPos - 1) == ':') {
return true;
}
return false;
}
/**
* Find the position of :: before the given position.
*/
private int findDoubleColonBefore(String text, int pos) {
int checkPos = pos - 1;
// Skip whitespace
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) {
checkPos--;
}
// Check for ::
if (checkPos >= 1 && text.charAt(checkPos) == ':' && text.charAt(checkPos - 1) == ':') {
return checkPos - 1;
}
return -1;
}
// ==================== SUGGESTION LOGIC ====================
@@ -389,7 +538,8 @@ public class AutocompleteManager {
* Show autocomplete suggestions.
*/
private void showSuggestions(String text, int cursorPosition, String prefix,
int prefixStart, boolean isMemberAccess, String receiverExpr) {
int prefixStart, boolean isMemberAccess, String receiverExpr,
boolean methodsOnly) {
if (insertCallback == null || document == null) return;
// Track context for usage recording when item is selected
@@ -416,7 +566,7 @@ public class AutocompleteManager {
AutocompleteProvider.Context context = new AutocompleteProvider.Context(
text, cursorPosition, lineNumber, columnPosition, currentLine,
prefix, prefixStart, isMemberAccess, receiverExpr, explicitTrigger
prefix, prefixStart, isMemberAccess, receiverExpr, explicitTrigger, methodsOnly
);
// Get suggestions from appropriate provider
@@ -32,10 +32,20 @@ public interface AutocompleteProvider {
public final String receiverExpression;
/** Whether autocomplete was explicitly triggered (CTRL+Space) */
public final boolean explicitTrigger;
/** Whether to show only methods (for method reference context ::) */
public final boolean methodsOnly;
public Context(String text, int cursorPosition, int lineNumber, int columnPosition,
String currentLine, String prefix, int prefixStart,
boolean isMemberAccess, String receiverExpression, boolean explicitTrigger) {
this(text, cursorPosition, lineNumber, columnPosition, currentLine, prefix, prefixStart,
isMemberAccess, receiverExpression, explicitTrigger, false);
}
public Context(String text, int cursorPosition, int lineNumber, int columnPosition,
String currentLine, String prefix, int prefixStart,
boolean isMemberAccess, String receiverExpression, boolean explicitTrigger,
boolean methodsOnly) {
this.text = text;
this.cursorPosition = cursorPosition;
this.lineNumber = lineNumber;
@@ -46,6 +56,7 @@ public interface AutocompleteProvider {
this.isMemberAccess = isMemberAccess;
this.receiverExpression = receiverExpression;
this.explicitTrigger = explicitTrigger;
this.methodsOnly = methodsOnly;
}
}
@@ -49,7 +49,7 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
SyntheticType syntheticType =
document.getTypeResolver().getSyntheticType(receiverType.getSimpleName());
if (syntheticType != null) {
addSyntheticTypeSuggestions(syntheticType, items);
addSyntheticTypeSuggestions(syntheticType, items, context.methodsOnly);
return;
}
@@ -65,25 +65,32 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
JSTypeInfo jsTypeInfo = receiverType.getJSTypeInfo();
if (jsTypeInfo != null) {
// Pass both: jsTypeInfo (current type in hierarchy) and receiverType (context for type params)
addMethodsFromType(jsTypeInfo, receiverType, items, new HashSet<>());
addFieldsFromType(jsTypeInfo, receiverType, items, new HashSet<>());
addMethodsFromType(jsTypeInfo, receiverType, items, new HashSet<>(), context.methodsOnly);
if (!context.methodsOnly) {
addFieldsFromType(jsTypeInfo, receiverType, items, new HashSet<>());
}
}
}
/**
* Add autocomplete suggestions for a synthetic type's methods and fields.
* @param syntheticType The synthetic type
* @param items The list to add items to
* @param forMethodReference If true, only add methods with no parentheses in insert text
*/
private void addSyntheticTypeSuggestions(SyntheticType syntheticType, List<AutocompleteItem> items) {
private void addSyntheticTypeSuggestions(SyntheticType syntheticType, List<AutocompleteItem> items, boolean forMethodReference) {
// Add methods
for (SyntheticMethod method : syntheticType.getMethods()) {
AutocompleteItem item = AutocompleteItem.fromSyntheticMethod(method, syntheticType.getTypeInfo());
AutocompleteItem item = AutocompleteItem.fromSyntheticMethod(method, syntheticType.getTypeInfo(), forMethodReference);
items.add(item);
}
// Add fields
for (SyntheticField field : syntheticType.getFields()) {
AutocompleteItem item = AutocompleteItem.fromSyntheticField(field);
items.add(item);
// Add fields (skip if forMethodReference is true)
if (!forMethodReference) {
for (SyntheticField field : syntheticType.getFields()) {
AutocompleteItem item = AutocompleteItem.fromSyntheticField(field);
items.add(item);
}
}
}
@@ -93,7 +100,17 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
* @param contextType The original TypeInfo context for resolving type parameters (stays constant)
*/
protected void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List<AutocompleteItem> items, Set<String> added) {
addMethodsFromType(type, contextType, items, added, 0);
addMethodsFromType(type, contextType, items, added, 0, false);
}
/**
* Recursively add methods from a type and its parents.
* @param type The current JS type to get methods from (changes as we walk up inheritance)
* @param contextType The original TypeInfo context for resolving type parameters (stays constant)
* @param forMethodReference If true, insert text will NOT include parentheses
*/
protected void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List<AutocompleteItem> items, Set<String> added, boolean forMethodReference) {
addMethodsFromType(type, contextType, items, added, 0, forMethodReference);
}
/**
@@ -103,6 +120,17 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
* @param contextType The original TypeInfo context for resolving type parameters (e.g., IPlayer with T → EntityPlayerMP)
*/
private void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List<AutocompleteItem> items, Set<String> added, int depth) {
addMethodsFromType(type, contextType, items, added, depth, false);
}
/**
* Recursively add methods from a type and its parents with inheritance depth tracking.
* Shows all overloads - one autocomplete item per overload.
* @param type The current JS type in inheritance chain
* @param contextType The original TypeInfo context for resolving type parameters (e.g., IPlayer with T → EntityPlayerMP)
* @param forMethodReference If true, insert text will NOT include parentheses
*/
private void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List<AutocompleteItem> items, Set<String> added, int depth, boolean forMethodReference) {
// Collect base method names (without $N suffix) that we haven't processed yet
Set<String> baseNames = new HashSet<>();
for (String key : type.getMethods().keySet()) {
@@ -127,13 +155,13 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
}
// Add one autocomplete item per overload
for (JSMethodInfo method : overloads) {
items.add(AutocompleteItem.fromJSMethod(method, contextType, depth));
items.add(AutocompleteItem.fromJSMethod(method, contextType, depth, forMethodReference));
}
}
// Add from parent type with incremented depth - keep same contextType
if (type.getResolvedParent() != null) {
addMethodsFromType(type.getResolvedParent(), contextType, items, added, depth + 1);
addMethodsFromType(type.getResolvedParent(), contextType, items, added, depth + 1, forMethodReference);
}
}
@@ -61,6 +61,27 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
addScopeSuggestions(context, items);
}
// For method reference context, filter to show only methods (and constructor "new")
if (context.methodsOnly) {
items.removeIf(item -> item.getKind() != AutocompleteItem.Kind.METHOD);
// Add "new" constructor reference option if the receiver is a class
if (context.receiverExpression != null) {
int resolvePos = getMemberAccessResolvePosition(context);
TypeInfo receiverType = document.resolveExpressionType(
context.receiverExpression, resolvePos);
if (receiverType != null && receiverType.isResolved() && isStaticContext) {
items.add(new AutocompleteItem.Builder()
.name("new")
.insertText("new")
.kind(AutocompleteItem.Kind.KEYWORD)
.typeLabel("constructor")
.signature(receiverType.getSimpleName() + "::new")
.build());
}
}
}
// Filter and score by prefix, then apply usage boosts and static penalties
filterAndScore(items, context.prefix, context.isMemberAccess, isStaticContext, ownerFullName);
@@ -93,7 +114,7 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
if (clazz == null) {
// Try ScriptTypeInfo
if (receiverType instanceof ScriptTypeInfo) {
addScriptTypeMembers((ScriptTypeInfo) receiverType, items, isStaticContext);
addScriptTypeMembers((ScriptTypeInfo) receiverType, items, isStaticContext, context.methodsOnly);
}
return;
}
@@ -111,21 +132,23 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
if (!addedMethods.contains(sig)) {
addedMethods.add(sig);
MethodInfo methodInfo = MethodInfo.fromReflection(method, receiverType);
items.add(AutocompleteItem.fromMethod(methodInfo));
items.add(AutocompleteItem.fromMethod(methodInfo, context.methodsOnly));
}
}
}
// Add fields
for (Field field : clazz.getFields()) {
if (Modifier.isPublic(field.getModifiers())) {
// Filter by static context
if (isStaticContext && !Modifier.isStatic(field.getModifiers())) {
continue;
// Add fields (skip if methodsOnly is true - but the filtering will be done in getSuggestions)
if (!context.methodsOnly) {
for (Field field : clazz.getFields()) {
if (Modifier.isPublic(field.getModifiers())) {
// Filter by static context
if (isStaticContext && !Modifier.isStatic(field.getModifiers())) {
continue;
}
FieldInfo fieldInfo = FieldInfo.fromReflection(field, receiverType);
items.add(AutocompleteItem.fromField(fieldInfo));
}
FieldInfo fieldInfo = FieldInfo.fromReflection(field, receiverType);
items.add(AutocompleteItem.fromField(fieldInfo));
}
}
@@ -165,6 +188,17 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
* Add members from a script-defined type.
*/
protected void addScriptTypeMembers(ScriptTypeInfo scriptType, List<AutocompleteItem> items, boolean isStaticContext) {
addScriptTypeMembers(scriptType, items, isStaticContext, false);
}
/**
* Add members from a script-defined type.
* @param scriptType The script type to get members from
* @param items The list to add items to
* @param isStaticContext Whether we're in a static context
* @param forMethodReference If true, only add methods with no parentheses in insert text
*/
protected void addScriptTypeMembers(ScriptTypeInfo scriptType, List<AutocompleteItem> items, boolean isStaticContext, boolean forMethodReference) {
// Add methods (getMethods returns Map<String, List<MethodInfo>>)
for (List<MethodInfo> overloads : scriptType.getMethods().values()) {
for (MethodInfo method : overloads) {
@@ -172,22 +206,25 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
if (isStaticContext && !method.isStatic()) {
continue;
}
items.add(AutocompleteItem.fromMethod(method));
items.add(AutocompleteItem.fromMethod(method, forMethodReference));
}
}
// Add fields (getFields returns Map<String, FieldInfo>)
for (FieldInfo field : scriptType.getFields().values()) {
// Filter by static context
if (isStaticContext && !field.isStatic()) {
continue;
// Add fields (skip if methodsOnly/forMethodReference is true)
if (!forMethodReference) {
// Add fields (getFields returns Map<String, FieldInfo>)
for (FieldInfo field : scriptType.getFields().values()) {
// Filter by static context
if (isStaticContext && !field.isStatic()) {
continue;
}
items.add(AutocompleteItem.fromField(field));
}
// Add enum constants (getEnumConstants returns Map<String, EnumConstantInfo>)
for (EnumConstantInfo enumConstant : scriptType.getEnumConstants().values()) {
items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo()));
}
items.add(AutocompleteItem.fromField(field));
}
// Add enum constants (getEnumConstants returns Map<String, EnumConstantInfo>)
for (EnumConstantInfo enumConstant : scriptType.getEnumConstants().values()) {
items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo()));
}
// Add parent class members
@@ -202,7 +239,7 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
if (!addedMethods.contains(sig)) {
addedMethods.add(sig);
MethodInfo methodInfo = MethodInfo.fromReflection(method, superType);
items.add(AutocompleteItem.fromMethod(methodInfo));
items.add(AutocompleteItem.fromMethod(methodInfo, forMethodReference));
}
}
}
@@ -255,14 +292,14 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
// Add methods from enclosing type
for (List<MethodInfo> overloads : enclosingType.getMethods().values()) {
for (MethodInfo method : overloads) {
items.add(AutocompleteItem.fromMethod(method));
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
}
}
// Add script-defined methods
for (MethodInfo method : document.getAllMethods()) {
items.add(AutocompleteItem.fromMethod(method));
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
addLanguageUniqueSuggestions(context, items);