Completely parsed type generics.

List<IPlayer> list;
list.get(0) NOW returns IPlayer, instead of T or Object.

Nested generics are also handled and functional:
Map<String, List<IPlayer>>

Implemented TokenHoverInfo/Autocomplete rendering and handling for generics as well.
This commit is contained in:
bigguy345 committed 2026-01-27 17:10:31 +02:00
1 parent 1e96a21cca
commit 5795cc984b
14 files changed
+1306 -154

No files matched your search

@@ -239,16 +239,16 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
if (i > 0) displayName.append(", ");
JSMethodInfo.JSParameterInfo param = method.getParameters().get(i);
// Use resolved type
// Use resolved type with full generic display
TypeInfo paramType = param.getResolvedType(contextType);
String paramTypeName = paramType.isResolved() ? paramType.getSimpleName() : param.getType();
String paramTypeName = paramType.isResolved() ? paramType.getDisplayName() : param.getType();
displayName.append(paramTypeName).append(" ").append(param.getName());
}
displayName.append(")");
// Get return type using the new method
// Get return type using the new method with full generic display
TypeInfo returnTypeInfo = method.getResolvedReturnType(contextType);
String returnType = returnTypeInfo.isResolved() ? returnTypeInfo.getSimpleName() : method.getReturnType();
String returnType = returnTypeInfo.isResolved() ? returnTypeInfo.getDisplayName() : method.getReturnType();
return new AutocompleteItem(
displayName.toString(),
@@ -290,9 +290,9 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
* @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.)
*/
public static AutocompleteItem fromJSField(JSFieldInfo field, TypeInfo contextType, int inheritanceDepth) {
// Get field type using the new method
// Get field type using the new method with full generic display
TypeInfo fieldTypeInfo = field.getResolvedType(contextType);
String fieldType = fieldTypeInfo.isResolved() ? fieldTypeInfo.getSimpleName() : field.getType();
String fieldType = fieldTypeInfo.isResolved() ? fieldTypeInfo.getDisplayName() : field.getType();
return new AutocompleteItem(
field.getName(),
@@ -549,8 +549,16 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
public int getMatchScore() { return matchScore; }
public int[] getMatchIndices() { return matchIndices; }
/**
* Get the display name for a type, including generic arguments.
* Uses the unified getDisplayName() method which handles:
* - Simple types: "String"
* - Parameterized types: "List<String>", "Map<String, Integer>"
* - Nested generics: "List<Map<String, Integer>>"
* - JS types with namespace: "IPlayerEvent.InteractEvent"
*/
public static String getName(TypeInfo type) {
return type.isJSType() ? type.getFullName() : type.getSimpleName();
return type.getDisplayName();
}
public int getParameterCount() {
@@ -1916,52 +1916,130 @@ public class ScriptDocument {
if (typeName == null || typeName.isEmpty())
return TypeInfo.unresolved(typeName, typeName);
// Strip generics for resolution
int genericStart = typeName.indexOf('<');
String baseName = genericStart > 0 ? typeName.substring(0, genericStart) : typeName;
String normalized = typeName.trim();
normalized = stripLeadingModifiers(normalized);
// Strip array brackets
baseName = baseName.replace("[]", "").trim();
// Preserve and resolve nested generics (e.g., List<Map<String, Integer>>)
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(normalized);
if (parsed == null) {
return TypeInfo.unresolved(normalized, normalized);
}
// Check primitive types first
TypeInfo result = resolveJavaFromParsedType(parsed);
return result != null ? result : TypeInfo.unresolved(parsed.baseName, normalized);
}
/**
* Strip only LEADING Java modifiers from a type expression.
* This avoids breaking generic argument lists which may contain whitespace.
*/
private String stripLeadingModifiers(String typeExpr) {
if (typeExpr == null) {
return null;
}
int i = 0;
int len = typeExpr.length();
while (i < len) {
while (i < len && Character.isWhitespace(typeExpr.charAt(i))) i++;
int start = i;
while (i < len && Character.isJavaIdentifierPart(typeExpr.charAt(i))) i++;
if (start == i) {
break;
}
String word = typeExpr.substring(start, i);
if (TypeResolver.isModifier(word)) {
// Continue stripping modifiers
continue;
}
// Not a modifier; rewind to the start of this token
return typeExpr.substring(start).trim();
}
return typeExpr.trim();
}
/**
* Resolve a GenericTypeParser ParsedType for Java/Groovy scripts, preserving type arguments.
* Also tracks import usage for base types and nested type arguments.
*/
private TypeInfo resolveJavaFromParsedType(GenericTypeParser.ParsedType parsed) {
if (parsed == null) {
return null;
}
String baseName = parsed.baseName;
if (baseName == null || baseName.isEmpty()) {
return null;
}
// Normalize whitespace around dots
baseName = baseName.replaceAll("\\s*\\.\\s*", ".").trim();
TypeInfo baseType;
// Primitives
if (TypeResolver.isPrimitiveType(baseName)) {
return TypeInfo.fromPrimitive(baseName);
baseType = TypeInfo.fromPrimitive(baseName);
}
// Common java.lang.String
else if ("String".equals(baseName)) {
baseType = typeResolver.resolveFullName("java.lang.String");
}
// Script-defined types (simple names only)
else if (!baseName.contains(".") && scriptTypes.containsKey(baseName)) {
baseType = scriptTypes.get(baseName);
}
// Fully-qualified
else if (baseName.contains(".")) {
baseType = typeResolver.resolveFullName(baseName);
}
// Imported/simple
else {
baseType = typeResolver.resolveSimpleName(baseName, importsBySimpleName, wildcardPackages);
// Check for String (common case)
if (baseName.equals("String")) {
return typeResolver.resolveFullName("java.lang.String");
}
// Track explicit import usage if present
ImportData usedImport = importsBySimpleName.get(baseName);
if (baseType != null && baseType.isResolved() && usedImport != null) {
usedImport.incrementUsage();
}
// Check script-defined types FIRST
if (scriptTypes.containsKey(baseName)) {
return scriptTypes.get(baseName);
}
// Check if there's an explicit import for this type
ImportData usedImport = importsBySimpleName.get(baseName);
// Try to resolve through imports/classpath
TypeInfo result = typeResolver.resolveSimpleName(baseName, importsBySimpleName, wildcardPackages);
// Track the import usage if we found one and the resolution succeeded
if (result != null && usedImport != null) {
usedImport.incrementUsage();
}
// Also check wildcard imports if the type was resolved through one
if (result != null && usedImport == null && wildcardPackages != null) {
String resultPkg = result.getPackageName();
// Check if resolved through a wildcard
for (ImportData imp : imports) {
if (imp.isWildcard() && resultPkg != null && resultPkg.equals(imp.getFullPath())) {
imp.incrementUsage();
break;
// Track wildcard import usage if resolved through a wildcard
if (baseType != null && baseType.isResolved() && usedImport == null && wildcardPackages != null) {
String resultPkg = baseType.getPackageName();
for (ImportData imp : imports) {
if (imp.isWildcard() && resultPkg != null && resultPkg.equals(imp.getFullPath())) {
imp.incrementUsage();
break;
}
}
}
}
return result;
if (baseType == null) {
baseType = TypeInfo.unresolved(baseName, baseName);
}
// Apply generic arguments
if (parsed.hasTypeArgs() && baseType.isResolved()) {
java.util.List<TypeInfo> resolvedArgs = new java.util.ArrayList<>();
for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) {
TypeInfo argType = resolveJavaFromParsedType(argParsed);
resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName, argParsed.baseName));
}
if (!resolvedArgs.isEmpty()) {
baseType = baseType.parameterize(resolvedArgs);
}
}
// Apply array dimensions
if (parsed.isArray) {
TypeInfo arrayType = baseType;
for (int i = 0; i < parsed.arrayDimensions; i++) {
arrayType = TypeInfo.arrayOf(arrayType);
}
baseType = arrayType;
}
return baseType;
}
// ==================== PHASE 4: BUILD MARKS ====================
@@ -7,6 +7,7 @@ import noppes.npcs.client.gui.util.script.interpreter.bridge.DtsJavaBridge;
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.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;
@@ -146,10 +147,21 @@ public final class FieldInfo {
/**
* Create a FieldInfo from reflection data for a class field.
* Preserves generic type information like List<String>.
*/
public static FieldInfo fromReflection(Field field, TypeInfo containingType) {
String name = field.getName();
TypeInfo type = TypeInfo.fromClass(field.getType());
// Use getGenericType() to preserve generic information
TypeInfo type = TypeInfo.fromGenericType(field.getGenericType());
if (type == null) {
type = TypeInfo.fromClass(field.getType());
}
// If the receiver is parameterized, substitute class type variables in the field type
java.util.Map<String, TypeInfo> receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
if (!receiverBindings.isEmpty()) {
type = TypeSubstitutor.substitute(type, receiverBindings);
}
// Check if this is an enum constant
if (field.isEnumConstant()) {
@@ -545,7 +545,8 @@ public class TokenHoverInfo {
int classColor = clazz.isInterface() ? TokenType.INTERFACE_DECL.getHexColor()
: clazz.isEnum() ? TokenType.ENUM_DECL.getHexColor()
: TokenType.IMPORTED_CLASS.getHexColor();
addSegment(getName(typeInfo), classColor);
// Render generics with correct segment colors if present
addTypeSegments(typeInfo);
// Extends
Class<?> superclass = clazz.getSuperclass();
@@ -604,7 +605,7 @@ public class TokenHoverInfo {
int classColor = scriptType.getKind() == TypeInfo.Kind.INTERFACE ? TokenType.INTERFACE_DECL.getHexColor()
: scriptType.getKind() == TypeInfo.Kind.ENUM ? TokenType.ENUM_DECL.getHexColor()
: TokenType.IMPORTED_CLASS.getHexColor();
addSegment(getName(typeInfo), classColor);
addTypeSegments(typeInfo);
// Extends clause for ScriptTypeInfo
if (scriptType.hasSuperClass()) {
@@ -612,7 +613,7 @@ public class TokenHoverInfo {
TypeInfo superClass = scriptType.getSuperClass();
if (superClass != null && superClass.isResolved()) {
// Color based on resolved type
addSegment(getName(superClass), getColorForTypeInfo(superClass));
addTypeSegments(superClass);
} else {
// Unresolved - show the raw name in undefined color
String superName = scriptType.getSuperClassName();
@@ -642,7 +643,8 @@ public class TokenHoverInfo {
String ifaceName = (i < interfaceNames.size()) ? interfaceNames.get(i) : getName(ifaceType);
if (ifaceType != null && ifaceType.isResolved()) {
addSegment(ifaceName, getColorForTypeInfo(ifaceType));
// Prefer rendering from the resolved TypeInfo so generics color correctly
addTypeSegments(ifaceType);
} else {
addSegment(ifaceName, TokenType.UNDEFINED_VAR.getHexColor());
}
@@ -675,7 +677,7 @@ public class TokenHoverInfo {
iconIndicator = "I";
addSegment("interface ", TokenType.MODIFIER.getHexColor());
addSegment(getName(typeInfo), TokenType.INTERFACE_DECL.getHexColor());
addTypeSegments(typeInfo);
if (jsType.getExtendsType() != null) {
addSegment(" extends ", TokenType.MODIFIER.getHexColor());
@@ -831,8 +833,7 @@ public class TokenHoverInfo {
packageName = pkg;
// Type - check for actual type color
int typeColor = getColorForTypeInfo(declaredType);
addSegment(getName(declaredType), typeColor);
addTypeSegments(declaredType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
@@ -872,8 +873,7 @@ public class TokenHoverInfo {
// Type (enum type name)
int typeColor = getColorForTypeInfo(enumType);
addSegment(getName(enumType), typeColor);
addTypeSegments(enumType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
@@ -900,8 +900,7 @@ public class TokenHoverInfo {
TypeInfo declaredType = fieldInfo.getTypeInfo();
if (declaredType != null) {
int typeColor = getColorForTypeInfo(declaredType);
addSegment(getName(declaredType), typeColor);
addTypeSegments(declaredType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
@@ -948,8 +947,7 @@ public class TokenHoverInfo {
TypeInfo declaredType = fieldInfo.getTypeInfo();
if (declaredType != null) {
int typeColor = getColorForTypeInfo(declaredType);
addSegment(getName(declaredType), typeColor);
addTypeSegments(declaredType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
@@ -963,8 +961,55 @@ public class TokenHoverInfo {
//addSegment(token.getText(), TokenType.UNDEFINED_VAR.getHexColor());
}
/**
* Get the display name for a type, including generic arguments.
* Uses the unified getDisplayName() method which handles:
* - Simple types: "String"
* - Parameterized types: "List<String>", "Map<String, Integer>"
* - Nested generics: "List<Map<String, Integer>>"
* - JS types with namespace: "IPlayerEvent.InteractEvent"
*/
public String getName(TypeInfo type){
return type.isJSType()? type.getFullName() : type.getSimpleName();
return type.getDisplayName();
}
/**
* Add a type name as multiple colored segments so generics render like the editor marks.
* Example: List<String> -> "List" (interface), "<" (default), "String" (class), ">" (default)
*/
private void addTypeSegments(TypeInfo typeInfo) {
addTypeSegments(typeInfo, 0);
}
private void addTypeSegments(TypeInfo typeInfo, int depth) {
if (typeInfo == null) {
addSegment("any", TokenType.DEFAULT.getHexColor());
return;
}
if (depth > 25) {
// Safety guard against pathological recursive types
addSegment(getName(typeInfo), getColorForTypeInfo(typeInfo));
return;
}
if (typeInfo.isParameterized()) {
TypeInfo raw = typeInfo.getRawType();
addSegment(getName(raw), getColorForTypeInfo(raw));
addSegment("<", TokenType.DEFAULT.getHexColor());
java.util.List<TypeInfo> args = typeInfo.getAppliedTypeArgs();
for (int i = 0; i < args.size(); i++) {
if (i > 0) {
addSegment(", ", TokenType.DEFAULT.getHexColor());
}
addTypeSegments(args.get(i), depth + 1);
}
addSegment(">", TokenType.DEFAULT.getHexColor());
return;
}
addSegment(getName(typeInfo), getColorForTypeInfo(typeInfo));
}
private void extractFieldInfoGeneric(Token token) {
@@ -1003,8 +1048,7 @@ public class TokenHoverInfo {
FieldInfo param = params.get(i);
TypeInfo paramType = param.getTypeInfo();
if (paramType != null) {
int paramTypeColor = getColorForTypeInfo(paramType);
addSegment(getName(paramType), paramTypeColor);
addTypeSegments(paramType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
addSegment(param.getName(), TokenType.PARAMETER.getHexColor());
@@ -1082,8 +1126,7 @@ public class TokenHoverInfo {
// Return type
TypeInfo returnType = methodInfo.getReturnType();
if (returnType != null) {
int returnTypeColor = getColorForTypeInfo(returnType);
addSegment(getName(returnType), returnTypeColor);
addTypeSegments(returnType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
} else {
addSegment("void ", TokenType.KEYWORD.getHexColor());
@@ -1100,8 +1143,7 @@ public class TokenHoverInfo {
FieldInfo param = params.get(i);
TypeInfo paramType = param.getTypeInfo();
if (paramType != null) {
int paramTypeColor = getColorForTypeInfo(paramType);
addSegment(getName(paramType), paramTypeColor);
addTypeSegments(paramType);
addSegment(" ", TokenType.DEFAULT.getHexColor());
}
addSegment(param.getName(), TokenType.PARAMETER.getHexColor());
@@ -79,11 +79,12 @@ public class JSFieldInfo {
}
/**
* Get display name - uses resolved TypeInfo simple name if available.
* Get display name - uses resolved TypeInfo display name if available,
* including generic type arguments like List<String>.
*/
public String getDisplayType() {
if (typeInfo != null && typeInfo.isResolved()) {
return typeInfo.getSimpleName();
return typeInfo.getDisplayName();
}
return type;
}
@@ -3,6 +3,7 @@ package noppes.npcs.client.gui.util.script.interpreter.js_parser;
import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver;
import noppes.npcs.client.gui.util.script.interpreter.type.TypeSubstitutor;
import java.util.*;
@@ -47,24 +48,31 @@ public class JSMethodInfo {
}
/**
* Get the resolved return type, with fallback resolution using type parameters.
* @param contextType The TypeInfo context for resolving type parameters (e.g., IPlayer to resolve T → EntityPlayerMP)
* @return The resolved TypeInfo for the return type
* Get the resolved return type, with type parameter substitution based on receiver context.
*
* For parameterized receivers like List<String>, this will substitute type variables:
* - If return type is "T" and receiver is List<String>, returns TypeInfo(String)
* - Handles nested generics like List<Map<K,V>> with proper substitution
*
* @param contextType The TypeInfo context for resolving type parameters (e.g., List<String> to resolve E → String)
* @return The resolved TypeInfo for the return type, with type variables substituted
*/
public TypeInfo getResolvedReturnType(TypeInfo contextType) {
// Use pre-resolved if available
if (returnTypeInfo != null && returnTypeInfo.isResolved())
return returnTypeInfo;
// Fall back to resolving from string
TypeResolver resolver = TypeResolver.getInstance();
TypeInfo resolved = returnTypeInfo = resolver.resolveJSType(returnType);
// If not resolved and contextType has type parameters, try to resolve as type parameter
if (contextType != null && !resolved.isResolved()) {
// First, resolve the return type string to a TypeInfo (now preserves generic args)
TypeInfo resolved = resolver.resolveJSType(returnType);
// If we have a parameterized context, apply type variable substitution
if (contextType != null && contextType.isParameterized()) {
resolved = TypeSubstitutor.getSubstitutedReturnType(resolved, returnType, contextType, resolver);
}
// Fallback: if not resolved and contextType has declared type parameters, try direct resolution
else if (contextType != null && !resolved.isResolved()) {
TypeInfo paramResolution = contextType.resolveTypeParamToTypeInfo(returnType);
if (paramResolution != null)
resolved = returnTypeInfo = paramResolution; //cache it to returnTypeInfo
if (paramResolution != null) {
resolved = paramResolution;
}
}
return resolved;
@@ -150,24 +158,30 @@ public class JSMethodInfo {
}
/**
* Get the resolved type, with fallback resolution using type parameters.
* Get the resolved type, with type parameter substitution based on receiver context.
*
* For parameterized receivers like Consumer<IAction>, this will substitute type variables:
* - If param type is "T" and receiver is Consumer<IAction>, returns TypeInfo(IAction)
*
* @param contextType The TypeInfo context for resolving type parameters
* @return The resolved TypeInfo for the parameter type
*/
public TypeInfo getResolvedType(TypeInfo contextType) {
// Use pre-resolved if available
if (typeInfo != null && typeInfo.isResolved())
return typeInfo;
// Fall back to resolving from string
TypeResolver resolver = TypeResolver.getInstance();
TypeInfo resolved = typeInfo = resolver.resolveJSType(type);
// If not resolved and contextType has type parameters, try to resolve as type parameter
if (contextType != null && !resolved.isResolved()) {
// First, resolve the type string to a TypeInfo (now preserves generic args)
TypeInfo resolved = resolver.resolveJSType(type);
// If we have a parameterized context, apply type variable substitution
if (contextType != null && contextType.isParameterized()) {
resolved = TypeSubstitutor.getSubstitutedReturnType(resolved, type, contextType, resolver);
}
// Fallback: if not resolved and contextType has declared type parameters, try direct resolution
else if (contextType != null && !resolved.isResolved()) {
TypeInfo paramResolution = contextType.resolveTypeParamToTypeInfo(type);
if (paramResolution != null)
resolved = typeInfo = paramResolution; //cache it to typeInfo
if (paramResolution != null) {
resolved = paramResolution;
}
}
return resolved;
@@ -179,11 +193,12 @@ public class JSMethodInfo {
public JSMethodInfo getContainingMethod() {return containingMethod;}
/**
* Get display name - uses resolved TypeInfo simple name if available.
* Get display name - uses resolved TypeInfo display name if available,
* including generic type arguments like List<String>.
*/
public String getDisplayType() {
if (typeInfo != null && typeInfo.isResolved()) {
return typeInfo.getSimpleName();
return typeInfo.getDisplayName();
}
return type;
}
@@ -48,18 +48,18 @@ public class TypeParamInfo {
}
/**
* Get simple display name for the bound type.
* Get display name for the bound type, including generic arguments.
*/
public String getBoundTypeName() {
if (boundTypeInfo == null)
return null;
return boundTypeInfo.getSimpleName();
return boundTypeInfo.getDisplayName();
}
@Override
public String toString() {
if (boundTypeInfo != null) {
return name + " extends " + boundTypeInfo.getSimpleName();
return name + " extends " + boundTypeInfo.getDisplayName();
} else if (boundType != null || fullBoundType != null) {
return name + " extends " + (boundType != null ? boundType : fullBoundType);
}
@@ -40,13 +40,13 @@ public class TypeScriptDefinitionParser {
"export\\s+type\\s+(\\w+)\\s*=\\s*([^;\\n]+);?");
private static final Pattern METHOD_PATTERN = Pattern.compile(
"^\\s*(\\w+)\\s*\\(([^)]*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
"(?m)^\\s*(\\w+)\\s*\\((.*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
private static final Pattern FIELD_PATTERN = Pattern.compile(
"^\\s*(readonly\\s+)?(\\w+)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
private static final Pattern GLOBAL_FUNCTION_PATTERN = Pattern.compile(
"function\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*:\\s*([^;]+);");
"function\\s+(\\w+)\\s*\\((.*)\\)\\s*:\\s*([^;]+);");
private static final Pattern GLOBAL_TYPE_ALIAS_PATTERN = Pattern.compile(
"type\\s+(\\w+)\\s*=\\s*import\\(['\"]([^'\"]+)['\"]\\)\\.([\\w.]+);");
@@ -666,19 +666,53 @@ public class TypeScriptDefinitionParser {
private String cleanType(String type) {
if (type == null) return "any";
type = type.trim();
// Handle import('./path').TypeName syntax
if (type.startsWith("import(")) {
// Extract the type name after the import
int dotIndex = type.lastIndexOf(").");
if (dotIndex > 0) {
type = type.substring(dotIndex + 2);
// Strip TypeScript import() type references anywhere in the string.
// Examples:
// - import('./data/IAction').IAction -> IAction
// - Java.java.util.function.Consumer<import('./x').T> -> Java.java.util.function.Consumer<T>
// This is important because import() can appear nested inside generics.
int importIdx;
while ((importIdx = type.indexOf("import(")) >= 0) {
int i = importIdx + "import(".length();
int depth = 1;
boolean inString = false;
char stringChar = 0;
while (i < type.length() && depth > 0) {
char c = type.charAt(i);
if (inString) {
if (c == stringChar && (i == 0 || type.charAt(i - 1) != '\\')) {
inString = false;
}
} else {
if (c == '\'' || c == '"') {
inString = true;
stringChar = c;
} else if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
}
}
i++;
}
// i is positioned just after the matching ')', if found.
if (depth != 0) {
break; // Unbalanced import( ... ) - stop trying to clean.
}
// If immediately followed by ".", remove "import(...) ." prefix.
if (i < type.length() && type.charAt(i) == '.') {
int removeEnd = i + 1;
type = type.substring(0, importIdx) + type.substring(removeEnd);
} else {
// Remove just the import(...) portion.
type = type.substring(0, importIdx) + type.substring(i);
}
}
// Handle arrays
type = type.replace("[]", "[]");
return type;
}
@@ -388,8 +388,8 @@ public class MethodCallInfo {
TypeInfo paramType = para.getTypeInfo();
if (argType != null && paramType != null) {
if (!TypeChecker.isTypeCompatible(paramType, argType)) {
setArgTypeError(i, "Expected " + paramType.getSimpleName() +
" but got " + argType.getSimpleName());
setArgTypeError(i, "Expected " + paramType.getDisplayName() +
" but got " + argType.getDisplayName());
}
} else if (paramType == null) {
setArgTypeError(i, "Parameter type of '" + para.getName() + "' is unresolved");
@@ -10,6 +10,7 @@ import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry;
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
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 java.lang.reflect.Constructor;
import java.lang.reflect.Method;
@@ -140,10 +141,15 @@ public final class MethodInfo {
/**
* Create a MethodInfo from reflection data.
* Used when resolving method calls on known types.
* Preserves generic type information from reflection.
*/
public static MethodInfo fromReflection(Method method, TypeInfo containingType) {
String name = method.getName();
TypeInfo returnType = TypeInfo.fromClass(method.getReturnType());
// Use getGenericReturnType() to preserve generic information like List<String>
TypeInfo returnType = TypeInfo.fromGenericType(method.getGenericReturnType());
if (returnType == null) {
returnType = TypeInfo.fromClass(method.getReturnType());
}
int modifiers = method.getModifiers();
// Try to find matching JSMethodInfo to bridge parameter names/docs and allow return overrides
@@ -166,11 +172,25 @@ public final class MethodInfo {
}
}
}
// If the receiver is parameterized (e.g., List<String>), substitute class type variables (E -> String)
java.util.Map<String, TypeInfo> receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
if (!receiverBindings.isEmpty()) {
returnType = TypeSubstitutor.substitute(returnType, receiverBindings);
}
List<FieldInfo> params = new ArrayList<>();
Class<?>[] paramTypes = method.getParameterTypes();
// Use getGenericParameterTypes() to preserve generic information
java.lang.reflect.Type[] genericParamTypes = method.getGenericParameterTypes();
List<JSMethodInfo.JSParameterInfo> jsParams = jsMethod != null ? jsMethod.getParameters() : null;
for (int i = 0; i < paramTypes.length; i++) {
TypeInfo paramType = TypeInfo.fromClass(paramTypes[i]);
for (int i = 0; i < genericParamTypes.length; i++) {
TypeInfo paramType = TypeInfo.fromGenericType(genericParamTypes[i]);
if (paramType == null) {
paramType = TypeInfo.fromClass(method.getParameterTypes()[i]);
}
if (!receiverBindings.isEmpty()) {
paramType = TypeSubstitutor.substitute(paramType, receiverBindings);
}
String paramName = "arg" + i;
if (jsParams != null && i < jsParams.size()) {
String jsName = jsParams.get(i).getName();
@@ -199,6 +219,7 @@ public final class MethodInfo {
/**
* Create a MethodInfo from a Constructor via reflection.
* Used when resolving constructor calls on external types.
* Preserves generic type information for constructor parameters.
*/
public static MethodInfo fromReflectionConstructor(Constructor<?> constructor, TypeInfo containingType) {
String name = containingType.getSimpleName(); // Constructor name is the type name
@@ -206,9 +227,13 @@ public final class MethodInfo {
int modifiers = constructor.getModifiers();
List<FieldInfo> params = new ArrayList<>();
Class<?>[] paramTypes = constructor.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
TypeInfo paramType = TypeInfo.fromClass(paramTypes[i]);
// Use getGenericParameterTypes() to preserve generic information
java.lang.reflect.Type[] genericParamTypes = constructor.getGenericParameterTypes();
for (int i = 0; i < genericParamTypes.length; i++) {
TypeInfo paramType = TypeInfo.fromGenericType(genericParamTypes[i]);
if (paramType == null) {
paramType = TypeInfo.fromClass(constructor.getParameterTypes()[i]);
}
params.add(FieldInfo.reflectionParam("arg" + i, paramType));
}
@@ -605,7 +630,7 @@ public final class MethodInfo {
// Check for unresolved parameter types
TypeInfo paramType = param.getTypeInfo();
if (paramType == null || !paramType.isResolved()) {
String typeName = paramType != null ? paramType.getSimpleName() : "unknown";
String typeName = paramType != null ? paramType.getDisplayName() : "unknown";
addParameterError(param, i, ErrorType.PARAMETER_UNDEFINED,
"Cannot resolve parameter type '" + typeName + "'");
}
@@ -639,7 +664,7 @@ public final class MethodInfo {
if (bodyText == null || bodyText.isEmpty()) return;
boolean isVoid = TypeChecker.isVoidType(returnType);
String expectedTypeName = isVoid ? "void" : returnType.getSimpleName();
String expectedTypeName = isVoid ? "void" : returnType.getDisplayName();
// Remove comments but keep strings (we need accurate positions)
String cleanBody = CodeParser.removeComments(bodyText);
@@ -0,0 +1,432 @@
package noppes.npcs.client.gui.util.script.interpreter.type;
import java.util.ArrayList;
import java.util.List;
/**
* Parser for generic type expressions with nested type arguments.
*
* Handles type expressions like:
* - Simple types: "String", "IPlayer"
* - Qualified names: "java.util.List", "IPlayerEvent.InteractEvent"
* - Single generic: "List<String>", "Consumer<IAction>"
* - Multiple generics: "Map<String, Integer>"
* - Nested generics: "List<Map<String, Integer>>"
* - Arrays: "String[]", "List<String>[]"
* - Nullable: "String?"
* - Union types: "String | null" (uses first type for resolution)
*
* This parser produces a ParsedType tree that can be resolved into parameterized TypeInfo instances.
*/
public class GenericTypeParser {
/**
* Represents a parsed type expression with potential generic arguments.
*/
public static class ParsedType {
/** The base type name (may be qualified, e.g., "java.util.List" or "IPlayer") */
public final String baseName;
/** The applied type arguments (for generics like List<String>), each is itself a ParsedType */
public final List<ParsedType> typeArgs;
/** Whether this type is an array (has [] suffix) */
public final boolean isArray;
/** Array dimensions (1 for T[], 2 for T[][], etc.) */
public final int arrayDimensions;
/** Whether this type is nullable (has ? suffix in TypeScript) */
public final boolean isNullable;
/** The original raw string before parsing */
public final String rawString;
public ParsedType(String baseName, List<ParsedType> typeArgs, boolean isArray,
int arrayDimensions, boolean isNullable, String rawString) {
this.baseName = baseName;
this.typeArgs = typeArgs != null ? typeArgs : new ArrayList<>();
this.isArray = isArray;
this.arrayDimensions = arrayDimensions;
this.isNullable = isNullable;
this.rawString = rawString;
}
/**
* Check if this parsed type has generic arguments.
*/
public boolean hasTypeArgs() {
return !typeArgs.isEmpty();
}
/**
* Get display string for debugging.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(baseName);
if (!typeArgs.isEmpty()) {
sb.append("<");
for (int i = 0; i < typeArgs.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(typeArgs.get(i).toString());
}
sb.append(">");
}
for (int i = 0; i < arrayDimensions; i++) {
sb.append("[]");
}
if (isNullable) {
sb.append("?");
}
return sb.toString();
}
}
/**
* Parse a type expression string into a ParsedType tree.
*
* @param typeExpr The type expression to parse (e.g., "List<Map<String, Integer>>[]")
* @return The parsed type, or null if parsing fails
*/
public static ParsedType parse(String typeExpr) {
if (typeExpr == null || typeExpr.isEmpty()) {
return null;
}
String expr = typeExpr.trim();
// Handle union types - use first type (same as current behavior)
if (expr.contains("|")) {
String[] parts = expr.split("\\|");
expr = parts[0].trim();
}
// Handle nullable marker (TypeScript ?), remove it but track
boolean isNullable = false;
if (expr.endsWith("?")) {
isNullable = true;
expr = expr.substring(0, expr.length() - 1).trim();
}
// Count and strip array dimensions
int arrayDims = 0;
while (expr.endsWith("[]")) {
arrayDims++;
expr = expr.substring(0, expr.length() - 2).trim();
}
// Now parse the base type with potential generic arguments
ParseResult result = parseTypeWithGenerics(expr, 0);
if (result == null || result.type == null) {
// Fallback: treat entire expression as a simple type
return new ParsedType(expr, null, arrayDims > 0, arrayDims, isNullable, typeExpr);
}
ParsedType parsed = result.type;
// Apply array and nullable modifiers
return new ParsedType(parsed.baseName, parsed.typeArgs,
arrayDims > 0, arrayDims, isNullable, typeExpr);
}
/**
* Internal result class for recursive parsing.
*/
private static class ParseResult {
final ParsedType type;
final int endIndex; // position after this type in the string
ParseResult(ParsedType type, int endIndex) {
this.type = type;
this.endIndex = endIndex;
}
}
/**
* Parse a type expression starting at the given index, handling nested generics.
* Returns the parsed type and the index after this type expression.
*/
private static ParseResult parseTypeWithGenerics(String expr, int startIndex) {
int i = startIndex;
int len = expr.length();
// Skip leading whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
if (i >= len) {
return null;
}
// Special-case: TypeScript import() type references like import('./x').TypeName
// We normalize these to just the referenced type name (e.g., "TypeName" or "Ns.TypeName").
String baseName;
if (expr.startsWith("import(", i)) {
int j = i + "import(".length();
int depth = 1;
boolean inString = false;
char stringChar = 0;
while (j < len && depth > 0) {
char c = expr.charAt(j);
if (inString) {
if (c == stringChar && (j == 0 || expr.charAt(j - 1) != '\\')) {
inString = false;
}
} else {
if (c == '\'' || c == '"') {
inString = true;
stringChar = c;
} else if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
}
}
j++;
}
// j is positioned just after ')'
i = j;
// Skip whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
// Optional dot before the referenced type
if (i < len && expr.charAt(i) == '.') {
i++;
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
}
StringBuilder nameBuilder = new StringBuilder();
while (i < len) {
char c = expr.charAt(i);
if (Character.isJavaIdentifierPart(c) || c == '.') {
nameBuilder.append(c);
i++;
} else {
break;
}
}
baseName = nameBuilder.toString().trim();
} else {
// Read the base type name (can include dots for qualified names)
StringBuilder baseNameBuilder = new StringBuilder();
while (i < len) {
char c = expr.charAt(i);
if (Character.isJavaIdentifierPart(c) || c == '.') {
baseNameBuilder.append(c);
i++;
} else {
break;
}
}
baseName = baseNameBuilder.toString().trim();
}
if (baseName.isEmpty()) {
return null;
}
// Remove trailing dots if any
while (baseName.endsWith(".")) {
baseName = baseName.substring(0, baseName.length() - 1);
}
// Skip whitespace before potential <
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
// Check for generic arguments
List<ParsedType> typeArgs = new ArrayList<>();
if (i < len && expr.charAt(i) == '<') {
i++; // Skip '<'
// Parse type arguments (comma-separated, handling nested <>)
while (i < len) {
// Skip whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
if (i >= len) break;
char c = expr.charAt(i);
if (c == '>') {
i++; // Skip '>'
break;
}
if (c == ',') {
i++; // Skip ','
continue;
}
// Parse a type argument (may itself have generics)
ParseResult argResult = parseTypeArgument(expr, i);
if (argResult != null && argResult.type != null) {
typeArgs.add(argResult.type);
i = argResult.endIndex;
} else {
// Skip forward until the next ',' or '>' at the current nesting level.
i = skipToNextTypeArgDelimiter(expr, i);
}
}
}
ParsedType type = new ParsedType(baseName, typeArgs, false, 0, false, expr.substring(startIndex, i));
return new ParseResult(type, i);
}
/**
* Skip forward until we hit ',' or '>' that would delimit a type argument.
* This prevents producing spurious additional type args when encountering unsupported syntax.
*/
private static int skipToNextTypeArgDelimiter(String expr, int startIndex) {
int i = startIndex;
int depth = 0;
boolean inString = false;
char stringChar = 0;
while (i < expr.length()) {
char c = expr.charAt(i);
if (inString) {
if (c == stringChar && (i == 0 || expr.charAt(i - 1) != '\\')) {
inString = false;
}
i++;
continue;
}
if (c == '\'' || c == '"') {
inString = true;
stringChar = c;
i++;
continue;
}
if (c == '<' || c == '(' || c == '[') {
depth++;
} else if (c == '>' || c == ')' || c == ']') {
if (depth > 0) {
depth--;
} else if (c == '>') {
return i; // Let caller handle closing '>'
}
} else if ((c == ',' || c == '>') && depth == 0) {
return i;
}
i++;
}
return i;
}
/**
* Parse a single type argument, which may include nested generics and array suffixes.
*/
private static ParseResult parseTypeArgument(String expr, int startIndex) {
int i = startIndex;
int len = expr.length();
// Skip leading whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
if (i >= len) {
return null;
}
// Check for wildcard (? extends X, ? super X, or just ?)
if (expr.charAt(i) == '?') {
i++;
// Skip whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
// Check for "extends" or "super"
if (i < len && expr.substring(i).startsWith("extends ")) {
i += 8; // Skip "extends "
// Parse the bound type
ParseResult boundResult = parseTypeWithGenerics(expr, i);
if (boundResult != null) {
return boundResult;
}
} else if (i < len && expr.substring(i).startsWith("super ")) {
i += 6; // Skip "super "
// Parse the bound type
ParseResult boundResult = parseTypeWithGenerics(expr, i);
if (boundResult != null) {
return boundResult;
}
}
// Plain wildcard, treat as Object
return new ParseResult(new ParsedType("Object", null, false, 0, false, "?"), i);
}
// Parse regular type with potential generics
ParseResult typeResult = parseTypeWithGenerics(expr, i);
if (typeResult == null) {
return null;
}
i = typeResult.endIndex;
ParsedType baseType = typeResult.type;
// Skip whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
// Check for array suffix
int arrayDims = 0;
while (i + 1 < len && expr.charAt(i) == '[' && expr.charAt(i + 1) == ']') {
arrayDims++;
i += 2;
// Skip whitespace
while (i < len && Character.isWhitespace(expr.charAt(i))) {
i++;
}
}
// Check for nullable suffix
boolean isNullable = false;
if (i < len && expr.charAt(i) == '?') {
isNullable = true;
i++;
}
// If we have array dims or nullable, wrap the base type
if (arrayDims > 0 || isNullable) {
return new ParseResult(
new ParsedType(baseType.baseName, baseType.typeArgs, arrayDims > 0, arrayDims, isNullable,
expr.substring(startIndex, i)),
i
);
}
return new ParseResult(baseType, i);
}
/**
* Convenience method to check if a type string contains generic arguments.
*/
public static boolean hasGenerics(String typeExpr) {
return typeExpr != null && typeExpr.contains("<") && typeExpr.contains(">");
}
/**
* Strip generic arguments from a type string (for base type lookup).
* Example: "List<String>" -> "List"
*/
public static String stripGenerics(String typeExpr) {
if (typeExpr == null) return null;
int idx = typeExpr.indexOf('<');
if (idx > 0) {
return typeExpr.substring(0, idx).trim();
}
return typeExpr;
}
}
@@ -11,6 +11,11 @@ import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.List;
@@ -63,20 +68,34 @@ public class TypeInfo {
// JavaScript/TypeScript type info (for types from .d.ts files)
private final JSTypeInfo jsTypeInfo; // The JS type info (null if Java type)
// Type parameters (generics)
// Declared type parameters (generics definition, e.g., "T extends Entity" on interface List<T>)
private final List<TypeParamInfo> typeParams = new ArrayList<>();
// Applied type arguments (concrete types provided for generics, e.g., <String, Integer> in Map<String, Integer>)
// These are TypeInfo instances that can themselves be parameterized for nested generics
private final List<TypeInfo> appliedTypeArgs = new ArrayList<>();
// For parameterized types, the raw/base type (e.g., List for List<String>)
// Null for non-parameterized types
private final TypeInfo rawType;
// Documentation (script-defined types)
private JSDocInfo jsDocInfo;
private TypeInfo(String simpleName, String fullName, String packageName,
Kind kind, Class<?> javaClass, boolean resolved, TypeInfo enclosingType) {
this(simpleName, fullName, packageName, kind, javaClass, resolved, enclosingType, null);
this(simpleName, fullName, packageName, kind, javaClass, resolved, enclosingType, null, null, null);
}
private TypeInfo(String simpleName, String fullName, String packageName,
Kind kind, Class<?> javaClass, boolean resolved, TypeInfo enclosingType,
JSTypeInfo jsTypeInfo) {
this(simpleName, fullName, packageName, kind, javaClass, resolved, enclosingType, jsTypeInfo, null, null);
}
private TypeInfo(String simpleName, String fullName, String packageName,
Kind kind, Class<?> javaClass, boolean resolved, TypeInfo enclosingType,
JSTypeInfo jsTypeInfo, TypeInfo rawType, List<TypeInfo> appliedTypeArgs) {
this.simpleName = simpleName;
this.fullName = fullName;
this.packageName = packageName;
@@ -85,6 +104,10 @@ public class TypeInfo {
this.resolved = resolved;
this.enclosingType = enclosingType;
this.jsTypeInfo = jsTypeInfo;
this.rawType = rawType;
if (appliedTypeArgs != null) {
this.appliedTypeArgs.addAll(appliedTypeArgs);
}
}
// Protected constructor for subclasses (like ScriptTypeInfo)
@@ -99,6 +122,7 @@ public class TypeInfo {
this.resolved = resolved;
this.enclosingType = enclosingType;
this.jsTypeInfo = null;
this.rawType = null;
}
// Factory methods
@@ -151,6 +175,94 @@ public class TypeInfo {
return new TypeInfo(simpleName, fullName, packageName, kind, clazz, true, enclosing);
}
/**
* Create a TypeInfo from a generic java.lang.reflect.Type.
* This preserves generic type arguments from reflection APIs like
* Method.getGenericReturnType() and Field.getGenericType().
*
* Examples:
* - List<String> -> TypeInfo(List) with appliedTypeArgs=[TypeInfo(String)]
* - Map<String, Integer> -> TypeInfo(Map) with appliedTypeArgs=[TypeInfo(String), TypeInfo(Integer)]
* - T (type variable) -> TypeInfo representing the type variable name
*
* @param type The generic type from reflection
* @return A TypeInfo preserving the generic structure, or null if type is null
*/
public static TypeInfo fromGenericType(Type type) {
if (type == null) return null;
if (type instanceof Class<?>) {
// Plain class - no generic info
return fromClass((Class<?>) type);
}
if (type instanceof ParameterizedType) {
// Generic type like List<String>
ParameterizedType paramType = (ParameterizedType) type;
Type rawType = paramType.getRawType();
if (!(rawType instanceof Class<?>)) {
// Edge case - should not happen normally
return rawType != null ? fromGenericType(rawType) : null;
}
// Get the raw type as TypeInfo
TypeInfo rawTypeInfo = fromClass((Class<?>) rawType);
// Recursively convert type arguments
Type[] typeArgs = paramType.getActualTypeArguments();
List<TypeInfo> appliedArgs = new ArrayList<>(typeArgs.length);
for (Type arg : typeArgs) {
TypeInfo argInfo = fromGenericType(arg);
if (argInfo != null) {
appliedArgs.add(argInfo);
}
}
// Return a parameterized TypeInfo
if (!appliedArgs.isEmpty()) {
return rawTypeInfo.parameterize(appliedArgs);
}
return rawTypeInfo;
}
if (type instanceof GenericArrayType) {
// Array of generic type, e.g. T[] or List<String>[]
GenericArrayType arrayType = (GenericArrayType) type;
TypeInfo elementType = fromGenericType(arrayType.getGenericComponentType());
if (elementType != null) {
return arrayOf(elementType);
}
return fromClass(Object[].class);
}
if (type instanceof TypeVariable<?>) {
// Type variable like T, E, K, V
TypeVariable<?> typeVar = (TypeVariable<?>) type;
String varName = typeVar.getName();
// Create an unresolved type representing the type variable
// The substitution system will handle replacing this with the actual type
return TypeInfo.unresolved(varName, varName);
}
if (type instanceof WildcardType) {
// Wildcard like ? or ? extends Number or ? super Integer
WildcardType wildcard = (WildcardType) type;
Type[] upperBounds = wildcard.getUpperBounds();
// Use the upper bound if available (most useful for ? extends T)
if (upperBounds.length > 0 && upperBounds[0] != Object.class) {
return fromGenericType(upperBounds[0]);
}
// For ? super T or plain ?, just use Object
return fromClass(Object.class);
}
// Unknown type - shouldn't happen in practice
return null;
}
/**
* Create a TypeInfo for a primitive type.
*/
@@ -199,9 +311,10 @@ public class TypeInfo {
if (elementType == null) {
return fromClass(Object[].class);
}
String simpleName = elementType.getSimpleName() + "[]";
String fullName = elementType.getFullName() + "[]";
// Preserve generic display in arrays (e.g., List<String>[]) and keep JS namespace display.
String simpleName = elementType.getDisplayName() + "[]";
String fullName = elementType.getDisplayNameFull() + "[]";
String pkg = elementType.getPackageName();
// Try to get the actual array class if we have a Java class
@@ -253,6 +366,125 @@ public class TypeInfo {
public boolean isEnum() {return kind == Kind.ENUM;}
public boolean isPrimitive() {return javaClass != null && javaClass.isPrimitive();}
// ==================== Applied Type Arguments (Parameterized Types) ====================
/**
* Check if this type is parameterized (has applied type arguments).
* For example, List<String> is parameterized, but List is not.
*/
public boolean isParameterized() {
return !appliedTypeArgs.isEmpty();
}
/**
* Get the raw/base type if this is parameterized.
* For List<String>, returns the TypeInfo for List.
* For non-parameterized types, returns this.
*/
public TypeInfo getRawType() {
return rawType != null ? rawType : this;
}
/**
* Get the applied type arguments.
* For List<String>, returns [TypeInfo(String)].
* For Map<String, Integer>, returns [TypeInfo(String), TypeInfo(Integer)].
* For nested generics like List<Map<String, Integer>>, the Map TypeInfo itself has appliedTypeArgs.
*/
public List<TypeInfo> getAppliedTypeArgs() {
return appliedTypeArgs;
}
/**
* Create a parameterized version of this type with the given type arguments.
* For example, calling parameterize([TypeInfo(String)]) on List returns List<String>.
*
* @param typeArgs The type arguments to apply
* @return A new parameterized TypeInfo
*/
public TypeInfo parameterize(List<TypeInfo> typeArgs) {
if (typeArgs == null || typeArgs.isEmpty()) {
return this;
}
// Keep base names stable for logic (constructor names, lookups, etc.).
// Generic arguments are tracked via appliedTypeArgs and rendered via getDisplayName*().
TypeInfo raw = getRawType();
return new TypeInfo(raw.simpleName, raw.fullName, raw.packageName, raw.kind, raw.javaClass,
raw.resolved, raw.enclosingType, raw.jsTypeInfo, raw, typeArgs);
}
/**
* Create a parameterized version of this type with a single type argument.
*/
public TypeInfo parameterize(TypeInfo typeArg) {
if (typeArg == null) {
return this;
}
List<TypeInfo> args = new ArrayList<>();
args.add(typeArg);
return parameterize(args);
}
/**
* Build the generic type arguments string like "<String, Integer>".
* @param typeArgs The type arguments
* @param useFullNames Whether to use full names (for fullName) or simple names (for simpleName)
*/
private static String buildTypeArgsString(List<TypeInfo> typeArgs, boolean useFullNames) {
if (typeArgs == null || typeArgs.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder("<");
for (int i = 0; i < typeArgs.size(); i++) {
if (i > 0) sb.append(", ");
TypeInfo arg = typeArgs.get(i);
sb.append(useFullNames ? arg.getDisplayNameFull() : arg.getDisplayNameSimple());
}
sb.append(">");
return sb.toString();
}
/**
* Get the canonical display name for this type, including generic arguments.
* This is the preferred method for UI display (hover, autocomplete, etc.).
*
* For Java types: uses simple name + generics (e.g., "List<String>")
* For JS types: uses full name + generics (e.g., "IPlayerEvent.InteractEvent")
* For arrays: includes "[]" suffix
* For nested generics: recursively builds (e.g., "List<Map<String, Integer>>")
*/
public String getDisplayName() {
// Use full name for JS types, simple name for Java
return isJSType() ? getDisplayNameFull() : getDisplayNameSimple();
}
/**
* Get display name using simple names for all types.
* Example: "Map<String, Integer>" instead of "java.util.Map<java.lang.String, java.lang.Integer>"
*/
public String getDisplayNameSimple() {
if (appliedTypeArgs.isEmpty()) {
return simpleName;
}
String baseName = rawType != null ? rawType.getSimpleName() : simpleName;
return baseName + buildTypeArgsString(appliedTypeArgs, false);
}
/**
* Get display name using full qualified names.
* Example: "java.util.Map<java.lang.String, java.lang.Integer>"
*/
public String getDisplayNameFull() {
if (appliedTypeArgs.isEmpty()) {
return fullName;
}
// For full display, use the raw type's full name + the args with their display names
String baseName = rawType != null ? rawType.getFullName() : fullName;
return baseName + buildTypeArgsString(appliedTypeArgs, true);
}
/**
* Returns true if this TypeInfo represents a Class reference (not an instance).
* For example, Java.type("java.io.File") returns a Class reference.
@@ -729,6 +961,21 @@ public class TypeInfo {
if (jsTypeInfo != null) {
return jsTypeInfo.getTypeParams();
}
// For Java reflection types, lazily expose declared generic parameters (e.g., List<E>, Map<K,V>)
if (javaClass != null && typeParams.isEmpty()) {
try {
TypeVariable<?>[] vars = javaClass.getTypeParameters();
for (TypeVariable<?> v : vars) {
if (v == null) continue;
String n = v.getName();
if (n == null || n.isEmpty()) continue;
typeParams.add(new TypeParamInfo(n, null, null));
}
} catch (Exception ignored) {
// Best-effort only; leave typeParams empty.
}
}
return typeParams;
}
@@ -314,8 +314,9 @@ public class TypeResolver {
/**
* Resolve a type name for JavaScript context.
* Handles JS primitives, .d.ts types, and falls back to Java types.
* NOW preserves generic type arguments in the returned TypeInfo.
*
* @param jsTypeName The JS type name (e.g., "IPlayer", "string", "number", "Java.java.io.File")
* @param jsTypeName The JS type name (e.g., "IPlayer", "string", "List<String>", "Map<String, Integer>")
* @return TypeInfo for the resolved type, or unresolved TypeInfo if not found
*/
public TypeInfo resolveJSType(String jsTypeName) {
@@ -323,43 +324,79 @@ public class TypeResolver {
return TypeInfo.fromPrimitive("void");
}
// Handle union types - use first type
if (jsTypeName.contains("|")) {
jsTypeName = jsTypeName.split("\\|")[0].trim();
// Use the generic type parser for full handling
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(jsTypeName);
if (parsed == null) {
return TypeInfo.unresolved(jsTypeName, jsTypeName);
}
// Handle nullable
jsTypeName = jsTypeName.replace("?", "").trim();
// Strip array brackets for base type resolution
boolean isArray = jsTypeName.endsWith("[]");
String baseName = isArray ? jsTypeName.substring(0, jsTypeName.length() - 2) : jsTypeName;
// Resolve the parsed type tree into a TypeInfo tree
return resolveFromParsedType(parsed);
}
/**
* Resolve a ParsedType tree into a TypeInfo, preserving generic arguments.
* This is the core resolution method that handles nested generics.
*/
private TypeInfo resolveFromParsedType(GenericTypeParser.ParsedType parsed) {
if (parsed == null) {
return null;
}
String baseName = parsed.baseName;
// Handle "Java." prefix - convert to actual Java type
if (baseName.startsWith("Java.")) {
baseName = baseName.substring(5); // Remove "Java."
}
// Resolve the base type (without generics)
TypeInfo baseType = resolveBaseType(baseName);
// If we have type arguments, recursively resolve them and create parameterized type
if (parsed.hasTypeArgs() && baseType != null && baseType.isResolved()) {
List<TypeInfo> resolvedArgs = new ArrayList<>();
for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) {
TypeInfo argType = resolveFromParsedType(argParsed);
resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName, argParsed.baseName));
}
baseType = baseType.parameterize(resolvedArgs);
}
// Handle array
if (parsed.isArray && baseType != null) {
for (int i = 0; i < parsed.arrayDimensions; i++) {
baseType = TypeInfo.arrayOf(baseType);
}
}
// Return the resolved (possibly parameterized) type
return baseType != null ? baseType : TypeInfo.unresolved(parsed.baseName, parsed.rawString);
}
/**
* Resolve a base type name (without generics) to a TypeInfo.
* This handles primitives, synthetic types, JS registry types, and Java types.
*/
private TypeInfo resolveBaseType(String baseName) {
if (baseName == null || baseName.isEmpty()) {
return null;
}
// Check synthetic types (Nashorn built-ins, custom types, etc.)
if (isSyntheticType(baseName)) {
SyntheticType syntheticType = getSyntheticType(baseName);
return syntheticType.getTypeInfo();
}
// Handle "Java." prefix - convert to actual Java type
// e.g., "Java.java.io.File" -> "java.io.File"
if (baseName.startsWith("Java.")) {
String javaFullName = baseName.substring(5); // Remove "Java."
TypeInfo javaType = resolveFullName(javaFullName);
if (javaType != null && javaType.isResolved()) {
return isArray ? TypeInfo.arrayOf(javaType) : javaType;
}
// Still return unresolved with the cleaned-up name
return TypeInfo.unresolved(javaFullName.substring(javaFullName.lastIndexOf('.') + 1), javaFullName);
}
// Check primitives and common types
switch (baseName.toLowerCase()) {
case "string":
return TypeInfo.STRING;
case "number":
case "int":
case "integer":
return TypeInfo.NUMBER;
return TypeInfo.NUMBER;
case "boolean":
case "bool":
return TypeInfo.BOOLEAN;
@@ -374,18 +411,17 @@ public class TypeResolver {
// Check JS type registry
JSTypeInfo jsTypeInfo = getJSTypeRegistry().getType(baseName);
if (jsTypeInfo != null) {
TypeInfo baseType = TypeInfo.fromJSTypeInfo(jsTypeInfo);
return isArray ? TypeInfo.arrayOf(baseType) : baseType;
return TypeInfo.fromJSTypeInfo(jsTypeInfo);
}
// Fall back to Java type resolution
TypeInfo javaType = resolveFullName(baseName);
if (javaType != null && javaType.isResolved()) {
return isArray ? TypeInfo.arrayOf(javaType) : javaType;
return javaType;
}
// Unresolved
return TypeInfo.unresolved(jsTypeName, jsTypeName);
return TypeInfo.unresolved(baseName, baseName);
}
/**
@@ -0,0 +1,222 @@
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
if (!type.isResolved() || isTypeVariable(typeName)) {
TypeInfo substitution = bindings.get(typeName);
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("[]")) {
// Extract element type and substitute
String elementTypeName = typeName.substring(0, typeName.length() - 2);
TypeInfo elementSubstitution = bindings.get(elementTypeName);
if (elementSubstitution != null) {
return TypeInfo.arrayOf(elementSubstitution);
}
}
return type;
}
/**
* Substitute type variables in a type string using the given bindings.
* Used when we have a raw type string (like "T" or "List<T>") that needs substitution.
*
* @param typeString The raw type string
* @param bindings The map from type variable names to concrete types
* @param resolver The type resolver to use for parsing
* @return The substituted TypeInfo
*/
public static TypeInfo substituteString(String typeString, Map<String, TypeInfo> bindings, TypeResolver resolver) {
if (typeString == null || typeString.isEmpty()) {
return null;
}
// First check if the whole string is a type variable
String trimmed = typeString.trim();
// Handle array suffix
boolean isArray = trimmed.endsWith("[]");
String baseName = isArray ? trimmed.substring(0, trimmed.length() - 2).trim() : trimmed;
// Strip generic args to check the base name
String bareBaseName = GenericTypeParser.stripGenerics(baseName);
// If bare base name is a type variable, substitute
TypeInfo directSubstitution = bindings.get(bareBaseName);
if (directSubstitution != null) {
// It's a type variable, return the substitution
TypeInfo result = directSubstitution;
if (isArray) {
result = TypeInfo.arrayOf(result);
}
return result;
}
// Parse and resolve the type, then substitute within it
TypeInfo resolved = resolver.resolveJSType(typeString);
return substitute(resolved, bindings);
}
/**
* Check if a type name looks like a type variable (single uppercase letter or short uppercase name).
*/
private static boolean isTypeVariable(String name) {
if (name == null || name.isEmpty()) {
return false;
}
// Common type variable patterns: T, E, K, V, R, U, etc.
// Also handles longer ones like KEY, VALUE but those are rare
return name.length() <= 3 &&
Character.isUpperCase(name.charAt(0)) &&
name.chars().allMatch(c -> Character.isUpperCase(c) || Character.isDigit(c));
}
/**
* Get the return type for a method on a parameterized receiver, with type variable substitution.
*
* @param rawReturnType The method's raw return type (may contain type variables)
* @param rawReturnTypeString The method's raw return type as a string (for unresolved types)
* @param receiverType The parameterized receiver type
* @param resolver The type resolver
* @return The substituted return type
*/
public static TypeInfo getSubstitutedReturnType(TypeInfo rawReturnType, String rawReturnTypeString,
TypeInfo receiverType, TypeResolver resolver) {
Map<String, TypeInfo> bindings = createBindingsFromReceiver(receiverType);
if (bindings.isEmpty()) {
return rawReturnType;
}
// Try substituting the resolved type first
TypeInfo substituted = substitute(rawReturnType, bindings);
if (substituted != rawReturnType && substituted.isResolved()) {
return substituted;
}
// If still not resolved, try substituting from the string
if (rawReturnTypeString != null && !rawReturnTypeString.isEmpty()) {
TypeInfo fromString = substituteString(rawReturnTypeString, bindings, resolver);
if (fromString != null && fromString.isResolved()) {
return fromString;
}
}
return substituted;
}
}