Merge branch 'dev' into core

This commit is contained in:
Kam committed 2026-03-13 16:23:28 -04:00
commit 27a9e4c808
17 files changed
+744 -534

No files matched your search

@@ -961,7 +961,7 @@ public class ClientProxy extends CommonProxy {
public void drawString(String text, int x, int y, int color) {
if (useCustomFont) {
textFont.renderString(text, x, y, color, true);
// textFont.renderString(text, x, y, color, true);
textFont.renderString(text, x, y, color, false);
} else {
Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(text, x, y, color);
@@ -575,7 +575,7 @@ public class JavaTextContainer extends TextContainer {
for (ImportEntry ie : importEntries) {
// Highlight the 'import' keyword
marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.IMPORT_KEYWORD));
marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.KEYWORD));
String fullPath = ie.fullPath;
int pathStart = ie.pathStart;
@@ -836,7 +836,7 @@ public class JavaTextContainer extends TextContainer {
Matcher m = CLASS_DECL.matcher(text);
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
while (m.find()) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.CLASS_KEYWORD));
marks.add(new Mark(m.start(1), m.end(1), TokenType.KEYWORD));
int nameStart = m.start(2);
int nameEnd = m.end(2);
@@ -868,7 +868,7 @@ public class JavaTextContainer extends TextContainer {
// Highlight general keywords
collectPatternMatches(marks, KEYWORD, TokenType.KEYWORD);
collectPatternMatches(marks, MODIFIER, TokenType.MODIFIER);
collectPatternMatches(marks, MODIFIER, TokenType.KEYWORD);
collectTypeDeclarations(marks);
collectPatternMatches(marks, NEW_TYPE, TokenType.NEW_TYPE, 1);
@@ -1211,10 +1211,7 @@ public class JavaTextContainer extends TextContainer {
public enum TokenType {
COMMENT('7', 130),
STRING('5', 120),
CLASS_KEYWORD('c', 115),
IMPORT_KEYWORD('6', 110),
KEYWORD('c', 100),
MODIFIER('6', 90),
NEW_TYPE('d', 80),
IMPORTED_CLASS('3', 75), //imported classes used in code
INTERFACE_DECL('b', 85),
@@ -22,12 +22,13 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
public enum Kind {
ENUM_CONSTANT(-1), // Enum constant value (highest priority for enums)
METHOD(0), // Method or function
FIELD(1), // Field or property
VARIABLE(2), // Local variable or parameter
CLASS(3), // Class or interface type
ENUM(4), // Enum type
KEYWORD(6), // Language keyword
SNIPPET(7); // Code snippet
FIELD(10), // Field or property
PARAMETER(19), // Local variable or parameter
VARIABLE(20), // Local variable or parameter
CLASS(30), // Class or interface type
ENUM(40), // Enum type
KEYWORD(60), // Language keyword
SNIPPET(70); // Code snippet
private final int priority;
@@ -158,7 +159,7 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
Kind kind;
switch (field.getScope()) {
case PARAMETER:
kind = Kind.VARIABLE;
kind = Kind.PARAMETER;
break;
case LOCAL:
kind = Kind.VARIABLE;
@@ -694,6 +695,7 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
case METHOD: return "m";
case FIELD: return "f";
case VARIABLE: return "v";
case PARAMETER: return "p";
case CLASS: return "C";
case ENUM: return "E";
case ENUM_CONSTANT: return "e";
@@ -711,6 +713,7 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
case METHOD: return 0xFFB877DB; // Purple for methods
case FIELD: return 0xFF79C0FF; // Blue for fields
case VARIABLE: return 0xFF7EE787; // Green for variables
case PARAMETER: return 0XFFFF00FF; // Green for variables
case CLASS: return 0xFFFFA657; // Orange for classes
case ENUM: return 0xFFFFD866; // Yellow for enums
case ENUM_CONSTANT: return 0xFFFFD866;
@@ -389,6 +389,17 @@ public class AutocompleteManager {
// Walk left across a dotted receiver chain
while (pos >= 0) {
// Skip excluded regions (comments/strings) to avoid reading dots from inside them
if (document != null && document.isExcluded(pos)) {
int jumped = jumpBeforeExcluded(pos);
if (jumped == pos) {
pos--;
} else {
pos = jumped;
}
continue;
}
char c = text.charAt(pos);
if (Character.isWhitespace(c)) {
@@ -414,10 +425,24 @@ public class AutocompleteManager {
// Consume identifier
while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--;
// If preceded by a dot, keep going
// If preceded by a dot, keep going (skip excluded ranges when looking for the dot)
int checkPos = pos;
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) {
checkPos--;
while (checkPos >= 0) {
char ch = text.charAt(checkPos);
if (Character.isWhitespace(ch)) {
checkPos--;
continue;
}
if (document != null && document.isExcluded(checkPos)) {
int jumped = jumpBeforeExcluded(checkPos);
if (jumped == checkPos) {
checkPos--;
} else {
checkPos = jumped;
}
continue;
}
break;
}
if (checkPos >= 0 && text.charAt(checkPos) == '.') {
pos = checkPos - 1;
@@ -1044,13 +1069,16 @@ public class AutocompleteManager {
// Check if we found a dot
if (pos >= 0 && text.charAt(pos) == '.') {
if (document != null && document.isExcluded(pos)) return -1;
return pos;
} else {
while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos)))
pos--;
if (pos >= 0 && text.charAt(pos) == '.')
if (pos >= 0 && text.charAt(pos) == '.') {
if (document != null && document.isExcluded(pos)) return -1;
return pos;
}
}
return -1;
}
@@ -482,6 +482,8 @@ public class AutocompleteMenu extends Gui {
return TokenType.getColor(item.getTypeInfo());
case VARIABLE:
return TokenType.LOCAL_FIELD.getHexColor();
case PARAMETER:
return TokenType.PARAMETER.getHexColor();
case KEYWORD:
return TokenType.KEYWORD.getHexColor();
default:
@@ -637,6 +639,9 @@ public class AutocompleteMenu extends Gui {
private void drawTypeLabel(AutocompleteItem item, String typeLabel, int x, int y, int typeColor, TypeInfo typeInfo) {
if (typeInfo == null || item.getKind() == AutocompleteItem.Kind.CLASS) { //draw package on right
// draw default package color instead of interface/enum colors
if (typeInfo != null && !typeInfo.isClass())
typeColor = TokenType.getPackageColor();
drawSimpleTypeWithArraySuffix(typeLabel, x, y, typeColor);
return;
}
@@ -1,15 +1,16 @@
package noppes.npcs.client.gui.util.script.autocomplete;
import noppes.npcs.client.gui.util.script.interpreter.js_parser.*;
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.*;
import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver;
import noppes.npcs.config.ConfigScript;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
@@ -37,6 +38,15 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
/**
* Add suggestions for member access (after dot).
* Uses ScriptDocument's unified type resolution system.
*
* Fixes applied vs original implementation:
* - Single getMemberAccessResolvePosition() call (was duplicated)
* - Single getMergeRegistryType() call (was duplicated)
* - Shared addedMethods/addedFields sets across ALL sources for cross-source deduplication
* - Unified nested type lookup via getAllNestedTypes() instead of raw reflection
* - Single Object method injection path (registry-based via fromJSMethod)
* - Name-based Object.class guard instead of fragile Class identity comparison
* - Logged SecurityException instead of silently swallowed
*/
protected void addMemberSuggestions(Context context, List<AutocompleteItem> items) {
String receiverExpr = context.receiverExpression;
@@ -44,113 +54,105 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
return;
}
// Resolve position once — used for both type resolution and static context detection
int resolvePos = getMemberAccessResolvePosition(context);
// Use ScriptDocument's resolveExpressionType - handles both Java and JS
TypeInfo receiverType = document.resolveExpressionType(receiverExpr, getMemberAccessResolvePosition(context));
TypeInfo receiverType = document.resolveExpressionType(receiverExpr, resolvePos);
if (receiverType == null || !receiverType.isResolved()) {
return;
}
// Check for synthetic types first (e.g., Nashorn Java object, custom types)
SyntheticType syntheticType =
document.getTypeResolver().getSyntheticType(receiverType.getSimpleName());
// --- JS-SPECIFIC: synthetic type early return ---
SyntheticType syntheticType = document.getTypeResolver().getSyntheticType(receiverType.getSimpleName());
if (syntheticType != null) {
addSyntheticTypeSuggestions(syntheticType, items, context.methodsOnly);
return;
}
boolean isStaticContext = isStaticAccess(receiverExpr, getMemberAccessResolvePosition(context));
boolean isStaticContext = isStaticAccess(receiverExpr, resolvePos);
// Resolve merge-registry type once — used for both method and field fallback
Class<?> javaClass = receiverType.getJavaClass();
if (javaClass != null) {
Set<String> addedMethods = new HashSet<>();
for (Method method : javaClass.getMethods()) {
if (!Modifier.isPublic(method.getModifiers())) continue;
if (isStaticContext && !Modifier.isStatic(method.getModifiers())) continue;
String sig = method.getName() + "(" + method.getParameterCount() + ")";
if (addedMethods.add(sig)) {
items.add(AutocompleteItem.fromMethod(MethodInfo.fromReflection(method, receiverType), context.methodsOnly));
}
JSTypeInfo mergeRegistryType = (javaClass != null
&& receiverType.getSyntheticMethods().isEmpty()
&& receiverType.getSyntheticFields().isEmpty())
? getMergeRegistryType(javaClass) : null;
// Shared deduplication sets — prevent the same method/field appearing from multiple sources
Set<String> addedMethods = new HashSet<>();
Set<String> addedFields = new HashSet<>();
// ---- SHARED: unified method enumeration (TypeInfo.getAllMethods covers reflection + synthetics) ----
for (MethodInfo method : receiverType.getAllMethods()) {
if (isStaticContext && !Modifier.isStatic(method.getModifiers()))
continue;
String sig = method.getName() + "(" + method.getParameterCount() + ")";
if (addedMethods.add(sig))
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
// --- JS-SPECIFIC: merge registry type fallback for methods ---
if (mergeRegistryType != null) {
addMethodsFromType(mergeRegistryType, receiverType, items, addedMethods, context.methodsOnly,
isStaticContext);
}
if (!context.methodsOnly) {
// ---- SHARED: unified field enumeration with deduplication ----
for (FieldInfo field : receiverType.getAllFields()) {
if (isStaticContext && !Modifier.isStatic(field.getModifiers()))
continue;
if (addedFields.add(field.getName()))
items.add(AutocompleteItem.fromField(field));
}
List<MethodInfo> effectiveSyntheticMethods = receiverType.getSyntheticMethods();
if (!effectiveSyntheticMethods.isEmpty()) {
for (MethodInfo method : effectiveSyntheticMethods) {
if (isStaticContext && !method.isStatic()) continue;
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
} else {
JSTypeInfo jsType = getMergeRegistryType(javaClass);
if (jsType != null) {
addMethodsFromType(jsType, receiverType, items, new HashSet<>(), context.methodsOnly, isStaticContext);
}
// --- JS-SPECIFIC: merge registry type fallback for fields ---
if (mergeRegistryType != null) {
addFieldsFromType(mergeRegistryType, receiverType, items, addedFields, isStaticContext);
}
if (!context.methodsOnly) {
for (Field field : javaClass.getFields()) {
if (!Modifier.isPublic(field.getModifiers())) continue;
if (isStaticContext && !Modifier.isStatic(field.getModifiers())) continue;
items.add(AutocompleteItem.fromField(FieldInfo.fromReflection(field, receiverType)));
}
if (!receiverType.getSyntheticFields().isEmpty()) {
for (FieldInfo field : receiverType.getSyntheticFields()) {
if (isStaticContext && !field.isStatic()) continue;
items.add(AutocompleteItem.fromField(field));
}
} else {
JSTypeInfo jsType = getMergeRegistryType(javaClass);
if (jsType != null) {
addFieldsFromType(jsType, receiverType, items, new HashSet<>(), isStaticContext);
}
}
}
// ---- SHARED: nested types (inner classes) in static context via getAllNestedTypes() ----
if (isStaticContext && !context.methodsOnly) {
// ScriptTypeInfo.getAllNestedTypes() returns script inner classes directly;
// TypeInfo.getAllNestedTypes() uses reflection. No duplicate logic needed.
for (TypeInfo nestedType : receiverType.getAllNestedTypes()) {
items.add(AutocompleteItem.fromType(nestedType));
}
if (!isStaticContext && javaClass != Object.class) {
JSTypeInfo objJSType = registry.getType("Object");
if (objJSType != null) {
for (JSMethodInfo m : objJSType.getMethods().values()) {
if (!m.isStatic()) {
}
// Enum constants — polymorphic via TypeInfo.getEnumConstants()
if (!context.methodsOnly) {
for (EnumConstantInfo enumConstant : receiverType.getEnumConstants().values()) {
items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo()));
}
}
// --- JS-SPECIFIC: Object methods from JS registry (single unified path) ---
// Add Object.class JS methods for instance access, unless receiver IS Object itself.
// Uses name comparison instead of Class identity for robustness across classloaders.
if (!isStaticContext && (javaClass == null || !"java.lang.Object".equals(javaClass.getName()))) {
JSTypeInfo objJSType = registry.getType("Object");
if (objJSType != null) {
for (JSMethodInfo m : objJSType.getMethods().values()) {
if (!m.isStatic()) {
String sig = m.getName() + "(" + m.getParameterCount() + ")";
if (addedMethods.add(sig)) {
items.add(AutocompleteItem.fromJSMethod(m, receiverType, 1, context.methodsOnly));
}
}
}
}
return;
}
Set<String> syntheticMethodNames = new HashSet<>();
for (MethodInfo method : receiverType.getSyntheticMethods()) {
syntheticMethodNames.add(method.getName());
if (isStaticContext && !method.isStatic()) continue;
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
for (FieldInfo field : receiverType.getSyntheticFields()) {
if (!context.methodsOnly) {
if (isStaticContext && !field.isStatic()) continue;
if (syntheticMethodNames.contains(field.getName())) continue;
items.add(AutocompleteItem.fromField(field));
}
}
JSTypeInfo jsTypeInfo = receiverType.getJSTypeInfo();
if (jsTypeInfo != null) {
addMethodsFromType(jsTypeInfo, receiverType, items, new HashSet<>(), context.methodsOnly, isStaticContext);
if (!context.methodsOnly && ConfigScript.ShowImplementationFieldsInAutocomplete) {
addFieldsFromType(jsTypeInfo, receiverType, items, new HashSet<>(), isStaticContext);
}
}
if (!isStaticContext) {
Set<String> addedObjMethods = new HashSet<>();
for (Method m : Object.class.getMethods()) {
if (!Modifier.isPublic(m.getModifiers()) || Modifier.isStatic(m.getModifiers())) continue;
String sig = m.getName() + "(" + m.getParameterCount() + ")";
if (addedObjMethods.add(sig)) {
items.add(AutocompleteItem.fromMethod(MethodInfo.fromReflection(m, receiverType), context.methodsOnly));
}
}
JSTypeInfo objJSType = registry.getType("Object");
if (objJSType != null) {
for (JSMethodInfo m : objJSType.getMethods().values()) {
if (!m.isStatic()) {
items.add(AutocompleteItem.fromJSMethod(m, receiverType, 1, context.methodsOnly));
}
// --- JS-SPECIFIC: pure JS type fallback (javaClass == null, not ScriptTypeInfo) ---
if (javaClass == null && !(receiverType instanceof ScriptTypeInfo)) {
JSTypeInfo jsTypeInfo = receiverType.getJSTypeInfo();
if (jsTypeInfo != null) {
addMethodsFromType(jsTypeInfo, receiverType, items, addedMethods, context.methodsOnly, isStaticContext);
if (!context.methodsOnly && ConfigScript.ShowImplementationFieldsInAutocomplete) {
addFieldsFromType(jsTypeInfo, receiverType, items, addedFields, isStaticContext);
}
}
}
@@ -10,8 +10,6 @@ import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
@@ -100,92 +98,52 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
if (receiverExpr == null || receiverExpr.isEmpty()) {
return;
}
// Resolve position once — used for both type resolution and static context detection
int resolvePos = getMemberAccessResolvePosition(context);
// Resolve the type of the receiver expression
TypeInfo receiverType = document.resolveExpressionType(receiverExpr, getMemberAccessResolvePosition(context));
TypeInfo receiverType = document.resolveExpressionType(receiverExpr, resolvePos);
if (receiverType == null || !receiverType.isResolved()) {
return;
}
// Determine if this is a static context (accessing a class type)
boolean isStaticContext = isStaticAccess(receiverExpr, getMemberAccessResolvePosition(context));
boolean isStaticContext = isStaticAccess(receiverExpr, resolvePos);
Class<?> clazz = receiverType.getJavaClass();
if (clazz == null) {
// Try ScriptTypeInfo
if (receiverType instanceof ScriptTypeInfo) {
addScriptTypeMembers((ScriptTypeInfo) receiverType, items, isStaticContext, context.methodsOnly);
}
return;
}
// Add methods
// Shared deduplication sets across all member sources
Set<String> addedMethods = new HashSet<>();
for (Method method : clazz.getMethods()) {
if (Modifier.isPublic(method.getModifiers())) {
// Filter by static context
if (isStaticContext && !Modifier.isStatic(method.getModifiers())) {
continue;
}
String sig = method.getName() + "(" + method.getParameterCount() + ")";
if (!addedMethods.contains(sig)) {
addedMethods.add(sig);
MethodInfo methodInfo = MethodInfo.fromReflection(method, receiverType);
items.add(AutocompleteItem.fromMethod(methodInfo, context.methodsOnly));
}
}
}
Set<String> addedFields = new HashSet<>();
for (MethodInfo method : receiverType.getSyntheticMethods()) {
if (isStaticContext && !Modifier.isStatic(method.getModifiers()))
continue;
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
// Unified method enumeration — works for Java types, ScriptTypeInfo, and intersection bounds
for (MethodInfo method : receiverType.getAllMethods()) {
if (isStaticContext && !Modifier.isStatic(method.getModifiers())) continue;
String sig = method.getName() + "(" + method.getParameterCount() + ")";
if (addedMethods.add(sig))
items.add(AutocompleteItem.fromMethod(method, context.methodsOnly));
}
// 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));
}
}
for (FieldInfo field : receiverType.getSyntheticFields()) {
if (isStaticContext && !Modifier.isStatic(field.getModifiers()))
continue;
items.add(AutocompleteItem.fromField(field));
// Unified field enumeration with deduplication
for (FieldInfo field : receiverType.getAllFields()) {
if (isStaticContext && !Modifier.isStatic(field.getModifiers())) continue;
if (addedFields.add(field.getName()))
items.add(AutocompleteItem.fromField(field));
}
}
// Add nested types (inner classes/interfaces) in static context
// Nested types (inner classes) in static context via getAllNestedTypes()
if (isStaticContext && !context.methodsOnly) {
try {
for (Class<?> nested : clazz.getDeclaredClasses()) {
if (!Modifier.isPublic(nested.getModifiers())) {
continue;
}
// Convert $ notation to dot notation for resolution
String nestedFullName = nested.getName().replace('$', '.');
TypeInfo nestedType = TypeResolver.getInstance().resolveFullName(nestedFullName);
if (nestedType != null && nestedType.isResolved()) {
items.add(AutocompleteItem.fromType(nestedType));
}
}
} catch (SecurityException ignored) {
// Some runtimes may restrict getDeclaredClasses()
for (TypeInfo nestedType : receiverType.getAllNestedTypes()) {
items.add(AutocompleteItem.fromType(nestedType));
}
}
// Enum constants — polymorphic via TypeInfo.getEnumConstants()
if (!context.methodsOnly) {
for (EnumConstantInfo enumConstant : receiverType.getEnumConstants().values()) {
items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo()));
}
}
}
/**
@@ -218,76 +176,6 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
return Math.max(0, Math.min(context.prefixStart, context.text.length()));
}
/**
* 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) {
// Filter by static context
if (isStaticContext && !method.isStatic()) {
continue;
}
items.add(AutocompleteItem.fromMethod(method, forMethodReference));
}
}
// 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()));
}
// Add nested types (inner classes/interfaces) in static context
if (isStaticContext) {
for (ScriptTypeInfo inner : scriptType.getInnerClasses()) {
items.add(AutocompleteItem.fromType(inner));
}
}
}
// Add parent class members
if (scriptType.hasSuperClass()) {
TypeInfo superType = scriptType.getSuperClass();
if (superType != null && superType.getJavaClass() != null) {
Class<?> superClazz = superType.getJavaClass();
Set<String> addedMethods = new HashSet<>();
for (Method method : superClazz.getMethods()) {
if (Modifier.isPublic(method.getModifiers())) {
String sig = method.getName() + "(" + method.getParameterCount() + ")";
if (!addedMethods.contains(sig)) {
addedMethods.add(sig);
MethodInfo methodInfo = MethodInfo.fromReflection(method, superType);
items.add(AutocompleteItem.fromMethod(methodInfo, forMethodReference));
}
}
}
}
}
}
/**
* Add suggestions based on current scope (not after a dot).
*/
@@ -151,11 +151,11 @@ public class FieldChainMarker {
int pos = m.end(2);
while (pos < text.length()) {
pos = document.skipWhitespace(pos);
if (pos >= text.length() || text.charAt(pos) != '.') break;
if (pos >= text.length() || document.isExcluded(pos) || text.charAt(pos) != '.') break;
pos++; // Skip dot
pos = document.skipWhitespace(pos);
if (pos >= text.length() || !Character.isJavaIdentifierStart(text.charAt(pos))) break;
if (pos >= text.length() || document.isExcluded(pos) || !Character.isJavaIdentifierStart(text.charAt(pos))) break;
// Read identifier
int identStart = pos;
@@ -452,11 +452,11 @@ public class FieldChainMarker {
int pos = identEnd;
while (pos < text.length()) {
pos = document.skipWhitespace(pos);
if (pos >= text.length() || text.charAt(pos) != '.') break;
if (pos >= text.length() || document.isExcluded(pos) || text.charAt(pos) != '.') break;
pos++; // Skip dot
pos = document.skipWhitespace(pos);
if (pos >= text.length() || !Character.isJavaIdentifierStart(text.charAt(pos))) break;
if (pos >= text.length() || document.isExcluded(pos) || !Character.isJavaIdentifierStart(text.charAt(pos))) break;
// Read identifier
int nStart = pos;
@@ -4308,6 +4308,54 @@ public class ScriptDocument {
return resolveTypeAndTrackUsage(typeName);
}
/**
* Recursively resolve any unresolved type names inside a TypeInfo using position-aware resolution.
*
* This handles a different concern than {@link GenericContext#substitute(TypeInfo)} —
* it does not replace type variables with concrete bindings. Instead, it re-resolves
* unresolved simple names (e.g., inner class names like "Node" or script-declared type
* parameters like "T") that appear as type arguments in parameterized types.
*
* For example, if a type resolves to {@code List<Node>} but "Node" is still unresolved,
* this will attempt to resolve "Node" using the position-aware
* {@link #resolveType(String, int)} which can find inner classes and type parameters
* visible at the given position.
*
* @param type the type whose unresolved components should be re-resolved
* @param position the script text offset for scope-aware resolution
* @return the type with all resolvable components resolved, or the original if nothing changed
*/
private TypeInfo substituteTypeParams(TypeInfo type, int position) {
if (type == null)
return null;
if (!type.isResolved() && type.getSimpleName() != null
&& !type.getSimpleName().contains(".")) {
TypeInfo sub = resolveType(type.getSimpleName(), position);
return (sub != null && sub.isResolved()) ? sub : type;
}
if (type.isParameterized()) {
List<TypeInfo> args = type.getAppliedTypeArgs();
if (args != null && !args.isEmpty()) {
List<TypeInfo> substituted = new ArrayList<>(args.size());
boolean anyChanged = false;
for (TypeInfo arg : args) {
TypeInfo sub = substituteTypeParams(arg, position);
if (sub != arg)
anyChanged = true;
substituted.add(sub);
}
if (anyChanged) {
TypeInfo raw = type.getRawType();
return raw != null ? raw.parameterize(substituted) : type.parameterize(substituted);
}
}
}
return type;
}
/**
* Position-aware type resolution overload.
* Resolves a type name with positional context so that an unqualified inner class name
@@ -4330,7 +4378,7 @@ public class ScriptDocument {
// If already resolved, no need for positional fallback
if (resolved != null && resolved.isResolved()) {
return resolved;
return substituteTypeParams(resolved, position);
}
if (typeName != null && !typeName.contains(".")) {
@@ -6419,7 +6467,7 @@ public class ScriptDocument {
while (pos >= 0 && Character.isWhitespace(text.charAt(pos)))
pos--;
if (pos < 0 || text.charAt(pos) != '.')
if (pos < 0 || isExcluded(pos) || text.charAt(pos) != '.')
return false;
// Skip the dot and any whitespace
@@ -6427,7 +6475,7 @@ public class ScriptDocument {
while (pos >= 0 && Character.isWhitespace(text.charAt(pos)))
pos--;
if (pos < 0)
if (pos < 0 || isExcluded(pos))
return false;
// Check what's before the dot - could be:
@@ -6458,7 +6506,7 @@ public class ScriptDocument {
pos--;
// If preceded by a dot, this is part of a chain - treat as instance for now
if (pos >= 0 && text.charAt(pos) == '.') {
if (pos >= 0 && !isExcluded(pos) && text.charAt(pos) == '.') {
return false;
}
@@ -7151,7 +7199,8 @@ public class ScriptDocument {
while (scanPos >= 0 && Character.isWhitespace(text.charAt(scanPos)))
scanPos--;
if (scanPos < 0 || text.charAt(scanPos) != '.') {
// Guard: dot inside a comment/string must not be treated as a receiver chain separator
if (scanPos < 0 || isExcluded(scanPos) || text.charAt(scanPos) != '.') {
return null; // No receiver
}
@@ -8082,11 +8131,24 @@ public class ScriptDocument {
if (Character.isJavaIdentifierPart(c)) {
while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--;
// Skip whitespace to check for chained identifier (preceded by a dot)
// Skip whitespace AND excluded ranges to check for chained identifier (preceded by a dot).
// Without skipping excluded ranges, a dot inside a comment (e.g. "//event.\n player")
// would be mistaken for a chain continuation dot.
int checkPos = pos;
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) checkPos--;
// If it's part of a chained identifier (preceded by a dot), continue
if (checkPos >= 0 && text.charAt(checkPos) == '.') { pos = checkPos - 1; continue; }
while (checkPos >= 0) {
if (isExcluded(checkPos)) {
for (int[] range : excludedRanges) {
if (checkPos >= range[0] && checkPos < range[1]) {
checkPos = range[0] - 1;
break;
}
}
continue;
}
if (Character.isWhitespace(text.charAt(checkPos))) { checkPos--; continue; }
break;
}
if (checkPos >= 0 && !isExcluded(checkPos) && text.charAt(checkPos) == '.') { pos = checkPos - 1; continue; }
break;
}
@@ -9967,7 +10029,7 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
TokenType type = isClassTypeInfo ? varInfo.isGlobal() ? TokenType.GLOBAL_FIELD
: TokenType.LOCAL_FIELD : info.getTokenType();
: TokenType.LOCAL_FIELD : TokenType.METHOD_CALL;
marks.add(new ScriptLine.Mark(start, end, type, isClassTypeInfo ? varInfo : ctorCall));
continue;
}
@@ -9,7 +9,7 @@ import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo;
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeSubstitutor;
import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo;
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
@@ -18,7 +18,6 @@ import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Metadata for a field (variable) declaration or reference.
@@ -165,12 +164,8 @@ public final class FieldInfo {
}
// If the receiver is parameterized, substitute class type variables in the field type
if (GenericContext.hasGenerics(containingType)) {
Map<String, TypeInfo> receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
if (!receiverBindings.isEmpty()) {
type = TypeSubstitutor.substitute(type, receiverBindings);
}
}
if (GenericContext.hasGenerics(containingType))
type = GenericContext.forReceiver(containingType).substitute(type);
// Check if this is an enum constant
if (field.isEnumConstant()) {
@@ -531,6 +526,38 @@ public final class FieldInfo {
public String getDocumentation() { return documentation; }
public JSDocInfo getJSDocInfo() { return jsDocInfo; }
public void setJSDocInfo(JSDocInfo jsDocInfo) { this.jsDocInfo = jsDocInfo; }
/**
* Create a copy of this field with its declared type substituted using the given context.
* Returns {@code this} unchanged if the context is null, the declared type is null,
* or substitution produces the same type (identity check).
*
* Used when a generic type is parameterized (e.g., {@code Box<String>}) and its raw fields
* (declared with type variables like T) need to reflect the concrete type arguments.
*
* Example: for {@code class Box<T> { T value; }}, calling this on the raw field {@code value: T}
* with a context binding {@code T → String} produces {@code value: String}.
*
* @param context the generic context containing type variable bindings; if null, returns {@code this} unchanged
* @return a new FieldInfo with the substituted declared type, or {@code this} if no substitution occurred
*/
public FieldInfo substituteTypeParams(GenericContext context) {
if (context == null || declaredType == null) {
return this;
}
TypeInfo subType = context.substitute(declaredType);
if (subType == declaredType) {
return this;
}
FieldInfo result = new FieldInfo(name, scope, subType, declarationOffset, resolved,
containingMethod, documentation, initStart, initEnd, modifiers, reflectionField);
result.jsDocInfo = this.jsDocInfo;
result.scopeInfo = this.scopeInfo;
result.isVarArg = this.isVarArg;
result.inferredType = this.inferredType;
return result;
}
public int getInitStart() { return initStart; }
public int getInitEnd() { return initEnd; }
public boolean hasInitializer() { return initStart >= 0 && initEnd > initStart; }
@@ -582,7 +582,7 @@ public class TokenHoverInfo {
// // Show modifiers from source if we have a declaration position
// String modifiers = extractModifiersAtPosition(fieldInfo.getDeclarationOffset());
// if (modifiers != null && !modifiers.isEmpty()) {
// addSegment(modifiers + " ", TokenType.MODIFIER.getHexColor());
// addSegment(modifiers + " ", TokenType.KEYWORD.getHexColor());
// }
// }
@@ -802,6 +802,64 @@ public class TokenHoverInfo {
} else {
addSegment(param.getBoundTypeName(), TokenType.IMPORTED_CLASS.getHexColor());
}
List<TypeInfo> additionalBoundTypes = param.getAdditionalBoundTypes();
List<String> additionalBoundNames = param.getAdditionalBoundNames();
for (int j = 0; j < additionalBoundNames.size(); j++) {
addSegment(" & ", TokenType.DEFAULT.getHexColor());
TypeInfo additionalBoundType = j < additionalBoundTypes.size() ? additionalBoundTypes.get(j) : null;
if (additionalBoundType != null && additionalBoundType.isResolved()) {
addTypeSegments(additionalBoundType);
if (!additionalBoundType.isParameterized()) {
addBoundTypeParamSegments(additionalBoundType);
}
} else {
addSegment(additionalBoundNames.get(j), TokenType.IMPORTED_CLASS.getHexColor());
}
}
}
}
addSegment(">", TokenType.DEFAULT.getHexColor());
}
private void addBoundTypeParamSegments(TypeInfo boundType) {
List<TypeParamInfo> params = boundType.getTypeParams();
if (params == null || params.isEmpty()) return;
addSegment("<", TokenType.DEFAULT.getHexColor());
for (int i = 0; i < params.size(); i++) {
if (i > 0)
addSegment(", ", TokenType.DEFAULT.getHexColor());
TypeParamInfo tp = params.get(i);
addSegment(tp.getName(), TokenType.GENERIC_TYPE_PARAM.getHexColor());
if (tp.getBoundTypeName() != null && !"Object".equals(tp.getBoundTypeName())) {
addSegment(" extends ", TokenType.KEYWORD.getHexColor());
TypeInfo innerBound = tp.getBoundTypeInfo();
if (innerBound != null && innerBound.isResolved()) {
addTypeSegments(innerBound);
if (!innerBound.isParameterized()) {
addBoundTypeParamSegments(innerBound);
}
} else {
addSegment(tp.getBoundTypeName(), TokenType.IMPORTED_CLASS.getHexColor());
}
List<TypeInfo> innerAdditional = tp.getAdditionalBoundTypes();
List<String> innerAdditionalNames = tp.getAdditionalBoundNames();
for (int j = 0; j < innerAdditionalNames.size(); j++) {
addSegment(" & ", TokenType.DEFAULT.getHexColor());
TypeInfo innerAddBound = j < innerAdditional.size() ? innerAdditional.get(j) : null;
if (innerAddBound != null && innerAddBound.isResolved()) {
addTypeSegments(innerAddBound);
if (!innerAddBound.isParameterized()) {
addBoundTypeParamSegments(innerAddBound);
}
} else {
addSegment(innerAdditionalNames.get(j), TokenType.IMPORTED_CLASS.getHexColor());
}
}
addSegment(" extends ", TokenType.KEYWORD.getHexColor());
}
}
@@ -11,7 +11,7 @@ import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeSubstitutor;
import noppes.npcs.client.gui.util.script.interpreter.type.GenericParameterAdapter;
import java.lang.reflect.Constructor;
@@ -173,13 +173,12 @@ public final class MethodInfo {
}
// If the receiver is parameterized (e.g., List<String>), substitute class type variables (E -> String)
Map<String, TypeInfo> receiverBindings = null;
GenericContext receiverCtx = null;
if (GenericContext.hasGenerics(containingType)) {
receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
if (!receiverBindings.isEmpty()) {
returnType = TypeSubstitutor.substitute(returnType, receiverBindings);
}
receiverCtx = GenericContext.forReceiver(containingType);
returnType = receiverCtx.substitute(returnType);
}
List<FieldInfo> params = new ArrayList<>();
// Use getGenericParameterTypes() to preserve generic information
java.lang.reflect.Type[] genericParamTypes = method.getGenericParameterTypes();
@@ -190,9 +189,8 @@ public final class MethodInfo {
paramType = TypeInfo.fromClass(method.getParameterTypes()[i]);
}
if (receiverBindings != null && !receiverBindings.isEmpty()) {
paramType = TypeSubstitutor.substitute(paramType, receiverBindings);
}
if (receiverCtx != null)
paramType = receiverCtx.substitute(paramType);
// Adapt Object params to receiver generic type args (e.g., Map.get(Object) -> Map.get(K))
TypeInfo adapted = GenericParameterAdapter.adaptParameterType(method, containingType, i, paramType);
@@ -377,6 +375,37 @@ public final class MethodInfo {
*/
public boolean hasInheritanceMarker() { return isOverride() || isImplements(); }
/**
* Create a copy of this method with all type variables substituted using the given context.
* Applies substitution to both the return type and every parameter type recursively.
*
* Used when a generic type is parameterized (e.g., {@code Box<String>}) and its raw methods
* (declared with type variables like T) need to reflect the concrete type arguments.
*
* Example: for {@code class Box<T> { T get(); }}, calling this on the raw {@code get() → T}
* with a context binding {@code T → String} produces {@code get() → String}.
*
* @param context the generic context containing type variable bindings; if null, returns {@code this} unchanged
* @return a new MethodInfo with substituted types, or {@code this} if context is null
*/
public MethodInfo substituteTypeParams(GenericContext context) {
if (context == null) {
return this;
}
TypeInfo subReturnType = context.substitute(returnType);
List<FieldInfo> subParams = new ArrayList<>(parameters.size());
for (FieldInfo param : parameters) {
subParams.add(param.substituteTypeParams(context));
}
MethodInfo result = new MethodInfo(name, subReturnType, containingType, subParams,
fullDeclarationOffset, typeOffset, nameOffset, bodyStart, bodyEnd,
resolved, isDeclaration, modifiers, documentation, javaMethod);
result.jsDocInfo = this.jsDocInfo;
result.overridesFrom = this.overridesFrom;
result.implementsFrom = this.implementsFrom;
return result;
}
/**
* Check if a position is inside this method's body.
*/
@@ -1,5 +1,6 @@
package noppes.npcs.client.gui.util.script.interpreter.token;
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
/**
@@ -110,7 +111,10 @@ public enum TokenType {
public static int getColor(TypeInfo typeInfo) {
return getByType(typeInfo).getHexColor();
}
public static int getPackageColor(){
return IMPORTED_CLASS.getHexColor();
}
/**
* Convert this token type to a Minecraft color code character.
* Used for backward compatibility with the existing rendering system.
@@ -8,12 +8,16 @@ import java.util.List;
import java.util.Map;
/**
* A context for resolving and substituting declared type parameters (T, E, K, V...)
* based on a receiver type.
* Single source of truth for generic type variable substitution.
*
* Policy:
* - Prefer applied type arguments when present (e.g. List<String> binds E -> String).
* - Fall back to declared bounds when no applied argument exists (e.g. T extends Entity -> Entity).
* Resolves type parameters (T, E, K, V...) to concrete types using:
* 1. Applied type arguments (e.g., List&lt;String&gt; binds E &rarr; String) — priority
* 2. Declared bounds fallback (e.g., &lt;T extends Entity&gt; binds T &rarr; Entity) — fallback
*
* Usage patterns:
* - {@link #forReceiver(TypeInfo)} — build context from a parameterized receiver type
* - {@link #fromBindings(List, List)} — build context from explicit params/args (anti-recursion safe)
* - {@link #substitute(TypeInfo)} — instance method with two-tier resolution
*/
public final class GenericContext {
@@ -10,6 +10,7 @@ import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -152,32 +153,12 @@ public class ScriptTypeInfo extends TypeInfo {
return super.getTypeParam(name);
}
private static MethodInfo substituteMethod(MethodInfo m, GenericContext ctx) {
TypeInfo retType = m.getReturnType();
TypeInfo subRet = ctx.substitute(retType);
List<FieldInfo> params = new ArrayList<>(m.getParameters());
boolean changed = subRet != retType;
for (int i = 0; i < params.size(); i++) {
FieldInfo p = params.get(i);
TypeInfo subP = ctx.substitute(p.getTypeInfo());
if (subP != p.getTypeInfo()) {
params.set(i, FieldInfo.reflectionParam(p.getName(), subP));
changed = true;
}
}
return changed ? MethodInfo.external(m.getName(), subRet, m.getContainingType(),
params, m.getModifiers(), m.getDocumentation()) : m;
}
@Override
public TypeInfo parameterize(List<TypeInfo> typeArgs) {
if (typeArgs == null || typeArgs.isEmpty()) return this;
Set<ScriptTypeInfo> active = PARAMETERIZING.get();
if (!active.add(this)) {
// Re-entrant call on the same raw type — fall back to shallow parameterization
// (no method/field substitution) to break the infinite recursion.
return super.parameterize(typeArgs);
}
@@ -199,17 +180,14 @@ public class ScriptTypeInfo extends TypeInfo {
// Parameterize methods, constructors, and fields with the generic context of this type.
for (Map.Entry<String, List<MethodInfo>> entry : this.methods.entrySet()) {
List<MethodInfo> substituted = new ArrayList<>();
for (MethodInfo m : entry.getValue()) substituted.add(substituteMethod(m, ctx));
for (MethodInfo m : entry.getValue()) substituted.add(m.substituteTypeParams(ctx));
result.methods.put(entry.getKey(), substituted);
}
for (MethodInfo ctor : this.constructors) {
result.constructors.add(substituteMethod(ctor, ctx));
result.constructors.add(ctor.substituteTypeParams(ctx));
}
for (Map.Entry<String, FieldInfo> entry : this.fields.entrySet()) {
FieldInfo f = entry.getValue();
TypeInfo subType = ctx.substitute(f.getTypeInfo());
result.fields.put(entry.getKey(), subType != f.getTypeInfo()
? FieldInfo.external(f.getName(), subType, null, f.getModifiers()) : f);
result.fields.put(entry.getKey(), entry.getValue().substituteTypeParams(ctx));
}
return result;
} finally {
@@ -310,7 +288,11 @@ public class ScriptTypeInfo extends TypeInfo {
if (enumConstants.containsKey(fieldName))
return true;
for (FieldInfo f : getSyntheticFields())
if (f.getName().equals(fieldName))
return true;
return false;
}
@@ -325,6 +307,10 @@ public class ScriptTypeInfo extends TypeInfo {
return enumConst.getFieldInfo();
}
for (FieldInfo f : getSyntheticFields())
if (f.getName().equals(fieldName))
return f;
return null;
}
@@ -361,6 +347,7 @@ public class ScriptTypeInfo extends TypeInfo {
/**
* Get all enum constants.
*/
@Override
public Map<String, EnumConstantInfo> getEnumConstants() {
return new HashMap<>(enumConstants);
}
@@ -380,32 +367,51 @@ public class ScriptTypeInfo extends TypeInfo {
@Override
public boolean hasMethod(String methodName) {
return methods.containsKey(methodName);
if (methods.containsKey(methodName))
return true;
for (MethodInfo m : getSyntheticMethods())
if (m.getName().equals(methodName))
return true;
return false;
}
@Override
public boolean hasMethod(String methodName, int paramCount) {
List<MethodInfo> overloads = methods.get(methodName);
if (overloads == null) return false;
for (MethodInfo m : overloads) {
if (m.getParameterCount() == paramCount) {
return true;
if (overloads != null) {
for (MethodInfo m : overloads) {
if (m.getParameterCount() == paramCount) {
return true;
}
}
}
for (MethodInfo m : getSyntheticMethods())
if (m.getName().equals(methodName) && m.getParameterCount() == paramCount)
return true;
return false;
}
@Override
public MethodInfo getMethodInfo(String methodName) {
List<MethodInfo> overloads = methods.get(methodName);
return (overloads != null && !overloads.isEmpty()) ? overloads.get(0) : null;
if (overloads != null && !overloads.isEmpty())
return overloads.get(0);
for (MethodInfo m : getSyntheticMethods())
if (m.getName().equals(methodName))
return m;
return null;
}
/**
* Get all method overloads with the given name.
*/
@Override
public List<MethodInfo> getAllMethodOverloads(String methodName) {
return methods.getOrDefault(methodName, new ArrayList<>());
List<MethodInfo> result = new ArrayList<>(methods.getOrDefault(methodName, Collections.emptyList()));
for (MethodInfo m : getSyntheticMethods())
if (m.getName().equals(methodName))
result.add(m);
return result;
}
/**
@@ -432,7 +438,26 @@ public class ScriptTypeInfo extends TypeInfo {
allMethods.addAll(overloads);
}
return allMethods;
}
}
@Override
public List<MethodInfo> getAllMethods() {
List<MethodInfo> result = getAllMethodsFlat();
result.addAll(getSyntheticMethods());
return result;
}
@Override
public List<FieldInfo> getAllFields() {
List<FieldInfo> result = new ArrayList<>(getFields().values());
result.addAll(getSyntheticFields());
return result;
}
@Override
public List<TypeInfo> getAllNestedTypes() {
return new ArrayList<>(innerClasses);
}
// ==================== CONSTRUCTOR MANAGEMENT ====================
@@ -604,6 +604,7 @@ public class TypeInfo {
public boolean isInnerClass() { return enclosingType != null; }
public boolean isInterface() {return kind == Kind.INTERFACE;}
public boolean isEnum() {return kind == Kind.ENUM;}
public boolean isClass() {return kind == Kind.CLASS;}
public boolean isPrimitive() {return this.isPrimitive || javaClass != null && javaClass.isPrimitive();}
private TypeInfo setPrimitive(boolean value) { this.isPrimitive = value; return this;}
@@ -771,6 +772,145 @@ public class TypeInfo {
}
}
/**
* Returns all public instance members of this type for autocomplete/resolution.
* Override in subclasses to extend or replace the default Java reflection path.
*/
public List<MethodInfo> getAllMethods() {
if (javaClass != null) {
// Java reflection path: enumerate public methods + synthetics
List<MethodInfo> result = new ArrayList<>();
try {
for (java.lang.reflect.Method m : javaClass.getMethods()) {
try {
result.add(MethodInfo.fromReflection(m, this));
} catch (Exception e) {
// Skip individual methods that fail (e.g., linkage errors on obscure return types)
}
}
} catch (Exception ignored) {}
result.addAll(getSyntheticMethods());
return result;
}
// javaClass == null: check rawType, jsTypeInfo, synthetics in priority order
if (rawType != null && rawType != this) {
List<MethodInfo> rawMethods = rawType.getAllMethods();
if (!rawMethods.isEmpty() && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
List<MethodInfo> substituted = new ArrayList<>(rawMethods.size());
for (MethodInfo m : rawMethods) {
substituted.add(m.substituteTypeParams(ctx));
}
return substituted;
}
return rawMethods;
}
// No javaClass, no rawType — collect from jsTypeInfo and synthetics
List<MethodInfo> result = new ArrayList<>();
if (jsTypeInfo != null) {
for (JSMethodInfo m : jsTypeInfo.getMethods().values()) {
result.add(MethodInfo.fromJSMethod(m, this));
}
}
result.addAll(getSyntheticMethods());
return result;
}
public List<FieldInfo> getAllFields() {
if (javaClass != null) {
// Java reflection path: enumerate public fields + synthetics
List<FieldInfo> result = new ArrayList<>();
try {
for (java.lang.reflect.Field f : javaClass.getFields()) {
try {
result.add(FieldInfo.fromReflection(f, this));
} catch (Exception e) {
// Skip individual fields that fail rather than losing ALL fields.
}
}
} catch (Exception ignored) {}
result.addAll(getSyntheticFields());
return result;
}
// javaClass == null: check rawType, jsTypeInfo, synthetics in priority order
if (rawType != null && rawType != this) {
List<FieldInfo> rawFields = rawType.getAllFields();
if (!rawFields.isEmpty() && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
List<FieldInfo> substituted = new ArrayList<>(rawFields.size());
for (FieldInfo f : rawFields) {
substituted.add(f.substituteTypeParams(ctx));
}
return substituted;
}
return rawFields;
}
// No javaClass, no rawType — collect from jsTypeInfo and synthetics
List<FieldInfo> result = new ArrayList<>();
if (jsTypeInfo != null) {
for (JSFieldInfo f : jsTypeInfo.getFields().values()) {
result.add(FieldInfo.fromJSField(f, this));
}
}
result.addAll(getSyntheticFields());
return result;
}
/**
* Returns all public nested types (inner classes/interfaces/enums) of this type.
* Uses reflection to discover nested types from the Java class, filters to public only,
* converts internal '$' separators to '.' for name resolution, and resolves each via TypeResolver.
*
* Override in subclasses (e.g., ScriptTypeInfo) to return script-defined inner classes.
*
* @return List of resolved nested TypeInfo instances (may be empty, never null)
*/
public List<TypeInfo> getAllNestedTypes() {
if (javaClass != null) {
List<TypeInfo> result = new ArrayList<>();
try {
for (Class<?> nested : javaClass.getDeclaredClasses()) {
if (!Modifier.isPublic(nested.getModifiers())) {
continue;
}
// Convert JVM internal '$' separator to '.' for TypeResolver lookup
String nestedFullName = nested.getName().replace('$', '.');
TypeInfo nestedType = TypeResolver.getInstance().resolveFullName(nestedFullName);
if (nestedType != null && nestedType.isResolved()) {
result.add(nestedType);
}
}
} catch (SecurityException ignored) {
// Some runtimes may restrict getDeclaredClasses()
}
return result;
}
if (rawType != null && rawType != this) {
return rawType.getAllNestedTypes();
}
// No javaClass, no rawType — check jsTypeInfo for inner types
if (jsTypeInfo != null) {
Map<String, JSTypeInfo> innerTypes = jsTypeInfo.getInnerTypes();
if (!innerTypes.isEmpty()) {
List<TypeInfo> result = new ArrayList<>(innerTypes.size());
for (JSTypeInfo inner : innerTypes.values()) {
TypeInfo ti = TypeInfo.fromJSTypeInfo(inner);
if (ti != null) {
result.add(ti);
}
}
return result;
}
}
return Collections.emptyList();
}
/**
* Check if this type has a method with the given name.
*/
@@ -789,6 +929,8 @@ public class TypeInfo {
} catch (Exception e) {
// Security or linkage error
}
} else if (rawType != null && rawType != this) {
return rawType.hasMethod(methodName);
}
TypeInfo obj = TypeInfo.object();
@@ -817,6 +959,8 @@ public class TypeInfo {
} catch (Exception e) {
// Security or linkage error
}
} else if (rawType != null && rawType != this) {
return rawType.hasMethod(methodName, paramCount);
}
TypeInfo obj = TypeInfo.object();
if (obj != this) return obj.hasMethod(methodName);
@@ -828,13 +972,15 @@ public class TypeInfo {
* Override in ScriptTypeInfo for script-defined types.
*/
public boolean hasConstructors() {
if (javaClass == null) return false;
try {
return javaClass.getConstructors().length > 0;
} catch (Exception e) {
// Security or linkage error
return false;
if (javaClass != null) {
try {
return javaClass.getConstructors().length > 0;
} catch (Exception e) {
return false;
}
}
if (rawType != null && rawType != this) return rawType.hasConstructors();
return false;
}
/**
@@ -843,16 +989,18 @@ public class TypeInfo {
*/
public List<MethodInfo> getConstructors() {
List<MethodInfo> result = new ArrayList<>();
if (javaClass == null) return result;
try {
java.lang.reflect.Constructor<?>[] constructors = javaClass.getConstructors();
for (java.lang.reflect.Constructor<?> ctor : constructors) {
result.add(MethodInfo.fromReflectionConstructor(ctor, this));
if (javaClass != null) {
try {
java.lang.reflect.Constructor<?>[] constructors = javaClass.getConstructors();
for (java.lang.reflect.Constructor<?> ctor : constructors) {
result.add(MethodInfo.fromReflectionConstructor(ctor, this));
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return result;
}
if (rawType != null && rawType != this) return rawType.getConstructors();
return result;
}
@@ -861,45 +1009,49 @@ public class TypeInfo {
* Override in ScriptTypeInfo for script-defined types.
*/
public MethodInfo findConstructor(int argCount) {
if (javaClass == null) return null;
try {
Constructor<?>[] constructors = javaClass.getConstructors();
for (Constructor<?> ctor : constructors) {
if (ctor.getParameterCount() == argCount) {
return MethodInfo.fromReflectionConstructor(ctor, this);
if (javaClass != null) {
try {
Constructor<?>[] constructors = javaClass.getConstructors();
for (Constructor<?> ctor : constructors) {
if (ctor.getParameterCount() == argCount) {
return MethodInfo.fromReflectionConstructor(ctor, this);
}
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return null;
}
if (rawType != null && rawType != this) return rawType.findConstructor(argCount);
return null;
}
public MethodInfo findConstructor(TypeInfo[] argTypes) {
if (javaClass == null) return null;
try {
Constructor<?>[] constructors = javaClass.getConstructors();
for (Constructor<?> ctor : constructors) {
if (ctor.getParameterCount() == argTypes.length) {
Class<?>[] paramTypes = ctor.getParameterTypes();
boolean match = true;
for (int i = 0; i < argTypes.length; i++) {
TypeInfo paramTypeInfo = TypeInfo.fromClass(paramTypes[i]);
if (!TypeChecker.isTypeCompatible(paramTypeInfo, argTypes[i])) {
match = false;
break;
if (javaClass != null) {
try {
Constructor<?>[] constructors = javaClass.getConstructors();
for (Constructor<?> ctor : constructors) {
if (ctor.getParameterCount() == argTypes.length) {
Class<?>[] paramTypes = ctor.getParameterTypes();
boolean match = true;
for (int i = 0; i < argTypes.length; i++) {
TypeInfo paramTypeInfo = TypeInfo.fromClass(paramTypes[i]);
if (!TypeChecker.isTypeCompatible(paramTypeInfo, argTypes[i])) {
match = false;
break;
}
}
if (match) {
return MethodInfo.fromReflectionConstructor(ctor, this);
}
}
if (match) {
return MethodInfo.fromReflectionConstructor(ctor, this);
}
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return null;
}
if (rawType != null && rawType != this) return rawType.findConstructor(argTypes);
return null;
}
@@ -913,30 +1065,63 @@ public class TypeInfo {
return jsTypeInfo.hasField(fieldName);
}
if (javaClass == null) return false;
try {
for (java.lang.reflect.Field f : javaClass.getFields()) {
if (f.getName().equals(fieldName)) {
return true;
if (javaClass != null) {
try {
for (java.lang.reflect.Field f : javaClass.getFields()) {
if (f.getName().equals(fieldName)) {
return true;
}
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return false;
}
if (rawType != null && rawType != this) return rawType.hasField(fieldName);
return false;
}
public boolean hasEnumConstant(String constantName) {
if (javaClass == null || !javaClass.isEnum()) return false;
/**
* Returns all enum constants for this type as a name-to-EnumConstantInfo map.
* For Java enum types, builds the map via reflection. For script-defined enums,
* ScriptTypeInfo overrides this to return its stored constants directly.
*
* @return Map of constant name to EnumConstantInfo (empty if not an enum or no constants)
*/
public Map<String, EnumConstantInfo> getEnumConstants() {
if (javaClass == null || !javaClass.isEnum()) {
if (rawType != null && rawType != this) {
return rawType.getEnumConstants();
}
return Collections.emptyMap();
}
Map<String, EnumConstantInfo> result = new LinkedHashMap<>();
try {
Object[] constants = javaClass.getEnumConstants();
for (Object constant : constants) {
if (constant.toString().equals(constantName))
return true;
String name = constant.toString();
result.put(name, EnumConstantInfo.fromReflection(name, this, null));
}
} catch (Exception e) {
// Security or linkage error
// Security or linkage error — return whatever we have so far
}
return result;
}
public boolean hasEnumConstant(String constantName) {
if (javaClass != null && javaClass.isEnum()) {
try {
Object[] constants = javaClass.getEnumConstants();
for (Object constant : constants) {
if (constant.toString().equals(constantName))
return true;
}
} catch (Exception e) {
// Security or linkage error
}
return false;
}
if (rawType != null && rawType != this) return rawType.hasEnumConstant(constantName);
return false;
}
@@ -944,16 +1129,19 @@ public class TypeInfo {
* Get an enum constant by name.
*/
public EnumConstantInfo getEnumConstant(String constantName) {
if (javaClass == null || !javaClass.isEnum()) return null;
try {
Object[] constants = javaClass.getEnumConstants();
for (Object constant : constants) {
if (constant.toString().equals(constantName))
return EnumConstantInfo.fromReflection(constantName, this, null);
if (javaClass != null && javaClass.isEnum()) {
try {
Object[] constants = javaClass.getEnumConstants();
for (Object constant : constants) {
if (constant.toString().equals(constantName))
return EnumConstantInfo.fromReflection(constantName, this, null);
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return null;
}
if (rawType != null && rawType != this) return rawType.getEnumConstant(constantName);
return null;
}
@@ -976,6 +1164,13 @@ public class TypeInfo {
} catch (Exception e) {
// Security or linkage error
}
} else if (rawType != null && rawType != this) {
MethodInfo rawMethod = rawType.getMethodInfo(methodName);
if (rawMethod != null && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
return rawMethod.substituteTypeParams(ctx);
}
return rawMethod;
}
TypeInfo obj = TypeInfo.object();
if (obj != this) return obj.getMethodInfo(methodName);
@@ -1012,6 +1207,16 @@ public class TypeInfo {
// Security or linkage error
}
if (!overloads.isEmpty()) return overloads;
} else if (rawType != null && rawType != this) {
java.util.List<MethodInfo> rawOverloads = rawType.getAllMethodOverloads(methodName);
if (!rawOverloads.isEmpty() && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
for (MethodInfo m : rawOverloads) {
overloads.add(m.substituteTypeParams(ctx));
}
return overloads;
}
return rawOverloads;
}
TypeInfo obj = TypeInfo.object();
if (obj != this) return obj.getAllMethodOverloads(methodName);
@@ -1078,16 +1283,25 @@ public class TypeInfo {
return null;
}
if (javaClass == null) return null;
try {
for (java.lang.reflect.Field f : javaClass.getFields()) {
if (f.getName().equals(fieldName)) {
// Create a synthetic FieldInfo from reflection
return FieldInfo.fromReflection(f, this);
if (javaClass != null) {
try {
for (java.lang.reflect.Field f : javaClass.getFields()) {
if (f.getName().equals(fieldName)) {
return FieldInfo.fromReflection(f, this);
}
}
} catch (Exception e) {
// Security or linkage error
}
} catch (Exception e) {
// Security or linkage error
return null;
}
if (rawType != null && rawType != this) {
FieldInfo rawField = rawType.getFieldInfo(fieldName);
if (rawField != null && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
return rawField.substituteTypeParams(ctx);
}
return rawField;
}
return null;
}
@@ -1206,7 +1420,17 @@ public class TypeInfo {
return null;
}
// Not a functional interface
// Not a functional interface — try rawType for parameterized script types
if (rawType != null && rawType != this) {
MethodInfo rawSAM = rawType.getSingleAbstractMethod();
if (rawSAM != null && isParameterized()) {
GenericContext ctx = GenericContext.forReceiver(this);
cachedSAM = rawSAM.substituteTypeParams(ctx);
return cachedSAM;
}
cachedSAM = rawSAM;
return cachedSAM;
}
cachedSAM = null;
return null;
@@ -1,146 +0,0 @@
package noppes.npcs.client.gui.util.script.interpreter.type;
import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility for substituting type variables (like T, E, K, V) with concrete types.
*
* Used when resolving members on parameterized types:
* - List<String>.get(int) returns String (not T/Object)
* - Map<String, Integer>.get(Object) returns Integer (not V)
*
* Handles nested generics:
* - List<Map<String, Integer>>.get(0) returns Map<String, Integer>
*/
public class TypeSubstitutor {
/**
* Create a binding map from declared type parameters to applied type arguments.
*
* Example: For List<String> where List is declared as interface List<E>:
* - declaredParams = [TypeParamInfo("E", ...)]
* - appliedArgs = [TypeInfo(String)]
* - Result: {"E" -> TypeInfo(String)}
*
* @param declaredParams The declared type parameters (from the generic type definition)
* @param appliedArgs The applied type arguments (from the parameterized usage)
* @return A map from type parameter names to their concrete TypeInfo values
*/
public static Map<String, TypeInfo> createBindings(List<TypeParamInfo> declaredParams, List<TypeInfo> appliedArgs) {
Map<String, TypeInfo> bindings = new HashMap<>();
if (declaredParams == null || appliedArgs == null) {
return bindings;
}
int count = Math.min(declaredParams.size(), appliedArgs.size());
for (int i = 0; i < count; i++) {
String paramName = declaredParams.get(i).getName();
TypeInfo argType = appliedArgs.get(i);
if (paramName != null && argType != null) {
bindings.put(paramName, argType);
}
}
return bindings;
}
/**
* Create bindings from a parameterized receiver type.
*
* @param receiverType The parameterized type (e.g., List<String>)
* @return Bindings from the type's declared params to its applied args
*/
public static Map<String, TypeInfo> createBindingsFromReceiver(TypeInfo receiverType) {
if (receiverType == null) {
return new HashMap<>();
}
// Get the raw type to access declared type parameters
TypeInfo rawType = receiverType.getRawType();
List<TypeParamInfo> declaredParams = null;
// Get declared params from JSTypeInfo or reflection
if (rawType.isJSType() && rawType.getJSTypeInfo() != null) {
declaredParams = rawType.getJSTypeInfo().getTypeParams();
} else {
declaredParams = rawType.getTypeParams();
}
// Get applied args from the parameterized type
List<TypeInfo> appliedArgs = receiverType.getAppliedTypeArgs();
return createBindings(declaredParams, appliedArgs);
}
/**
* Substitute type variables in a type using the given bindings.
*
* @param type The type to substitute (may contain type variables like T, E)
* @param bindings The map from type variable names to concrete types
* @return The substituted type
*/
public static TypeInfo substitute(TypeInfo type, Map<String, TypeInfo> bindings) {
if (type == null || bindings == null || bindings.isEmpty()) {
return type;
}
String typeName = type.getSimpleName();
// Check if this type is itself a type variable.
// Two cases:
// 1. Unresolved TypeInfo (Java reflection path: TypeInfo.fromGenericType creates these for T, E, K, V)
// 2. TypeInfo.typeParameter() (script-defined path: resolved but tagged as a type parameter)
// For tagged type parameters, use getTypeParameterName() as the lookup key.
if (!type.isResolved() || type.isTypeParameter()) {
String lookupKey = type.isTypeParameter() ? type.getTypeParameterName() : typeName;
TypeInfo substitution = bindings.get(lookupKey);
if (substitution != null) {
return substitution;
}
}
// If the type has applied type arguments, substitute within them recursively
if (type.isParameterized()) {
List<TypeInfo> originalArgs = type.getAppliedTypeArgs();
List<TypeInfo> substitutedArgs = new ArrayList<>();
boolean changed = false;
for (TypeInfo arg : originalArgs) {
TypeInfo substitutedArg = substitute(arg, bindings);
substitutedArgs.add(substitutedArg);
if (substitutedArg != arg) {
changed = true;
}
}
if (changed) {
// Create a new parameterized type with substituted args
return type.getRawType().parameterize(substitutedArgs);
}
}
// Handle array types - substitute the element type
if (type.getSimpleName().endsWith("[]")) {
TypeStringNormalizer.ArraySplit split = TypeStringNormalizer.splitArraySuffixes(typeName);
String elementTypeName = split.base;
int dims = split.dimensions;
TypeInfo elementSubstitution = elementTypeName != null ? bindings.get(elementTypeName) : null;
if (elementSubstitution != null) {
TypeInfo result = elementSubstitution;
for (int i = 0; i < dims; i++) {
result = TypeInfo.arrayOf(result);
}
return result;
}
}
return type;
}
}