diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java index a396a6402..1ca72ec9a 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui.util.script.interpreter; import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; import java.util.ArrayList; @@ -62,6 +63,12 @@ public final class ObjectLiteralParser { TypeInfo resolve(String expr, int position); } + /** Resolves a script-declared method by name. Used to copy parameter/return info into callable properties. */ + @FunctionalInterface + public interface MethodReferenceResolverFn { + MethodInfo resolve(String methodName, TypeInfo[] argTypes); + } + /** * Callback to resolve a variable by name at a given document position. * Delegates to {@code ScriptDocument.resolveVariable(name, position)}. @@ -107,8 +114,9 @@ public final class ObjectLiteralParser { * A single property inside an object literal. * *

Tracks the key name, whether the key was written as a bare identifier or a quoted string, - * the absolute document offsets for both key and value spans, and the inferred value type - * (when type inference was requested).

+ * the absolute document offsets for both key and value spans, the inferred value type + * (when type inference was requested), and optional callable metadata when the value is a + * function expression, arrow function, or shorthand method.

*/ public static final class ObjectLiteralProperty { /** The property key name (without quotes if originally quoted). */ @@ -125,9 +133,11 @@ public final class ObjectLiteralParser { public final int valueEndAbs; /** The inferred type of the value expression, or {@code null} if inference was not requested. */ public final TypeInfo valueType; + /** Callable metadata if this property's value is a function expression, arrow, or shorthand method. */ + public final CallableInfo callableInfo; ObjectLiteralProperty(String keyName, boolean isIdentifierKey, int keyStartAbs, int keyEndAbs, - int valueStartAbs, int valueEndAbs, TypeInfo valueType) { + int valueStartAbs, int valueEndAbs, TypeInfo valueType, CallableInfo callableInfo) { this.keyName = keyName; this.isIdentifierKey = isIdentifierKey; this.keyStartAbs = keyStartAbs; @@ -135,6 +145,11 @@ public final class ObjectLiteralParser { this.valueStartAbs = valueStartAbs; this.valueEndAbs = valueEndAbs; this.valueType = valueType; + this.callableInfo = callableInfo; + } + + public boolean isCallable() { + return callableInfo != null; } } @@ -182,15 +197,18 @@ public final class ObjectLiteralParser { * @param inferTypes if {@code true}, attempt to resolve value types and build a synthetic shape * @param assumeComplete if {@code true}, treat the entire string as a complete literal (no brace matching needed) * @param typeResolver callback for resolving value expression types (may be {@code null} if {@code inferTypes} is false) + * @param methodChecker callback for checking if an identifier is a known script method (for callable detection) * @return the analysis result, or {@code null} if the input is not a valid object literal start */ public static ObjectLiteralAnalysis parse(String objectLiteral, int baseOffset, boolean inferTypes, boolean assumeComplete, - ExpressionTypeResolverFn typeResolver) { + ExpressionTypeResolverFn typeResolver, + MethodReferenceResolverFn methodResolver) { if (objectLiteral == null) { return null; } + // Trim leading and trailing whitespace. int leading = 0; while (leading < objectLiteral.length() && Character.isWhitespace(objectLiteral.charAt(leading))) { leading++; @@ -203,10 +221,12 @@ public final class ObjectLiteralParser { String src = objectLiteral.substring(leading, trailing); int absBase = baseOffset + leading; + // Verify this starts with '{'. if (src.isEmpty() || src.charAt(0) != '{') { return null; } + // Find the matching '}' or use the entire string if assumeComplete is true. int endExclusive; if (assumeComplete) { endExclusive = src.length(); @@ -217,6 +237,7 @@ public final class ObjectLiteralParser { } } + // Only attempt type inference if the literal is complete (closing brace found). boolean supportsInference = (endExclusive == src.length()); int bodyStart = 1; int bodyEnd = endExclusive - 1; @@ -224,16 +245,10 @@ public final class ObjectLiteralParser { List props = new ArrayList<>(); boolean sawUnsupported = false; + // Parse each property in the object literal body. int i = bodyStart; while (i < bodyEnd) { - while (i < bodyEnd) { - char c = src.charAt(i); - if (Character.isWhitespace(c) || c == ',') { - i++; - continue; - } - break; - } + i = skipSeparatorsAndComments(src, i, bodyEnd); if (i >= bodyEnd) { break; } @@ -243,7 +258,9 @@ public final class ObjectLiteralParser { boolean isIdentifierKey = false; char kc = src.charAt(i); + // Parse key: quoted string or bare identifier or async method shorthand if (kc == '"' || kc == '\'') { + // Quoted key — extract and validate int keyEnd = scanStringLiteralEnd(src, i); if (keyEnd < 0 || keyEnd > bodyEnd) { sawUnsupported = true; @@ -258,12 +275,31 @@ public final class ObjectLiteralParser { } i = keyEnd; } else if (Character.isJavaIdentifierStart(kc)) { + // Bare identifier key i++; while (i < bodyEnd && Character.isJavaIdentifierPart(src.charAt(i))) { i++; } keyName = src.substring(keyStart, i); isIdentifierKey = true; + + // Handle 'async methodName()' shorthand syntax + if ("async".equals(keyName)) { + int afterAsync = i; + while (afterAsync < bodyEnd && Character.isWhitespace(src.charAt(afterAsync))) { + afterAsync++; + } + if (afterAsync < bodyEnd && Character.isJavaIdentifierStart(src.charAt(afterAsync))) { + int realKeyStart = afterAsync; + afterAsync++; + while (afterAsync < bodyEnd && Character.isJavaIdentifierPart(src.charAt(afterAsync))) { + afterAsync++; + } + keyStart = realKeyStart; + keyName = src.substring(realKeyStart, afterAsync); + i = afterAsync; + } + } } else if (kc == '[') { // Computed key — unsupported for inference, skip to next property sawUnsupported = true; @@ -285,13 +321,64 @@ public final class ObjectLiteralParser { i++; } + // Check for shorthand method syntax: key() { ... } + if (i < bodyEnd && src.charAt(i) == '(' && isIdentifierKey) { + int parenOpen = i; + int parenClose = findMatchingParen(src, parenOpen); + if (parenClose < 0 || parenClose >= bodyEnd) { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } + + // Extract parameter names and infer return type from the method body. + List params = extractParameterNames(src.substring(parenOpen + 1, parenClose)); + int afterParen = parenClose + 1; + while (afterParen < bodyEnd && Character.isWhitespace(src.charAt(afterParen))) { + afterParen++; + } + // Expect a '{' after the parameter list + if (afterParen >= bodyEnd || src.charAt(afterParen) != '{') { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, afterParen, bodyEnd); + continue; + } + + int braceEnd = findMatchingObjectLiteralEnd(src.substring(afterParen)); + if (braceEnd <= 0) { + sawUnsupported = true; + break; + } + int methodBodyEnd = afterParen + braceEnd; + String bodyText = src.substring(afterParen, methodBodyEnd); + TypeInfo returnType = inferReturnTypeFromBlockBody(bodyText, absBase + afterParen, typeResolver); + + CallableInfo callableInfo = new CallableInfo(params, returnType, + absBase + afterParen, absBase + methodBodyEnd, true); + int keyStartAbs = absBase + keyStart; + int keyEndAbs = absBase + keyEnd; + int valueStartAbs = absBase + parenOpen; + int valueEndAbs = absBase + methodBodyEnd; + + props.add(new ObjectLiteralProperty(keyName, true, keyStartAbs, keyEndAbs, + valueStartAbs, valueEndAbs, returnType, callableInfo)); + i = methodBodyEnd; + while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { + i++; + } + if (i < bodyEnd && src.charAt(i) == ',') { + i++; + } + continue; + } + + // Regular property: key: value if (i >= bodyEnd || src.charAt(i) != ':') { - // Shorthand property or invalid — skip sawUnsupported = true; i = scanToNextTopLevelComma(src, i, bodyEnd); continue; } - i++; // skip ':' + i++; while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { i++; @@ -303,10 +390,17 @@ public final class ObjectLiteralParser { break; } + // Try to detect callable or infer value type TypeInfo valueType = null; + CallableInfo callableInfo = null; if (inferTypes && typeResolver != null) { String valueExpr = src.substring(valueStart, valueEnd).trim(); - valueType = inferValueType(valueExpr, absBase + valueStart, typeResolver); + callableInfo = detectCallableExpression(valueExpr, absBase + valueStart, methodResolver, typeResolver); + if (callableInfo != null) { + valueType = callableInfo.returnType; + } else { + valueType = inferValueType(valueExpr, absBase + valueStart, typeResolver); + } } int keyStartAbs = absBase + keyStart; @@ -316,16 +410,11 @@ public final class ObjectLiteralParser { if (keyName != null) { props.add(new ObjectLiteralProperty(keyName, isIdentifierKey, keyStartAbs, keyEndAbs, - valueStartAbs, valueEndAbs, valueType)); + valueStartAbs, valueEndAbs, valueType, callableInfo)); } i = valueEnd; - while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { - i++; - } - if (i < bodyEnd && src.charAt(i) == ',') { - i++; - } + i = skipSeparatorsAndComments(src, i, bodyEnd); } if (sawUnsupported) { @@ -504,10 +593,12 @@ public final class ObjectLiteralParser { return false; } TypeInfo safeType = (propertyType != null && propertyType.isResolved()) ? propertyType : TypeInfo.ANY; - receiverType.addOrUpdateSyntheticField(propertyName, safeType); + receiverType.removeSyntheticField(propertyName); + receiverType.addSyntheticField(propertyName, safeType); return true; } + /** Holds the resolved receiver type, property name, and field for a dynamic property access result. */ public static final class DynamicFieldResult { public final TypeInfo receiverType; public final String propertyName; @@ -520,6 +611,7 @@ public final class ObjectLiteralParser { } } + /** Resolve an existing field on a dynamic property access receiver without modifying the type shape. */ public static DynamicFieldResult resolveExistingField(DynamicPropertyAccess access, ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { TypeInfo receiver = resolveDynamicPropertyReceiverType(access, typeResolver, varResolver); @@ -527,16 +619,487 @@ public final class ObjectLiteralParser { return new DynamicFieldResult(receiver, access.propertyName, field); } + /** Extend a synthetic object's shape with a new property, then return the resolved field. Overload without RHS text. */ public static DynamicFieldResult extendAndGetField(DynamicPropertyAccess access, TypeInfo existingReceiver, TypeInfo sourceType, ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { + return extendAndGetField(access, existingReceiver, sourceType, null, typeResolver, varResolver); + } + + /** + * Extend a synthetic object's shape with a new property, then return the resolved field. + * When {@code rhsText} is a function expression, a synthetic method is registered instead of a plain field. + */ + public static DynamicFieldResult extendAndGetField(DynamicPropertyAccess access, + TypeInfo existingReceiver, TypeInfo sourceType, String rhsText, + ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { + // Prefer the already-resolved receiver to avoid a redundant re-resolution. TypeInfo receiver = (existingReceiver != null && existingReceiver.isResolved()) ? existingReceiver : resolveDynamicPropertyReceiverType(access, typeResolver, varResolver); - if (!extendSyntheticObjectShape(receiver, access.propertyName, sourceType)) return null; + if (receiver == null || !receiver.isSyntheticObjectLiteralType()) return null; + + // If the RHS looks like a callable (function/arrow/ref), register it as a method; otherwise as a field. + CallableInfo callable = (rhsText != null) ? detectCallableExpression(rhsText.trim(), -1, null, typeResolver) : null; + if (callable != null) { + extendSyntheticObjectWithMethod(receiver, access.propertyName, callable); + } else { + if (!extendSyntheticObjectShape(receiver, access.propertyName, sourceType)) return null; + } return new DynamicFieldResult(receiver, access.propertyName, receiver.getFieldInfo(access.propertyName)); } + /** + * Metadata for a callable property value (function expression, arrow function, or shorthand method). + * + *

Captures the parameter names and the inferred return type so that the property can be + * registered as a synthetic method on the object literal's type.

+ */ + public static final class CallableInfo { + private static final TypeInfo THIS_RETURN_SENTINEL = TypeInfo.unresolved("", ""); + public final List parameterNames; + public final TypeInfo returnType; + public final int bodyStartAbs; + public final int bodyEndAbs; + public final boolean blockBody; + + CallableInfo(List parameterNames, TypeInfo returnType, int bodyStartAbs, int bodyEndAbs, boolean blockBody) { + this.parameterNames = parameterNames != null ? parameterNames : new ArrayList<>(); + this.returnType = returnType; + this.bodyStartAbs = bodyStartAbs; + this.bodyEndAbs = bodyEndAbs; + this.blockBody = blockBody; + } + + public boolean returnsThis() { + return returnType == THIS_RETURN_SENTINEL; + } + + static TypeInfo thisReturnSentinel() { + return THIS_RETURN_SENTINEL; + } + } + + // ────────────────────────────────────────────────────────────────────────── + // Callable expression detection + // ────────────────────────────────────────────────────────────────────────── + + /** + * Detect whether a value expression is callable (function expression, arrow function, or bare script method reference). + * Returns a {@link CallableInfo} with parameter names and inferred return type, or {@code null} if not callable. + */ + static CallableInfo detectCallableExpression(String expr, int exprStartAbs, + MethodReferenceResolverFn methodResolver, + ExpressionTypeResolverFn typeResolver) { + if (expr == null || expr.isEmpty()) return null; + + // Inline function expression: function(...) { ... } + if (expr.startsWith("function")) { + return parseFunctionExpressionCallable(expr, exprStartAbs, typeResolver); + } + + // Arrow function: (...) => ... or x => ... + if (expr.contains("=>")) { + return parseArrowFunctionCallable(expr, exprStartAbs, typeResolver); + } + + // Bare identifier that resolves to a known script method (e.g. onTick: handleTick) + if (isSimpleIdentifier(expr.trim()) && methodResolver != null) { + MethodInfo method = methodResolver.resolve(expr.trim(), new TypeInfo[0]); + if (method != null) { + TypeInfo returnType = method.getReturnType() != null ? method.getReturnType() : TypeInfo.ANY; + List paramNames = new ArrayList<>(); + for (FieldInfo param : method.getParameters()) paramNames.add(param.getName()); + return new CallableInfo(paramNames, returnType, exprStartAbs, exprStartAbs + expr.trim().length(), false); + } + } + + return null; + } + + /** Parse a {@code function(...) { ... }} expression into a CallableInfo, extracting params and inferring return type. */ + private static CallableInfo parseFunctionExpressionCallable(String expr, int exprStartAbs, + ExpressionTypeResolverFn typeResolver) { + int parenOpen = expr.indexOf('('); + if (parenOpen < 0) return null; + int parenClose = findMatchingParen(expr, parenOpen); + if (parenClose < 0) return null; + + List params = extractParameterNames(expr.substring(parenOpen + 1, parenClose)); + TypeInfo returnType = inferReturnTypeFromBody(expr, parenClose + 1, exprStartAbs, typeResolver); + String rest = expr.substring(parenClose + 1).trim(); + int bodyOffset = expr.indexOf(rest, parenClose + 1); + return new CallableInfo(params, returnType, + exprStartAbs >= 0 ? exprStartAbs + Math.max(bodyOffset, 0) : -1, + exprStartAbs >= 0 ? exprStartAbs + expr.length() : -1, + rest.startsWith("{")); + } + + /** + * Parse an arrow function — handles both parenthesized params {@code (a, b) => ...} + * and single bare param {@code x => ...}. + */ + private static CallableInfo parseArrowFunctionCallable(String expr, int exprStartAbs, + ExpressionTypeResolverFn typeResolver) { + int arrowIdx = findArrowOperator(expr); + if (arrowIdx < 0) return null; + + String paramPart = expr.substring(0, arrowIdx).trim(); + List params; + if (paramPart.startsWith("(") && paramPart.endsWith(")")) { + // Parenthesized parameter list + params = extractParameterNames(paramPart.substring(1, paramPart.length() - 1)); + } else { + // Single bare parameter (no parens) + params = new ArrayList<>(); + if (isSimpleIdentifier(paramPart)) { + params.add(paramPart); + } + } + + String bodyPart = expr.substring(arrowIdx + 2).trim(); + int bodyOffset = expr.indexOf(bodyPart, arrowIdx + 2); + int bodyStartAbs = exprStartAbs >= 0 ? exprStartAbs + Math.max(bodyOffset, 0) : -1; + // Route both block and expression bodies through the shared inference path + TypeInfo returnType = inferReturnTypeFromBody(bodyPart, 0, bodyStartAbs, typeResolver); + return new CallableInfo(params, returnType, + bodyStartAbs, + bodyStartAbs >= 0 ? bodyStartAbs + bodyPart.length() : -1, + bodyPart.startsWith("{")); + } + + /** + * Find the {@code =>} operator in an arrow function expression, skipping strings and nested parentheses + * to avoid false positives from comparison operators inside nested expressions. + */ + private static int findArrowOperator(String expr) { + boolean inString = false; + char stringChar = 0; + int parenDepth = 0; + + for (int i = 0; i < expr.length() - 1; i++) { + char c = expr.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '(') parenDepth++; + else if (c == ')') parenDepth = Math.max(0, parenDepth - 1); + + if (c == '=' && expr.charAt(i + 1) == '>' && parenDepth == 0) { + return i; + } + } + return -1; + } + + /** Split a comma-separated parameter list into individual names, stripping any leading type annotation. */ + private static List extractParameterNames(String paramList) { + List params = new ArrayList<>(); + if (paramList == null || paramList.trim().isEmpty()) return params; + + for (String part : paramList.split(",")) { + String name = part.trim(); + int spaceIdx = name.indexOf(' '); + if (spaceIdx > 0) name = name.substring(0, spaceIdx); + if (isSimpleIdentifier(name)) { + params.add(name); + } + } + return params; + } + + /** Find the closing {@code )} matching the opening {@code (} at {@code openPos}, respecting strings and nesting. */ + private static int findMatchingParen(String src, int openPos) { + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = openPos; i < src.length(); i++) { + char c = src.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '(') depth++; + else if (c == ')') { depth--; if (depth == 0) return i; } + } + return -1; + } + + /** Infer the return type from the portion of a function expression after the parameter list. */ + private static TypeInfo inferReturnTypeFromBody(String expr, int afterParams, + int exprStartAbs, ExpressionTypeResolverFn typeResolver) { + String rest = expr.substring(afterParams).trim(); + int restOffset = expr.indexOf(rest, afterParams); + int restStartAbs = exprStartAbs >= 0 ? exprStartAbs + restOffset : -1; + if (rest.startsWith("{")) { + return inferReturnTypeFromBlockBody(rest, restStartAbs, typeResolver); + } + return inferReturnTypeFromExpressionBody(rest, restStartAbs, typeResolver); + } + + /** + * Infer a return type from a block body {@code { ... }} by scanning {@code return} statements + * and resolving each expression via the type resolver. Falls back to {@code ANY} if nothing resolves. + */ + private static TypeInfo inferReturnTypeFromBlockBody(String body, int bodyStartAbs, + ExpressionTypeResolverFn typeResolver) { + if (body == null || !body.startsWith("{")) return TypeInfo.ANY; + + int endBrace = findMatchingObjectLiteralEnd(body); + if (endBrace <= 0) return TypeInfo.ANY; + + String inner = body.substring(1, endBrace - 1); + int innerStartAbs = bodyStartAbs >= 0 ? bodyStartAbs + 1 : -1; + + // Scan for 'return ' statements and resolve each one. + int i = 0; + while (i < inner.length()) { + int returnIdx = inner.indexOf("return", i); + if (returnIdx < 0) break; + + // Ensure 'return' is a keyword boundary, not part of a longer identifier. + if (returnIdx > 0 && Character.isJavaIdentifierPart(inner.charAt(returnIdx - 1))) { + i = returnIdx + 6; + continue; + } + int afterReturn = returnIdx + 6; + if (afterReturn >= inner.length()) break; + char afterChar = inner.charAt(afterReturn); + if (!Character.isWhitespace(afterChar) && afterChar != ';') { + i = afterReturn; + continue; + } + + while (afterReturn < inner.length() && Character.isWhitespace(inner.charAt(afterReturn))) { + afterReturn++; + } + + // Scan to end of the return expression (stop at ';' or newline at depth 0). + int exprEnd = afterReturn; + int depth = 0; + while (exprEnd < inner.length()) { + char c = inner.charAt(exprEnd); + if (c == '{' || c == '(' || c == '[') depth++; + else if (c == '}' || c == ')' || c == ']') { if (depth == 0) break; depth--; } + else if ((c == ';' || c == '\n' || c == '\r') && depth == 0) break; + exprEnd++; + } + + String returnExpr = inner.substring(afterReturn, exprEnd).trim(); + if (returnExpr.isEmpty()) { i = exprEnd + 1; continue; } + + if ("this".equals(returnExpr)) return CallableInfo.thisReturnSentinel(); + + // Try full type resolution, then fall back to literal matching. + if (typeResolver != null && innerStartAbs >= 0) { + TypeInfo resolved = typeResolver.resolve(returnExpr, innerStartAbs + afterReturn); + if (resolved != null && resolved.isResolved()) return resolved; + } + TypeInfo literal = resolveLiteralType(returnExpr); + if (literal != TypeInfo.ANY) return literal; + + i = exprEnd + 1; + } + + return TypeInfo.ANY; + } + + /** + * Infer a return type from a concise arrow-function body (expression, not block). + * Delegates to the type resolver first, then falls back to literal pattern matching. + */ + private static TypeInfo inferReturnTypeFromExpressionBody(String bodyExpr, int bodyStartAbs, + ExpressionTypeResolverFn typeResolver) { + if (bodyExpr == null || bodyExpr.isEmpty()) return TypeInfo.ANY; + bodyExpr = bodyExpr.trim(); + + if ("this".equals(bodyExpr)) return CallableInfo.thisReturnSentinel(); + + // Full resolution via ScriptDocument — covers variables, method calls, chains, etc. + if (typeResolver != null && bodyStartAbs >= 0) { + TypeInfo resolved = typeResolver.resolve(bodyExpr, bodyStartAbs); + if (resolved != null && resolved.isResolved()) return resolved; + } + + return resolveLiteralType(bodyExpr); + } + + /** Match simple literal expressions to their TypeInfo without needing a resolver. */ + private static TypeInfo resolveLiteralType(String expr) { + if (expr.startsWith("{") && expr.endsWith("}")) return TypeInfo.ANY; + if (expr.startsWith("\"") && expr.endsWith("\"")) return TypeInfo.string(); + if (expr.startsWith("'") && expr.endsWith("'")) return TypeInfo.fromPrimitive("char"); + if (expr.equals("true") || expr.equals("false")) return TypeInfo.fromPrimitive("boolean"); + if (expr.matches("[-+]?\\d*\\.?\\d+[fFdD]?")) return TypeInfo.NUMBER; + if (expr.contains("+") || expr.contains("-") || expr.contains("*") || expr.contains("/") || expr.contains("%")) return TypeInfo.NUMBER; + return TypeInfo.ANY; + } + + /** + * Register a callable property as both a synthetic field (for field-access resolution) + * and a synthetic method (for call-site resolution) on the receiver's type shape. + */ + private static void extendSyntheticObjectWithMethod(TypeInfo receiver, String name, CallableInfo callable) { + // Build typed parameter list — all params default to ANY since we only have names, not types. + List params = new ArrayList<>(); + for (String paramName : callable.parameterNames) { + params.add(FieldInfo.external(paramName, TypeInfo.ANY, null, java.lang.reflect.Modifier.PUBLIC)); + } + // Use 'receiver' as the return type sentinel when the method returns 'this'. + TypeInfo returnType = callable.returnsThis() ? receiver : (callable.returnType != null ? callable.returnType : TypeInfo.ANY); + receiver.removeSyntheticField(name); + receiver.addSyntheticField(name, TypeInfo.ANY); + receiver.removeSyntheticMethod(name); + receiver.addSyntheticMethod(name, returnType, params); + } + + /** + * Walk backward from the start of an inner callable scope to find the enclosing object literal and + * attach its inferred {@link TypeInfo} as the scope's containing object type (enabling {@code this.} resolution). + * Handles three cases: {@code key: function(...)} (colon), {@code obj = { ... }} (equals), and shorthand methods. + */ + static void attachObjectLiteralContext(InnerCallableScope scope, ScriptDocument doc) { + // Only applicable for JS; skip if already has a containing object type. + if (!doc.isJavaScript() || scope == null || scope.getContainingObjectType() != null) { + return; + } + String text = doc.getText(); + int headerStart = scope.getHeaderStart(); + if (headerStart < 0 || headerStart >= text.length()) { + return; + } + + // Walk backward from the scope header to find a ':' or '=' that indicates object literal context. + int searchPos = headerStart - 1; + while (searchPos >= 0 && Character.isWhitespace(text.charAt(searchPos))) { + searchPos--; + } + if (searchPos < 0) { + return; + } + + // Find the opening '{' of the enclosing object literal by walking backward, respecting nesting and strings. + int braceStart = -1; + if (text.charAt(searchPos) == ':') { + // Case 1: key: function(...) — find the containing {...} + searchPos--; + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } else if (text.charAt(searchPos) == '=') { + // Case 2: variable = {...} — find the containing {...} + searchPos--; + while (searchPos >= 0 && Character.isWhitespace(text.charAt(searchPos))) { + searchPos--; + } + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } else if (scope.getKind() == InnerCallableScope.Kind.JS_SHORTHAND_METHOD) { + // Case 3: Shorthand method inside {...} — find the containing {...} + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } + + if (braceStart < 0) { + return; + } + + ObjectLiteralAnalysis analysis = doc.getObjectLiteral(braceStart); + if (analysis != null && analysis.inferredType != null) { + scope.setContainingObjectType(analysis.inferredType); + } + } + + + /** + * Infer the TypeInfo for a single value expression inside an object literal. + * Nested object literals are recursively parsed; arrays and other complex expressions fall back to {@code ANY}. + */ private static TypeInfo inferValueType(String valueExpr, int valueStartAbs, ExpressionTypeResolverFn typeResolver) { if (valueExpr == null || valueExpr.isEmpty()) { return TypeInfo.ANY; @@ -544,7 +1107,7 @@ public final class ObjectLiteralParser { char first = valueExpr.charAt(0); if (first == '{') { - ObjectLiteralAnalysis nested = parse(valueExpr, valueStartAbs, true, false, typeResolver); + ObjectLiteralAnalysis nested = parse(valueExpr, valueStartAbs, true, false, typeResolver,null); if (nested != null && nested.supportsInference && nested.inferredType != null) { return nested.inferredType; } @@ -704,6 +1267,116 @@ public final class ObjectLiteralParser { return endLimit; } + /** Advance past whitespace, commas, and line/block comments between object literal properties. */ + private static int skipSeparatorsAndComments(String src, int start, int endLimit) { + int i = start; + while (i < endLimit) { + char c = src.charAt(i); + char next = (i + 1 < endLimit) ? src.charAt(i + 1) : 0; + if (Character.isWhitespace(c) || c == ',') { + i++; + continue; + } + if (c == '/' && next == '/') { + i += 2; + while (i < endLimit) { + char line = src.charAt(i); + if (line == '\n' || line == '\r') { + break; + } + i++; + } + continue; + } + if (c == '/' && next == '*') { + i += 2; + while (i + 1 < endLimit) { + if (src.charAt(i) == '*' && src.charAt(i + 1) == '/') { + i += 2; + break; + } + i++; + } + continue; + } + break; + } + return i; + } + + /** + * Determine whether the document position is inside an object literal by counting unmatched braces + * and verifying that the nearest enclosing {@code {} is preceded by {@code =}, {@code :}, {@code (}, etc. + */ + static boolean isInsideObjectLiteral(int position, ScriptDocument doc) { + // First pass: count unmatched braces forward to position to check if we're in a brace context. + int braceDepth = 0; + boolean inString = false; + char stringChar = 0; + String text = doc.getText(); + for (int i = 0; i < position && i < text.length(); i++) { + if (doc.isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '{') braceDepth++; + else if (c == '}') braceDepth = Math.max(0, braceDepth - 1); + } + // Not inside any braces at all. + if (braceDepth <= 0) return false; + + // Second pass: walk backward to find the matching '{' for our position. + int braceStart = -1; + int depth = 0; + inString = false; + stringChar = 0; + for (int i = position - 1; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + if (braceStart < 0) { + return false; + } + + // Third pass: check if the '{' is preceded by a literal indicator (=, :, (, [, comma, or nested {). + for (int i = braceStart - 1; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i) || Character.isWhitespace(c)) { + continue; + } + return c == '=' || c == ':' || c == '(' || c == '[' || c == ',' || c == '{'; + } + return true; + } + /** * Scan forward to find the next top-level comma (skipping nested structures and strings). * diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java index 5fd9f7155..f26c3cd9d 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java @@ -136,6 +136,11 @@ public class ScriptDocument { // SAM context tracking for named function references // Maps method name -> first SAM signature applied (for conflict detection) private final Map scriptMethodSamContexts = new HashMap<>(); + + // Cached object literal analyses, keyed by brace-start offset in text. + // Populated once in parseObjectLiterals() and consumed by markObjectLiteralKeys, + // resolveExpressionType, and attachObjectLiteralContext. + private final Map objectLiterals = new HashMap<>(); // Thread-local to communicate SAM conflict errors from resolveIdentifier back to parseMethodArguments // Set when injectSamParameterTypes detects a conflict, cleared after argument is created @@ -359,6 +364,7 @@ public class ScriptDocument { externalFieldAssignments.clear(); declarationErrors.clear(); scriptMethodSamContexts.clear(); + objectLiterals.clear(); // Unified pipeline for both languages List marks = formatUnified(); @@ -701,6 +707,9 @@ public class ScriptDocument { // Parse and validate assignments (reassignments) - UNIFIED for both languages parseAssignments(); + // Cache object literals after globals/locals are available for accurate value-type inference + parseObjectLiterals(); + // Detect method overrides and interface implementations for script types - Java only if (!isJavaScript()) { detectMethodInheritance(); @@ -2662,7 +2671,7 @@ public class ScriptDocument { int start = m.start(); if (isExcluded(start)) continue; - if (!isInsideObjectLiteral(start)) continue; + if (!ObjectLiteralParser.isInsideObjectLiteral(start,this)) continue; String methodName = m.group(1); if (TypeChecker.isJavaScriptKeyword(methodName)) continue; @@ -3381,36 +3390,42 @@ public class ScriptDocument { } private void markObjectLiteralKeys(List marks) { + for (ObjectLiteralParser.ObjectLiteralAnalysis analysis : objectLiterals.values()) { + for (ObjectLiteralParser.ObjectLiteralProperty p : analysis.properties) { + if (p.isIdentifierKey) { + marks.add(new ScriptLine.Mark(p.keyStartAbs, p.keyEndAbs, TokenType.LOCAL_FIELD)); + } + } + } + } + + private void parseObjectLiterals() { + if (!isJavaScript()) return; int i = 0; while (i < text.length()) { int brace = text.indexOf('{', i); - if (brace < 0) { - return; - } - i = brace; + if (brace < 0) break; if (isExcluded(brace) || !isLikelyObjectLiteralStart(brace)) { - i++; + i = brace + 1; continue; } - int end = findMatchingBraceEndInDocument(brace); if (end <= brace) { - i++; + i = brace + 1; continue; } - String objectLiteral = text.substring(brace, end); - ObjectLiteralParser.ObjectLiteralAnalysis analysis = ObjectLiteralParser.parse(objectLiteral, brace, false, true, null); - if (analysis != null) { - for (ObjectLiteralParser.ObjectLiteralProperty p : analysis.properties) { - if (p.isIdentifierKey) { - marks.add(new ScriptLine.Mark(p.keyStartAbs, p.keyEndAbs, TokenType.LOCAL_FIELD)); - } - } - } - + ObjectLiteralParser.ObjectLiteralAnalysis analysis = + ObjectLiteralParser.parse(objectLiteral, brace, true, true, this::resolveExpressionType, this::getScriptMethodInfo); + if (analysis != null) + objectLiterals.put(brace, analysis); + i = brace + 1; } + // Wire each object-literal inner scope to its containing object type (needs the cache) + for (InnerCallableScope scope : innerScopes) + ObjectLiteralParser.attachObjectLiteralContext(scope, this); + } private boolean isLikelyObjectLiteralStart(int bracePos) { @@ -5305,11 +5320,17 @@ public class ScriptDocument { expr = expr.trim(); expr = stripLineComments(expr); + if (expr.endsWith(".")) + expr = expr.substring(0, expr.length() - 1).trim(); + if (expr.isEmpty()) return null; if (isJavaScript() && expr.charAt(0) == '{') { - ObjectLiteralParser.ObjectLiteralAnalysis analysis = ObjectLiteralParser.parse(expr, position, true, false, this::resolveExpressionType); + ObjectLiteralParser.ObjectLiteralAnalysis analysis = objectLiterals.get(position); + if (analysis == null) + analysis = ObjectLiteralParser.parse(expr, position, true, false, this::resolveExpressionType, this::getScriptMethodInfo); + if (analysis == null) { return TypeInfo.ANY; } @@ -6022,10 +6043,16 @@ public class ScriptDocument { return true; case '<': - // Could be < > <= >= << or generics + // <<, <= are always operators if (next == '<' || next == '=') return true; - // Check if this looks like relational (not generic type params) - // Generics typically follow a type name directly with no space + // If preceded by digit/)/] it's definitely a relational operator (not a generic) + prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prevC = expr.charAt(prevIdx); + if (Character.isDigit(prevC) || prevC == ')' || prevC == ']') return true; + } + // Generics follow an uppercase type name; anything else is relational int nextNonSpace = i + 1; while (nextNonSpace < expr.length() && Character.isWhitespace(expr.charAt(nextNonSpace))) nextNonSpace++; if (nextNonSpace < expr.length() && !Character.isUpperCase(expr.charAt(nextNonSpace))) { @@ -6034,8 +6061,15 @@ public class ScriptDocument { break; case '>': + // >>, >= are always operators if (next == '>' || next == '=') return true; - // Similar check for generics + // If preceded by digit/)/] it's definitely a relational operator (not closing generic) + prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prevC = expr.charAt(prevIdx); + if (Character.isDigit(prevC) || prevC == ')' || prevC == ']') return true; + } break; case '!': @@ -6651,7 +6685,7 @@ public class ScriptDocument { /** * Get the best matching script method overload based on argument types. */ - private MethodInfo getScriptMethodInfo(String methodName, TypeInfo[] argTypes) { + MethodInfo getScriptMethodInfo(String methodName, TypeInfo[] argTypes) { List candidates = new ArrayList<>(); // Collect all methods with matching name @@ -7383,7 +7417,7 @@ public class ScriptDocument { if (dynamicPropertyAccess != null) { ObjectLiteralParser.DynamicFieldResult res = ObjectLiteralParser.extendAndGetField( - dynamicPropertyAccess, receiverType, sourceType, + dynamicPropertyAccess, receiverType, sourceType, rhs, this::resolveExpressionType, this::resolveVariable); if (res != null) { receiverType = res.receiverType; @@ -8323,6 +8357,10 @@ public class ScriptDocument { return Collections.unmodifiableList(innerScopes); } + public ObjectLiteralParser.ObjectLiteralAnalysis getObjectLiteral(int braceOffset) { + return objectLiterals.get(braceOffset); + } + public List getScriptTypes() { return scriptTypes.values().stream().collect(Collectors.toList()); } diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java index 1d15032a0..f7b552323 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java @@ -353,17 +353,44 @@ public class TypeInfo { if (properties != null) { for (ObjectLiteralParser.ObjectLiteralProperty p : properties) { TypeInfo vt = (p.valueType != null) ? p.valueType : TypeInfo.ANY; - t.syntheticFields.add(FieldInfo.external(p.keyName, vt, null, Modifier.PUBLIC)); + if (p.isCallable()) { + ObjectLiteralParser.CallableInfo ci = p.callableInfo; + t.syntheticFields.add(FieldInfo.external(p.keyName, TypeInfo.ANY, null, Modifier.PUBLIC)); + TypeInfo returnType = ci.returnsThis() ? t : ci.returnType; + if (returnType == null) { + returnType = t; + } + List params = new ArrayList<>(); + for (String paramName : ci.parameterNames) { + params.add(FieldInfo.external(paramName, TypeInfo.ANY, null, Modifier.PUBLIC)); + } + t.syntheticMethods.add(MethodInfo.external(p.keyName, returnType, t, + params, Modifier.PUBLIC, null)); + } else { + t.syntheticFields.add(FieldInfo.external(p.keyName, vt, null, Modifier.PUBLIC)); + } } } return t; } - public void addOrUpdateSyntheticField(String name, TypeInfo type) { - syntheticFields.removeIf(f -> f.getName().equals(name)); + public void addSyntheticField(String name, TypeInfo type) { syntheticFields.add(FieldInfo.external(name, type, null, Modifier.PUBLIC)); } + public void removeSyntheticField(String name) { + syntheticFields.removeIf(f -> f.getName().equals(name)); + } + + public void addSyntheticMethod(String name, TypeInfo returnType, List params) { + syntheticMethods.add(MethodInfo.external(name, returnType, this, + params != null ? params : Collections.emptyList(), Modifier.PUBLIC, null)); + } + + public void removeSyntheticMethod(String name) { + syntheticMethods.removeIf(m -> m.getName().equals(name)); + } + public static void injectJSMembers(TypeInfo target, JSTypeInfo jsExtensions) { for (JSFieldInfo jsField : jsExtensions.getFields().values()) target.syntheticFields.add(FieldInfo.fromJSField(jsField, target));