mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-19 03:49:10 +00:00
Optimised and refined type generics parsing. Removed bloat and added edge case handling
This commit is contained in:
1 parent
19cdf19a9b
commit
125a799df4
12 files changed
+722
-410
No files matched your search
+1
-1
Submodule src/api updated: 2e5d86993c...2054012fae.
@@ -27,6 +27,7 @@ import noppes.npcs.constants.ScriptContext;
|
||||
import noppes.npcs.controllers.data.DataScript;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -1916,17 +1917,98 @@ public class ScriptDocument {
|
||||
if (typeName == null || typeName.isEmpty())
|
||||
return TypeInfo.unresolved(typeName, typeName);
|
||||
|
||||
String normalized = typeName.trim();
|
||||
normalized = stripLeadingModifiers(normalized);
|
||||
final String normalized = typeName.trim();
|
||||
final String normalizedFinal = stripLeadingModifiers(normalized);
|
||||
|
||||
// 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);
|
||||
// Split array suffixes first
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalizedFinal);
|
||||
String baseExpr = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
// Base type resolver with import tracking
|
||||
Function<String, TypeInfo> resolveBase = baseName -> {
|
||||
TypeInfo resolved;
|
||||
|
||||
// Primitives
|
||||
if (TypeResolver.isPrimitiveType(baseName)) {
|
||||
resolved = TypeInfo.fromPrimitive(baseName);
|
||||
}
|
||||
// Common java.lang.String
|
||||
else if ("String".equals(baseName)) {
|
||||
resolved = typeResolver.resolveFullName("java.lang.String");
|
||||
}
|
||||
// Script-defined types (simple names only)
|
||||
else if (!baseName.contains(".") && scriptTypes.containsKey(baseName)) {
|
||||
resolved = scriptTypes.get(baseName);
|
||||
}
|
||||
// Fully-qualified
|
||||
else if (baseName.contains(".")) {
|
||||
resolved = typeResolver.resolveFullName(baseName);
|
||||
}
|
||||
// Imported/simple
|
||||
else {
|
||||
resolved = typeResolver.resolveSimpleName(baseName, importsBySimpleName, wildcardPackages);
|
||||
|
||||
// Track import usage
|
||||
if (resolved != null && resolved.isResolved()) {
|
||||
ImportData usedImport = importsBySimpleName.get(baseName);
|
||||
if (usedImport != null) {
|
||||
usedImport.incrementUsage();
|
||||
} else if (wildcardPackages != null) {
|
||||
String resultPkg = resolved.getPackageName();
|
||||
for (ImportData imp : imports) {
|
||||
if (imp.isWildcard() && resultPkg != null && resultPkg.equals(imp.getFullPath())) {
|
||||
imp.incrementUsage();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resolved != null ? resolved : TypeInfo.unresolved(baseName, normalizedFinal);
|
||||
};
|
||||
|
||||
TypeInfo resolved;
|
||||
|
||||
// Fast path: no generics - skip expensive parsing
|
||||
if (!baseExpr.contains("<")) {
|
||||
resolved = resolveBase.apply(baseExpr);
|
||||
} else {
|
||||
// Slow path: parse and resolve generics
|
||||
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(baseExpr);
|
||||
if (parsed != null) {
|
||||
// Normalize whitespace around dots in base name
|
||||
String baseName = parsed.baseName.replaceAll("\\s*\\.\\s*", ".").trim();
|
||||
resolved = resolveBase.apply(baseName);
|
||||
|
||||
// Apply generic arguments
|
||||
if (parsed.hasTypeArgs() && resolved != null && resolved.isResolved()) {
|
||||
List<TypeInfo> resolvedArgs = new ArrayList<>();
|
||||
for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) {
|
||||
if (argParsed == null) {
|
||||
resolvedArgs.add(TypeInfo.fromClass(Object.class));
|
||||
} else {
|
||||
TypeInfo argType = resolveTypeAndTrackUsage(argParsed.rawString);
|
||||
resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName,
|
||||
argParsed.baseName));
|
||||
}
|
||||
}
|
||||
if (!resolvedArgs.isEmpty()) {
|
||||
resolved = resolved.parameterize(resolvedArgs);
|
||||
}
|
||||
}
|
||||
} else
|
||||
// Fallback: treat as simple type
|
||||
resolved = resolveBase.apply(baseExpr);
|
||||
}
|
||||
|
||||
TypeInfo result = resolveJavaFromParsedType(parsed);
|
||||
return result != null ? result : TypeInfo.unresolved(parsed.baseName, normalized);
|
||||
// Apply array dimensions
|
||||
for (int i = 0; i < arrayDims; i++) {
|
||||
resolved = TypeInfo.arrayOf(resolved);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1957,91 +2039,6 @@ public class ScriptDocument {
|
||||
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)) {
|
||||
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);
|
||||
|
||||
// Track explicit import usage if present
|
||||
ImportData usedImport = importsBySimpleName.get(baseName);
|
||||
if (baseType != null && baseType.isResolved() && usedImport != null) {
|
||||
usedImport.incrementUsage();
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 ====================
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,7 @@ import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry;
|
||||
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.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;
|
||||
@@ -16,6 +17,7 @@ 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.
|
||||
@@ -158,9 +160,11 @@ public final class FieldInfo {
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (GenericContext.hasGenerics(containingType)) {
|
||||
Map<String, TypeInfo> receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
|
||||
if (!receiverBindings.isEmpty()) {
|
||||
type = TypeSubstitutor.substitute(type, receiverBindings);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is an enum constant
|
||||
|
||||
+11
-12
@@ -1,6 +1,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.GenericContext;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver;
|
||||
/**
|
||||
@@ -44,19 +45,17 @@ public class JSFieldInfo {
|
||||
* @return The resolved TypeInfo for the field 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()) {
|
||||
TypeInfo paramResolution = contextType.resolveTypeParamToTypeInfo(type);
|
||||
if (paramResolution != null)
|
||||
resolved = typeInfo = paramResolution; // cache it to typeInfo
|
||||
|
||||
// Cache only the raw resolved type; substitutions depend on the receiver context.
|
||||
TypeInfo resolved = typeInfo != null ? typeInfo : resolver.resolveJSType(type);
|
||||
if (typeInfo == null) {
|
||||
typeInfo = resolved;
|
||||
}
|
||||
|
||||
if (contextType != null) {
|
||||
GenericContext ctx = GenericContext.forReceiver(contextType);
|
||||
return ctx.substituteType(resolved, type, resolver);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
|
||||
+7
-25
@@ -1,9 +1,9 @@
|
||||
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.GenericContext;
|
||||
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.*;
|
||||
|
||||
@@ -59,20 +59,11 @@ public class JSMethodInfo {
|
||||
*/
|
||||
public TypeInfo getResolvedReturnType(TypeInfo contextType) {
|
||||
TypeResolver resolver = TypeResolver.getInstance();
|
||||
|
||||
// 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 = paramResolution;
|
||||
}
|
||||
if (contextType != null) {
|
||||
GenericContext ctx = GenericContext.forReceiver(contextType);
|
||||
resolved = ctx.substituteType(resolved, returnType, resolver);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
@@ -168,20 +159,11 @@ public class JSMethodInfo {
|
||||
*/
|
||||
public TypeInfo getResolvedType(TypeInfo contextType) {
|
||||
TypeResolver resolver = TypeResolver.getInstance();
|
||||
|
||||
// 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 = paramResolution;
|
||||
}
|
||||
if (contextType != null) {
|
||||
GenericContext ctx = GenericContext.forReceiver(contextType);
|
||||
resolved = ctx.substituteType(resolved, type, resolver);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
|
||||
+2
-49
@@ -2,6 +2,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.jsdoc.JSDocTag;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeStringNormalizer;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
@@ -665,55 +666,7 @@ public class TypeScriptDefinitionParser {
|
||||
*/
|
||||
private String cleanType(String type) {
|
||||
if (type == null) return "any";
|
||||
type = type.trim();
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
return type;
|
||||
return TypeStringNormalizer.stripImportTypeSyntax(type);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,7 @@ import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo;
|
||||
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.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;
|
||||
@@ -15,11 +16,7 @@ import noppes.npcs.client.gui.util.script.interpreter.type.TypeSubstitutor;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Metadata for a method declaration or method call.
|
||||
@@ -174,9 +171,12 @@ 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);
|
||||
Map<String, TypeInfo> receiverBindings = null;
|
||||
if (GenericContext.hasGenerics(containingType)) {
|
||||
receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType);
|
||||
if (!receiverBindings.isEmpty()) {
|
||||
returnType = TypeSubstitutor.substitute(returnType, receiverBindings);
|
||||
}
|
||||
}
|
||||
List<FieldInfo> params = new ArrayList<>();
|
||||
// Use getGenericParameterTypes() to preserve generic information
|
||||
@@ -188,7 +188,7 @@ public final class MethodInfo {
|
||||
paramType = TypeInfo.fromClass(method.getParameterTypes()[i]);
|
||||
}
|
||||
|
||||
if (!receiverBindings.isEmpty()) {
|
||||
if (receiverBindings != null && !receiverBindings.isEmpty()) {
|
||||
paramType = TypeSubstitutor.substitute(paramType, receiverBindings);
|
||||
}
|
||||
String paramName = "arg" + i;
|
||||
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* A context for resolving and substituting declared type parameters (T, E, K, V...)
|
||||
* based on a receiver type.
|
||||
*
|
||||
* 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).
|
||||
*/
|
||||
public final class GenericContext {
|
||||
|
||||
/** Singleton context for types with no generic parameters. Used to avoid object allocation. */
|
||||
private static final GenericContext EMPTY = new GenericContext(new HashMap<>(), new HashMap<>());
|
||||
|
||||
/**
|
||||
* Map of type variable names to their applied type arguments.
|
||||
* For example, in List<String>, this contains E -> TypeInfo.STRING.
|
||||
* Applied bindings take precedence over bound fallbacks.
|
||||
*/
|
||||
private final Map<String, TypeInfo> appliedBindings;
|
||||
|
||||
/**
|
||||
* Map of type variable names to their declared upper bounds.
|
||||
* For example, in <T extends Entity>, this contains T -> TypeInfo(Entity).
|
||||
* Used as fallback when no applied argument exists.
|
||||
*/
|
||||
private final Map<String, TypeInfo> boundFallbacks;
|
||||
|
||||
private GenericContext(Map<String, TypeInfo> appliedBindings, Map<String, TypeInfo> boundFallbacks) {
|
||||
this.appliedBindings = appliedBindings != null ? appliedBindings : new HashMap<>();
|
||||
this.boundFallbacks = boundFallbacks != null ? boundFallbacks : new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GenericContext for a receiver type.
|
||||
*
|
||||
* Fast path: returns singleton EMPTY for non-generic types (no allocation overhead).
|
||||
* Slow path: builds maps from type parameters and applied arguments for generic types.
|
||||
*
|
||||
* @param receiverType the type to extract generic bindings from (e.g., List<String>, DAO<T extends Entity>)
|
||||
* @return a context with applied bindings and bound fallbacks, or EMPTY singleton if receiverType is not generic
|
||||
*/
|
||||
public static GenericContext forReceiver(TypeInfo receiverType) {
|
||||
// Fast path: return singleton for non-generic types
|
||||
if (receiverType == null || !hasGenerics(receiverType)) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
TypeInfo rawType = receiverType.getRawType();
|
||||
List<TypeParamInfo> declaredParams = rawType != null ? rawType.getTypeParams() : null;
|
||||
List<TypeInfo> appliedArgs = receiverType.getAppliedTypeArgs();
|
||||
|
||||
Map<String, TypeInfo> applied = new HashMap<>();
|
||||
if (declaredParams != null && appliedArgs != null) {
|
||||
int count = Math.min(declaredParams.size(), appliedArgs.size());
|
||||
for (int i = 0; i < count; i++) {
|
||||
TypeParamInfo declared = declaredParams.get(i);
|
||||
TypeInfo arg = appliedArgs.get(i);
|
||||
if (declared == null || declared.getName() == null || declared.getName().isEmpty() || arg == null) {
|
||||
continue;
|
||||
}
|
||||
applied.put(declared.getName(), arg);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, TypeInfo> bounds = new HashMap<>();
|
||||
if (declaredParams != null) {
|
||||
for (TypeParamInfo declared : declaredParams) {
|
||||
if (declared == null) continue;
|
||||
String name = declared.getName();
|
||||
if (name == null || name.isEmpty()) continue;
|
||||
TypeInfo bound = declared.getBoundTypeInfo();
|
||||
if (bound != null && bound.isResolved()) {
|
||||
bounds.put(name, bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new GenericContext(applied, bounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a type has generics that need substitution.
|
||||
*
|
||||
* Returns true if:
|
||||
* - Type is parameterized (e.g., List<String>)
|
||||
* - Type's raw form differs from the type itself
|
||||
* - Type has declared type parameters
|
||||
*
|
||||
* @param type the type to check
|
||||
* @return true if this type contains generic information that may need substitution
|
||||
*/
|
||||
public static boolean hasGenerics(TypeInfo type) {
|
||||
return type.isParameterized() ||
|
||||
type.getRawType() != type ||
|
||||
(type.getTypeParams() != null && !type.getTypeParams().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a type variable to its bound or applied type.
|
||||
*
|
||||
* Prefers applied bindings (e.g., E -> String in List<String>) over declared bounds.
|
||||
* Falls back to bounds (e.g., T -> Entity in <T extends Entity>) if no applied argument exists.
|
||||
* Returns null if the variable is not found in either map.
|
||||
*
|
||||
* @param name the type variable name (e.g., "T", "E", "K")
|
||||
* @return the resolved TypeInfo, or null if variable not found
|
||||
*/
|
||||
public TypeInfo resolveTypeVariable(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
TypeInfo applied = appliedBindings.get(name);
|
||||
if (applied != null) {
|
||||
return applied;
|
||||
}
|
||||
|
||||
return boundFallbacks.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute type variables in a TypeInfo recursively.
|
||||
*
|
||||
* Handles:
|
||||
* - Direct type variables (unresolved types representing T, E, etc.)
|
||||
* - Parameterized types (recursively substitutes inside type arguments)
|
||||
* - Array types (substitutes the element type, preserves array dimensions)
|
||||
*
|
||||
* @param type the type to substitute (may contain type variables)
|
||||
* @return the substituted type, or the original type if no substitutions apply
|
||||
*/
|
||||
public TypeInfo substitute(TypeInfo type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Direct type variable substitution (unresolved types represent type variables like T).
|
||||
if (!type.isResolved()) {
|
||||
TypeInfo substitution = resolveTypeVariable(type.getSimpleName());
|
||||
if (substitution != null) {
|
||||
return substitution;
|
||||
}
|
||||
}
|
||||
|
||||
// Parameterized types: substitute inside args.
|
||||
if (type.isParameterized()) {
|
||||
List<TypeInfo> originalArgs = type.getAppliedTypeArgs();
|
||||
List<TypeInfo> substitutedArgs = new ArrayList<>(originalArgs.size());
|
||||
boolean changed = false;
|
||||
|
||||
for (TypeInfo arg : originalArgs) {
|
||||
TypeInfo substitutedArg = substitute(arg);
|
||||
substitutedArgs.add(substitutedArg);
|
||||
if (substitutedArg != arg) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
return type.getRawType().parameterize(substitutedArgs);
|
||||
}
|
||||
}
|
||||
|
||||
// Array wrapper types are represented by a display-name suffix; we can still substitute
|
||||
// a plain "T[]" by looking up "T".
|
||||
String simple = type.getSimpleName();
|
||||
if (simple != null && simple.endsWith("[]")) {
|
||||
TypeStringNormalizer.ArraySplit split = TypeStringNormalizer.splitArraySuffixes(simple);
|
||||
String elementName = split.base;
|
||||
int dims = split.dimensions;
|
||||
TypeInfo elementSub = resolveTypeVariable(elementName);
|
||||
if (elementSub != null) {
|
||||
TypeInfo result = elementSub;
|
||||
for (int i = 0; i < dims; i++) {
|
||||
result = TypeInfo.arrayOf(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute type variables in a type string.
|
||||
*
|
||||
* Attempts substitution in this order:
|
||||
* 1. Normalize the string (strip imports, pick union branch, remove nullable suffix, split arrays)
|
||||
* 2. Try direct type variable lookup (e.g., "T" -> resolved Entity)
|
||||
* 3. Fall back to full type resolution with substitution applied
|
||||
*
|
||||
* @param typeString the type expression as a string (e.g., "T", "T[]", "List<T>")
|
||||
* @param resolver optional TypeResolver for fallback resolution; if null, returns null on failure
|
||||
* @return the substituted type, or null if resolution fails
|
||||
*/
|
||||
public TypeInfo substituteString(String typeString, TypeResolver resolver) {
|
||||
if (typeString == null || typeString.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String normalized = TypeStringNormalizer.stripImportTypeSyntax(typeString);
|
||||
normalized = TypeStringNormalizer.pickPreferredUnionBranch(normalized);
|
||||
normalized = TypeStringNormalizer.stripNullableSuffix(normalized);
|
||||
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalized);
|
||||
String baseExpr = arraySplit.base;
|
||||
int dims = arraySplit.dimensions;
|
||||
|
||||
String bareBase = GenericTypeParser.stripGenerics(baseExpr);
|
||||
TypeInfo direct = resolveTypeVariable(bareBase);
|
||||
if (direct != null) {
|
||||
TypeInfo result = direct;
|
||||
for (int i = 0; i < dims; i++) {
|
||||
result = TypeInfo.arrayOf(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (resolver == null) {
|
||||
return null;
|
||||
}
|
||||
TypeInfo resolved = resolver.resolveJSType(typeString);
|
||||
return substitute(resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute type variables in a resolved type, with string fallback.
|
||||
*
|
||||
* Two-phase approach:
|
||||
* 1. Try substituting the resolved type directly
|
||||
* 2. If that fails, attempt substitution via the raw string as fallback
|
||||
*
|
||||
* This handles edge cases where the TypeInfo doesn't capture enough information
|
||||
* to do proper substitution (e.g., union types, complex generics).
|
||||
*
|
||||
* @param resolvedType a TypeInfo that has already been resolved (may still contain type variables)
|
||||
* @param rawTypeString the original type string before resolution (for fallback)
|
||||
* @param resolver optional TypeResolver for string-based fallback resolution
|
||||
* @return the substituted type, or the best attempt if full substitution fails
|
||||
*/
|
||||
public TypeInfo substituteType(TypeInfo resolvedType, String rawTypeString, TypeResolver resolver) {
|
||||
if (resolvedType == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
TypeInfo substituted = substitute(resolvedType);
|
||||
if (substituted != null && substituted.isResolved()) {
|
||||
return substituted;
|
||||
}
|
||||
|
||||
if (rawTypeString != null && !rawTypeString.trim().isEmpty()) {
|
||||
TypeInfo fromString = substituteString(rawTypeString, resolver);
|
||||
if (fromString != null && fromString.isResolved()) {
|
||||
return fromString;
|
||||
}
|
||||
}
|
||||
|
||||
return substituted;
|
||||
}
|
||||
}
|
||||
+23
-130
@@ -12,9 +12,9 @@ import java.util.List;
|
||||
* - 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)
|
||||
*
|
||||
* Note: union/nullability/array semantics are handled by higher-level resolvers.
|
||||
* This parser only consumes suffix tokens where needed to correctly delimit type arguments.
|
||||
*
|
||||
* This parser produces a ParsedType tree that can be resolved into parameterized TypeInfo instances.
|
||||
*/
|
||||
@@ -30,25 +30,12 @@ public class GenericTypeParser {
|
||||
/** 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) {
|
||||
public ParsedType(String baseName, List<ParsedType> typeArgs, String rawString) {
|
||||
this.baseName = baseName;
|
||||
this.typeArgs = typeArgs != null ? typeArgs : new ArrayList<>();
|
||||
this.isArray = isArray;
|
||||
this.arrayDimensions = arrayDimensions;
|
||||
this.isNullable = isNullable;
|
||||
this.rawString = rawString;
|
||||
}
|
||||
|
||||
@@ -73,12 +60,6 @@ public class GenericTypeParser {
|
||||
}
|
||||
sb.append(">");
|
||||
}
|
||||
for (int i = 0; i < arrayDimensions; i++) {
|
||||
sb.append("[]");
|
||||
}
|
||||
if (isNullable) {
|
||||
sb.append("?");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -96,38 +77,14 @@ public class GenericTypeParser {
|
||||
|
||||
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);
|
||||
return new ParsedType(expr, null, typeExpr);
|
||||
}
|
||||
|
||||
ParsedType parsed = result.type;
|
||||
|
||||
// Apply array and nullable modifiers
|
||||
return new ParsedType(parsed.baseName, parsed.typeArgs,
|
||||
arrayDims > 0, arrayDims, isNullable, typeExpr);
|
||||
return result.type;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,71 +117,18 @@ public class GenericTypeParser {
|
||||
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))) {
|
||||
// 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;
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
String baseName = baseNameBuilder.toString().trim();
|
||||
|
||||
if (baseName.isEmpty()) {
|
||||
return null;
|
||||
@@ -277,7 +181,7 @@ public class GenericTypeParser {
|
||||
}
|
||||
}
|
||||
|
||||
ParsedType type = new ParsedType(baseName, typeArgs, false, 0, false, expr.substring(startIndex, i));
|
||||
ParsedType type = new ParsedType(baseName, typeArgs, expr.substring(startIndex, i));
|
||||
return new ParseResult(type, i);
|
||||
}
|
||||
|
||||
@@ -363,7 +267,7 @@ public class GenericTypeParser {
|
||||
}
|
||||
}
|
||||
// Plain wildcard, treat as Object
|
||||
return new ParseResult(new ParsedType("Object", null, false, 0, false, "?"), i);
|
||||
return new ParseResult(new ParsedType("Object", null, "?"), i);
|
||||
}
|
||||
|
||||
// Parse regular type with potential generics
|
||||
@@ -380,33 +284,22 @@ public class GenericTypeParser {
|
||||
i++;
|
||||
}
|
||||
|
||||
// Check for array suffix
|
||||
int arrayDims = 0;
|
||||
// Consume array suffixes / nullable suffix so the caller can correctly find delimiters.
|
||||
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
|
||||
);
|
||||
|
||||
// Preserve the full raw substring (including suffixes) for higher-level resolvers.
|
||||
if (i != typeResult.endIndex) {
|
||||
return new ParseResult(new ParsedType(baseType.baseName, baseType.typeArgs, expr.substring(startIndex, i)), i);
|
||||
}
|
||||
|
||||
|
||||
return new ParseResult(baseType, i);
|
||||
}
|
||||
|
||||
|
||||
+62
-43
@@ -324,54 +324,68 @@ public class TypeResolver {
|
||||
return TypeInfo.fromPrimitive("void");
|
||||
}
|
||||
|
||||
// Use the generic type parser for full handling
|
||||
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(jsTypeName);
|
||||
if (parsed == null) {
|
||||
// Normalize import() references first.
|
||||
String normalized = TypeStringNormalizer.stripImportTypeSyntax(jsTypeName);
|
||||
if (normalized == null || normalized.isEmpty()) {
|
||||
return TypeInfo.fromPrimitive("void");
|
||||
}
|
||||
|
||||
// Unions: pick a single "best" branch for resolution (prefer non-nullish).
|
||||
normalized = TypeStringNormalizer.pickPreferredUnionBranch(normalized);
|
||||
|
||||
// Nullable: treat Foo? as Foo | null (for resolution purposes this means "resolve Foo").
|
||||
normalized = TypeStringNormalizer.stripNullableSuffix(normalized);
|
||||
|
||||
// Arrays: handled here, not in the generics structural parser.
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalized);
|
||||
String baseExpr = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
if (baseExpr == null || baseExpr.isEmpty()) {
|
||||
return TypeInfo.unresolved(jsTypeName, 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;
|
||||
|
||||
TypeInfo resolved = null;
|
||||
// Fast path: no generics - skip expensive parsing
|
||||
if (!baseExpr.contains("<")) {
|
||||
resolved = resolveBaseType(baseExpr);
|
||||
} else {
|
||||
// Slow path: parse and resolve into a TypeInfo, preserving generic arguments.
|
||||
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(baseExpr);
|
||||
if (parsed != null) {
|
||||
// Resolve the base type (without generics)
|
||||
TypeInfo baseType = resolveBaseType(parsed.baseName);
|
||||
|
||||
// If we have type arguments, resolve them (allowing each arg to have its own arrays/unions/etc).
|
||||
if (parsed.hasTypeArgs() && baseType != null && baseType.isResolved()) {
|
||||
List<TypeInfo> resolvedArgs = new ArrayList<>();
|
||||
for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) {
|
||||
if (argParsed == null) {
|
||||
resolvedArgs.add(TypeInfo.ANY);
|
||||
continue;
|
||||
}
|
||||
TypeInfo argType = resolveJSType(argParsed.rawString);
|
||||
resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName,
|
||||
argParsed.baseName));
|
||||
}
|
||||
if (!resolvedArgs.isEmpty()) {
|
||||
baseType = baseType.parameterize(resolvedArgs);
|
||||
}
|
||||
}
|
||||
resolved = baseType != null ? baseType : TypeInfo.unresolved(parsed.baseName, parsed.rawString);
|
||||
} else
|
||||
resolved = resolveBaseType(baseExpr);
|
||||
}
|
||||
|
||||
String baseName = parsed.baseName;
|
||||
|
||||
// Handle "Java." prefix - convert to actual Java type
|
||||
if (baseName.startsWith("Java.")) {
|
||||
baseName = baseName.substring(5); // Remove "Java."
|
||||
|
||||
if (resolved == null) {
|
||||
resolved = TypeInfo.unresolved(baseExpr, jsTypeName);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
for (int i = 0; i < arrayDims; i++) {
|
||||
resolved = TypeInfo.arrayOf(resolved);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -383,6 +397,11 @@ public class TypeResolver {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle "Java." prefix - convert to actual Java type
|
||||
if (baseName.startsWith("Java.")) {
|
||||
baseName = baseName.substring(5);
|
||||
}
|
||||
|
||||
// Check synthetic types (Nashorn built-ins, custom types, etc.)
|
||||
if (isSyntheticType(baseName)) {
|
||||
SyntheticType syntheticType = getSyntheticType(baseName);
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.type;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Shared utilities for cleaning and normalizing type expressions.
|
||||
*
|
||||
* This is intentionally a small, dependency-light helper that both the runtime resolver
|
||||
* and the .d.ts parser can use.
|
||||
*/
|
||||
public final class TypeStringNormalizer {
|
||||
|
||||
private TypeStringNormalizer() {}
|
||||
|
||||
public static final class ArraySplit {
|
||||
public final String base;
|
||||
public final int dimensions;
|
||||
|
||||
public ArraySplit(String base, int dimensions) {
|
||||
this.base = base;
|
||||
this.dimensions = dimensions;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
*/
|
||||
public static String stripImportTypeSyntax(String type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String out = type.trim();
|
||||
int importIdx;
|
||||
while ((importIdx = out.indexOf("import(")) >= 0) {
|
||||
int i = importIdx + "import(".length();
|
||||
int depth = 1;
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
while (i < out.length() && depth > 0) {
|
||||
char c = out.charAt(i);
|
||||
if (inString) {
|
||||
if (c == stringChar && (i == 0 || out.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 the "import(...)." prefix.
|
||||
if (i < out.length() && out.charAt(i) == '.') {
|
||||
int removeEnd = i + 1;
|
||||
out = out.substring(0, importIdx) + out.substring(removeEnd);
|
||||
} else {
|
||||
// Remove just the import(...) portion.
|
||||
out = out.substring(0, importIdx) + out.substring(i);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a trailing TypeScript nullable suffix: Foo? -> Foo.
|
||||
*/
|
||||
public static String stripNullableSuffix(String type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
String out = type.trim();
|
||||
if (out.endsWith("?")) {
|
||||
return out.substring(0, out.length() - 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split trailing array suffixes: Foo[][] -> base=Foo, dimensions=2.
|
||||
*/
|
||||
public static ArraySplit splitArraySuffixes(String type) {
|
||||
if (type == null) {
|
||||
return new ArraySplit(null, 0);
|
||||
}
|
||||
String out = type.trim();
|
||||
int dims = 0;
|
||||
while (out.endsWith("[]")) {
|
||||
dims++;
|
||||
out = out.substring(0, out.length() - 2).trim();
|
||||
}
|
||||
return new ArraySplit(out, dims);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a top-level union (depth-aware) into branches.
|
||||
*/
|
||||
public static List<String> splitTopLevelUnion(String type) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
if (type == null) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
String expr = type.trim();
|
||||
if (expr.isEmpty()) {
|
||||
parts.add("");
|
||||
return parts;
|
||||
}
|
||||
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
int start = 0;
|
||||
for (int i = 0; i < expr.length(); i++) {
|
||||
char c = expr.charAt(i);
|
||||
|
||||
if (inString) {
|
||||
if (c == stringChar && (i == 0 || expr.charAt(i - 1) != '\\')) {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '\'' || c == '"' || c == '`') {
|
||||
inString = true;
|
||||
stringChar = c;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '<' || c == '(' || c == '[' || c == '{') {
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (c == '>' || c == ')' || c == ']' || c == '}') {
|
||||
if (depth > 0) {
|
||||
depth--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '|' && depth == 0) {
|
||||
String part = expr.substring(start, i).trim();
|
||||
if (!part.isEmpty()) {
|
||||
parts.add(part);
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
String tail = expr.substring(start).trim();
|
||||
if (!tail.isEmpty()) {
|
||||
parts.add(tail);
|
||||
}
|
||||
|
||||
if (parts.isEmpty()) {
|
||||
parts.add(expr);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose a single branch to represent a union type for resolution.
|
||||
*
|
||||
* Policy:
|
||||
* - Prefer the first non-nullish branch (not null/undefined/void).
|
||||
* - Otherwise, fall back to the first branch.
|
||||
*/
|
||||
public static String pickPreferredUnionBranch(String type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> parts = splitTopLevelUnion(type);
|
||||
if (parts.size() <= 1) {
|
||||
return type.trim();
|
||||
}
|
||||
|
||||
for (String part : parts) {
|
||||
if (!isNullishBranch(part)) {
|
||||
return part.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return parts.get(0).trim();
|
||||
}
|
||||
|
||||
private static boolean isNullishBranch(String part) {
|
||||
if (part == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String s = part.trim();
|
||||
if (s.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Strip generics so "null<...>" doesn't behave weirdly.
|
||||
s = GenericTypeParser.stripGenerics(s);
|
||||
s = s.trim().toLowerCase();
|
||||
return "null".equals(s) || "undefined".equals(s) || "void".equals(s);
|
||||
}
|
||||
}
|
||||
+20
-45
@@ -93,7 +93,7 @@ public class TypeSubstitutor {
|
||||
String typeName = type.getSimpleName();
|
||||
|
||||
// Check if this type is itself a type variable
|
||||
if (!type.isResolved() || isTypeVariable(typeName)) {
|
||||
if (!type.isResolved()) {
|
||||
TypeInfo substitution = bindings.get(typeName);
|
||||
if (substitution != null) {
|
||||
return substitution;
|
||||
@@ -122,11 +122,16 @@ public class TypeSubstitutor {
|
||||
|
||||
// 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);
|
||||
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) {
|
||||
return TypeInfo.arrayOf(elementSubstitution);
|
||||
TypeInfo result = elementSubstitution;
|
||||
for (int i = 0; i < dims; i++) {
|
||||
result = TypeInfo.arrayOf(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,11 +153,13 @@ public class TypeSubstitutor {
|
||||
}
|
||||
|
||||
// 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;
|
||||
String trimmed = TypeStringNormalizer.stripImportTypeSyntax(typeString);
|
||||
trimmed = TypeStringNormalizer.pickPreferredUnionBranch(trimmed);
|
||||
trimmed = TypeStringNormalizer.stripNullableSuffix(trimmed);
|
||||
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(trimmed);
|
||||
String baseName = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
// Strip generic args to check the base name
|
||||
String bareBaseName = GenericTypeParser.stripGenerics(baseName);
|
||||
@@ -162,7 +169,7 @@ public class TypeSubstitutor {
|
||||
if (directSubstitution != null) {
|
||||
// It's a type variable, return the substitution
|
||||
TypeInfo result = directSubstitution;
|
||||
if (isArray) {
|
||||
for (int i = 0; i < arrayDims; i++) {
|
||||
result = TypeInfo.arrayOf(result);
|
||||
}
|
||||
return result;
|
||||
@@ -173,20 +180,6 @@ public class TypeSubstitutor {
|
||||
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.
|
||||
*
|
||||
@@ -198,25 +191,7 @@ public class TypeSubstitutor {
|
||||
*/
|
||||
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;
|
||||
GenericContext ctx = GenericContext.forReceiver(receiverType);
|
||||
return ctx.substituteType(rawReturnType, rawReturnTypeString, resolver);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user