mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-20 04:09:57 +00:00
JS PARSER MK.I
This commit is contained in:
1 parent
6948690042
commit
79d1b74a0f
192 files changed
+8462
-14
No files matched your search
@@ -195,6 +195,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
activeArea.init(editorX, editorY, editorWidth, editorHeight,
|
||||
container == null ? "" : container.script);
|
||||
}
|
||||
|
||||
// Set the scripting language for proper syntax highlighting
|
||||
activeArea.setLanguage(this.handler.getLanguage());
|
||||
|
||||
// Setup fullscreen key binding
|
||||
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
|
||||
|
||||
@@ -2331,6 +2331,26 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
this.enableCodeHighlighting = true;
|
||||
this.container.formatCodeText();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the scripting language for syntax highlighting and type inference.
|
||||
* @param language The language name (e.g., "ECMAScript", "Groovy")
|
||||
*/
|
||||
public void setLanguage(String language) {
|
||||
if (this.container != null) {
|
||||
this.container.setLanguage(language);
|
||||
if (this.enableCodeHighlighting) {
|
||||
this.container.formatCodeText();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current scripting language.
|
||||
*/
|
||||
public String getLanguage() {
|
||||
return this.container != null ? this.container.getLanguage() : "ECMAScript";
|
||||
}
|
||||
|
||||
public void setListener(ITextChangeListener listener) {
|
||||
this.listener = listener;
|
||||
|
||||
@@ -8,6 +8,7 @@ import noppes.npcs.client.gui.util.script.interpreter.field.AssignmentInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSScriptAnalyzer;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature;
|
||||
@@ -114,6 +115,9 @@ public class ScriptDocument {
|
||||
|
||||
// Type resolver
|
||||
private final TypeResolver typeResolver;
|
||||
|
||||
// Script language: "ECMAScript", "Groovy", etc.
|
||||
private String language = "ECMAScript";
|
||||
|
||||
// Layout properties
|
||||
public int lineHeight = 13;
|
||||
@@ -132,6 +136,33 @@ public class ScriptDocument {
|
||||
this.typeResolver = resolver != null ? resolver : TypeResolver.getInstance();
|
||||
setText(text);
|
||||
}
|
||||
|
||||
public ScriptDocument(String text, String language) {
|
||||
this.typeResolver = TypeResolver.getInstance();
|
||||
this.language = language != null ? language : "ECMAScript";
|
||||
setText(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the scripting language.
|
||||
*/
|
||||
public void setLanguage(String language) {
|
||||
this.language = language != null ? language : "ECMAScript";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scripting language.
|
||||
*/
|
||||
public String getLanguage() {
|
||||
return language;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a JavaScript/ECMAScript document.
|
||||
*/
|
||||
public boolean isJavaScript() {
|
||||
return "ECMAScript".equalsIgnoreCase(language);
|
||||
}
|
||||
|
||||
// ==================== TEXT MANAGEMENT ====================
|
||||
|
||||
@@ -219,18 +250,15 @@ public class ScriptDocument {
|
||||
methodCalls.clear();
|
||||
externalFieldAssignments.clear();
|
||||
declarationErrors.clear();
|
||||
|
||||
// Phase 1: Find excluded regions (strings/comments)
|
||||
findExcludedRanges();
|
||||
|
||||
// Phase 2: Parse imports
|
||||
parseImports();
|
||||
|
||||
// Phase 3: Parse structure (script types, methods, fields, locals)
|
||||
parseStructure();
|
||||
|
||||
// Phase 4: Build marks and assign to lines
|
||||
List<ScriptLine.Mark> marks = buildMarks();
|
||||
|
||||
List<ScriptLine.Mark> marks;
|
||||
|
||||
// Use different analysis paths for JavaScript vs Java
|
||||
if (isJavaScript()) {
|
||||
marks = formatJavaScript();
|
||||
} else {
|
||||
marks = formatJava();
|
||||
}
|
||||
|
||||
// Phase 5: Resolve conflicts and sort
|
||||
marks = resolveConflicts(marks);
|
||||
@@ -243,6 +271,32 @@ public class ScriptDocument {
|
||||
// Phase 7: Compute indent guides
|
||||
computeIndentGuides(marks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format JavaScript/ECMAScript code using the JS type inference system.
|
||||
*/
|
||||
private List<ScriptLine.Mark> formatJavaScript() {
|
||||
// Use JSScriptAnalyzer for JS-specific analysis
|
||||
JSScriptAnalyzer analyzer = new JSScriptAnalyzer(text);
|
||||
return analyzer.analyze();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Java/Groovy code using the full Java analysis system.
|
||||
*/
|
||||
private List<ScriptLine.Mark> formatJava() {
|
||||
// Phase 1: Find excluded regions (strings/comments)
|
||||
findExcludedRanges();
|
||||
|
||||
// Phase 2: Parse imports
|
||||
parseImports();
|
||||
|
||||
// Phase 3: Parse structure (script types, methods, fields, locals)
|
||||
parseStructure();
|
||||
|
||||
// Phase 4: Build marks and assign to lines
|
||||
return buildMarks();
|
||||
}
|
||||
|
||||
// ==================== PHASE 1: EXCLUDED RANGES ====================
|
||||
|
||||
|
||||
+30
-1
@@ -31,6 +31,9 @@ public class ScriptTextContainer extends JavaTextContainer {
|
||||
public static boolean USE_NEW_INTERPRETER = true;
|
||||
|
||||
private ScriptDocument document;
|
||||
|
||||
/** The scripting language: "ECMAScript", "Groovy", etc. */
|
||||
private String language = "ECMAScript";
|
||||
|
||||
public ScriptTextContainer(String text) {
|
||||
super(text);
|
||||
@@ -38,6 +41,32 @@ public class ScriptTextContainer extends JavaTextContainer {
|
||||
document = new ScriptDocument(text);
|
||||
}
|
||||
}
|
||||
|
||||
public ScriptTextContainer(String text, String language) {
|
||||
super(text);
|
||||
this.language = language != null ? language : "ECMAScript";
|
||||
if (USE_NEW_INTERPRETER) {
|
||||
document = new ScriptDocument(text, this.language);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the scripting language. This affects syntax highlighting and type inference.
|
||||
* @param language The language name (e.g., "ECMAScript", "Groovy")
|
||||
*/
|
||||
public void setLanguage(String language) {
|
||||
this.language = language != null ? language : "ECMAScript";
|
||||
if (document != null) {
|
||||
document.setLanguage(this.language);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current scripting language.
|
||||
*/
|
||||
public String getLanguage() {
|
||||
return language;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(int width, int height) {
|
||||
@@ -73,7 +102,7 @@ public class ScriptTextContainer extends JavaTextContainer {
|
||||
return;
|
||||
}
|
||||
|
||||
document = new ScriptDocument(this.text);
|
||||
document = new ScriptDocument(this.text, this.language);
|
||||
init(width, height);
|
||||
}
|
||||
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
/**
|
||||
* Represents a field/property in a TypeScript interface.
|
||||
*/
|
||||
public class JSFieldInfo {
|
||||
|
||||
private final String name;
|
||||
private final String type; // Raw type string
|
||||
private final boolean readonly;
|
||||
private String documentation;
|
||||
|
||||
public JSFieldInfo(String name, String type, boolean readonly) {
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
this.readonly = readonly;
|
||||
}
|
||||
|
||||
public JSFieldInfo setDocumentation(String documentation) {
|
||||
this.documentation = documentation;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Getters
|
||||
public String getName() { return name; }
|
||||
public String getType() { return type; }
|
||||
public boolean isReadonly() { return readonly; }
|
||||
public String getDocumentation() { return documentation; }
|
||||
|
||||
/**
|
||||
* Build hover info HTML for this field.
|
||||
*/
|
||||
public String buildHoverInfo() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (readonly) {
|
||||
sb.append("<i>readonly</i> ");
|
||||
}
|
||||
sb.append("<b>").append(name).append("</b>: <i>").append(type).append("</i>");
|
||||
|
||||
if (documentation != null && !documentation.isEmpty()) {
|
||||
sb.append("<br><br>").append(documentation);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return (readonly ? "readonly " : "") + name + ": " + type;
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Container classes for hover information in JS scripts.
|
||||
*/
|
||||
public class JSHoverInfo {
|
||||
|
||||
/**
|
||||
* Hover info for a variable.
|
||||
*/
|
||||
public static class VariableInfo {
|
||||
public final String name;
|
||||
public final String typeName;
|
||||
public final JSTypeInfo resolvedType;
|
||||
|
||||
public VariableInfo(String name, String typeName, JSTypeInfo resolvedType) {
|
||||
this.name = name;
|
||||
this.typeName = typeName;
|
||||
this.resolvedType = resolvedType;
|
||||
}
|
||||
|
||||
public String buildHoverHtml() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("<b>").append(name).append("</b>: <i>").append(typeName).append("</i>");
|
||||
|
||||
if (resolvedType != null && resolvedType.getDocumentation() != null) {
|
||||
sb.append("<br><br>").append(resolvedType.getDocumentation());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hover info for a method.
|
||||
*/
|
||||
public static class MethodInfo {
|
||||
public final JSMethodInfo method;
|
||||
public final JSTypeInfo containingType;
|
||||
|
||||
public MethodInfo(JSMethodInfo method, JSTypeInfo containingType) {
|
||||
this.method = method;
|
||||
this.containingType = containingType;
|
||||
}
|
||||
|
||||
public String buildHoverHtml() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// Show containing type
|
||||
if (containingType != null) {
|
||||
sb.append("<i>").append(containingType.getFullName()).append("</i><br>");
|
||||
}
|
||||
|
||||
// Show method signature
|
||||
sb.append(method.buildHoverInfo());
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hover info for a field.
|
||||
*/
|
||||
public static class FieldInfo {
|
||||
public final JSFieldInfo field;
|
||||
public final JSTypeInfo containingType;
|
||||
|
||||
public FieldInfo(JSFieldInfo field, JSTypeInfo containingType) {
|
||||
this.field = field;
|
||||
this.containingType = containingType;
|
||||
}
|
||||
|
||||
public String buildHoverHtml() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// Show containing type
|
||||
if (containingType != null) {
|
||||
sb.append("<i>").append(containingType.getFullName()).append("</i><br>");
|
||||
}
|
||||
|
||||
// Show field info
|
||||
sb.append(field.buildHoverInfo());
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hover info for a hook function.
|
||||
*/
|
||||
public static class FunctionInfo {
|
||||
public final String name;
|
||||
public final List<JSTypeRegistry.HookSignature> signatures;
|
||||
|
||||
public FunctionInfo(String name, List<JSTypeRegistry.HookSignature> signatures) {
|
||||
this.name = name;
|
||||
this.signatures = signatures;
|
||||
}
|
||||
|
||||
public String buildHoverHtml() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("<b>Hook: ").append(name).append("</b>");
|
||||
|
||||
if (!signatures.isEmpty()) {
|
||||
sb.append("<br><br>Overloads:");
|
||||
for (JSTypeRegistry.HookSignature sig : signatures) {
|
||||
sb.append("<br>• function ").append(name).append("(")
|
||||
.append(sig.paramName).append(": <i>").append(sig.paramType).append("</i>)");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Represents a method signature parsed from .d.ts files.
|
||||
*/
|
||||
public class JSMethodInfo {
|
||||
|
||||
private final String name;
|
||||
private final String returnType; // Raw type string, e.g., "number", "IEntity", "void"
|
||||
private final List<JSParameterInfo> parameters;
|
||||
private String documentation;
|
||||
|
||||
public JSMethodInfo(String name, String returnType, List<JSParameterInfo> parameters) {
|
||||
this.name = name;
|
||||
this.returnType = returnType;
|
||||
this.parameters = parameters != null ? new ArrayList<>(parameters) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public JSMethodInfo setDocumentation(String documentation) {
|
||||
this.documentation = documentation;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Getters
|
||||
public String getName() { return name; }
|
||||
public String getReturnType() { return returnType; }
|
||||
public List<JSParameterInfo> getParameters() { return parameters; }
|
||||
public String getDocumentation() { return documentation; }
|
||||
public int getParameterCount() { return parameters.size(); }
|
||||
|
||||
/**
|
||||
* Get a formatted signature string for display.
|
||||
*/
|
||||
public String getSignature() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(name).append("(");
|
||||
for (int i = 0; i < parameters.size(); i++) {
|
||||
if (i > 0) sb.append(", ");
|
||||
JSParameterInfo param = parameters.get(i);
|
||||
sb.append(param.getName()).append(": ").append(param.getType());
|
||||
}
|
||||
sb.append("): ").append(returnType);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build hover info HTML for this method.
|
||||
*/
|
||||
public String buildHoverInfo() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("<b>").append(name).append("</b>(");
|
||||
for (int i = 0; i < parameters.size(); i++) {
|
||||
if (i > 0) sb.append(", ");
|
||||
JSParameterInfo param = parameters.get(i);
|
||||
sb.append(param.getName()).append(": <i>").append(param.getType()).append("</i>");
|
||||
}
|
||||
sb.append("): <i>").append(returnType).append("</i>");
|
||||
|
||||
if (documentation != null && !documentation.isEmpty()) {
|
||||
sb.append("<br><br>").append(documentation);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getSignature();
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a parameter in a method signature.
|
||||
*/
|
||||
public static class JSParameterInfo {
|
||||
private final String name;
|
||||
private final String type;
|
||||
|
||||
public JSParameterInfo(String name, String type) {
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getName() { return name; }
|
||||
public String getType() { return type; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + ": " + type;
|
||||
}
|
||||
}
|
||||
}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.interpreter.ScriptLine;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
|
||||
/**
|
||||
* Analyzes JavaScript scripts to produce syntax highlighting marks and type information.
|
||||
* Uses the JSTypeRegistry to resolve types and validate member access.
|
||||
*/
|
||||
public class JSScriptAnalyzer {
|
||||
|
||||
private final String text;
|
||||
private final JSTypeRegistry registry;
|
||||
|
||||
// Variable tracking: varName -> inferred type name
|
||||
private final Map<String, String> variableTypes = new HashMap<>();
|
||||
|
||||
// Function parameter types: funcName -> paramName -> typeName
|
||||
private final Map<String, Map<String, String>> functionParams = new HashMap<>();
|
||||
|
||||
// Excluded ranges (strings, comments)
|
||||
private final List<int[]> excludedRanges = new ArrayList<>();
|
||||
|
||||
// Patterns
|
||||
private static final Pattern STRING_PATTERN = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'");
|
||||
private static final Pattern COMMENT_PATTERN = Pattern.compile("//.*?$|/\\*.*?\\*/", Pattern.MULTILINE | Pattern.DOTALL);
|
||||
private static final Pattern FUNCTION_PATTERN = Pattern.compile("function\\s+(\\w+)\\s*\\(([^)]*)\\)");
|
||||
private static final Pattern VAR_DECL_PATTERN = Pattern.compile("(?:var|let|const)\\s+(\\w+)(?:\\s*=\\s*([^;]+))?");
|
||||
private static final Pattern ASSIGNMENT_PATTERN = Pattern.compile("(\\w+)\\s*=\\s*([^;]+)");
|
||||
private static final Pattern METHOD_CALL_PATTERN = Pattern.compile("(\\w+(?:\\.\\w+)*)\\s*\\(");
|
||||
private static final Pattern MEMBER_ACCESS_PATTERN = Pattern.compile("(\\w+)(?:\\.(\\w+))+");
|
||||
private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b");
|
||||
|
||||
private static final Pattern JS_KEYWORD_PATTERN = Pattern.compile(
|
||||
"\\b(function|var|let|const|if|else|for|while|do|switch|case|break|continue|return|" +
|
||||
"try|catch|finally|throw|new|typeof|instanceof|in|of|this|null|undefined|true|false|" +
|
||||
"class|extends|import|export|default|async|await|yield)\\b");
|
||||
|
||||
private static final Pattern NUMBER_PATTERN = Pattern.compile("\\b\\d+\\.?\\d*\\b");
|
||||
|
||||
public JSScriptAnalyzer(String text) {
|
||||
this.text = text;
|
||||
this.registry = JSTypeRegistry.getInstance();
|
||||
// Ensure registry is initialized
|
||||
if (!registry.isInitialized()) {
|
||||
registry.initializeFromResources();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze the script and produce marks.
|
||||
*/
|
||||
public List<ScriptLine.Mark> analyze() {
|
||||
List<ScriptLine.Mark> marks = new ArrayList<>();
|
||||
|
||||
// First pass: find excluded regions
|
||||
findExcludedRanges();
|
||||
|
||||
// Mark comments and strings
|
||||
addPatternMarks(marks, COMMENT_PATTERN, TokenType.COMMENT);
|
||||
addPatternMarks(marks, STRING_PATTERN, TokenType.STRING);
|
||||
|
||||
// Mark keywords
|
||||
addPatternMarks(marks, JS_KEYWORD_PATTERN, TokenType.KEYWORD);
|
||||
|
||||
// Mark numbers
|
||||
addPatternMarks(marks, NUMBER_PATTERN, TokenType.LITERAL);
|
||||
|
||||
// Parse functions and infer parameter types from hooks
|
||||
parseFunctions(marks);
|
||||
|
||||
// Parse variable declarations
|
||||
parseVariables(marks);
|
||||
|
||||
// Mark member accesses with type validation
|
||||
markMemberAccesses(marks);
|
||||
|
||||
// Mark method calls
|
||||
markMethodCalls(marks);
|
||||
|
||||
return marks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find strings and comments to exclude from analysis.
|
||||
*/
|
||||
private void findExcludedRanges() {
|
||||
Matcher m = STRING_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
excludedRanges.add(new int[]{m.start(), m.end()});
|
||||
}
|
||||
|
||||
m = COMMENT_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
excludedRanges.add(new int[]{m.start(), m.end()});
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isExcluded(int pos) {
|
||||
for (int[] range : excludedRanges) {
|
||||
if (pos >= range[0] && pos < range[1]) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse function declarations and infer parameter types from hook signatures.
|
||||
*/
|
||||
private void parseFunctions(List<ScriptLine.Mark> marks) {
|
||||
Matcher m = FUNCTION_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
if (isExcluded(m.start())) continue;
|
||||
|
||||
String funcName = m.group(1);
|
||||
String params = m.group(2);
|
||||
|
||||
// Mark function name
|
||||
int nameStart = m.start(1);
|
||||
int nameEnd = m.end(1);
|
||||
|
||||
// Check if this is a known hook
|
||||
if (registry.isHook(funcName)) {
|
||||
marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_DECL,
|
||||
new JSHoverInfo.FunctionInfo(funcName, registry.getHookSignatures(funcName))));
|
||||
|
||||
// Infer parameter types from hook
|
||||
List<JSTypeRegistry.HookSignature> sigs = registry.getHookSignatures(funcName);
|
||||
if (!sigs.isEmpty() && !params.isEmpty()) {
|
||||
// Parse parameter names from function
|
||||
String[] paramNames = params.split(",");
|
||||
if (paramNames.length > 0) {
|
||||
String paramName = paramNames[0].trim();
|
||||
// Use first hook signature's type
|
||||
String paramType = sigs.get(0).paramType;
|
||||
|
||||
// Store in function params and variable types
|
||||
Map<String, String> funcParamMap = new HashMap<>();
|
||||
funcParamMap.put(paramName, paramType);
|
||||
functionParams.put(funcName, funcParamMap);
|
||||
variableTypes.put(paramName, paramType);
|
||||
|
||||
// Mark the parameter
|
||||
int paramStart = m.start(2) + params.indexOf(paramName);
|
||||
int paramEnd = paramStart + paramName.length();
|
||||
JSTypeInfo typeInfo = registry.getType(paramType);
|
||||
marks.add(new ScriptLine.Mark(paramStart, paramEnd, TokenType.PARAMETER,
|
||||
new JSHoverInfo.VariableInfo(paramName, paramType, typeInfo)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_DECL, funcName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse variable declarations and infer types.
|
||||
*/
|
||||
private void parseVariables(List<ScriptLine.Mark> marks) {
|
||||
Matcher m = VAR_DECL_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
if (isExcluded(m.start())) continue;
|
||||
|
||||
String varName = m.group(1);
|
||||
String initializer = m.group(2);
|
||||
|
||||
// Infer type from initializer
|
||||
String inferredType = null;
|
||||
if (initializer != null) {
|
||||
inferredType = inferTypeFromExpression(initializer.trim());
|
||||
}
|
||||
|
||||
if (inferredType != null) {
|
||||
variableTypes.put(varName, inferredType);
|
||||
}
|
||||
|
||||
// Mark variable declaration
|
||||
int varStart = m.start(1);
|
||||
int varEnd = m.end(1);
|
||||
JSTypeInfo typeInfo = inferredType != null ? registry.getType(inferredType) : null;
|
||||
marks.add(new ScriptLine.Mark(varStart, varEnd, TokenType.LOCAL_FIELD,
|
||||
new JSHoverInfo.VariableInfo(varName, inferredType != null ? inferredType : "any", typeInfo)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer type from an expression.
|
||||
*/
|
||||
private String inferTypeFromExpression(String expr) {
|
||||
if (expr == null || expr.isEmpty()) return null;
|
||||
|
||||
// String literal
|
||||
if (expr.startsWith("\"") || expr.startsWith("'")) {
|
||||
return "string";
|
||||
}
|
||||
|
||||
// Number literal
|
||||
if (expr.matches("\\d+\\.?\\d*")) {
|
||||
return "number";
|
||||
}
|
||||
|
||||
// Boolean literal
|
||||
if (expr.equals("true") || expr.equals("false")) {
|
||||
return "boolean";
|
||||
}
|
||||
|
||||
// null/undefined
|
||||
if (expr.equals("null")) return "null";
|
||||
if (expr.equals("undefined")) return "undefined";
|
||||
|
||||
// Array literal
|
||||
if (expr.startsWith("[")) {
|
||||
return "any[]";
|
||||
}
|
||||
|
||||
// Object literal
|
||||
if (expr.startsWith("{")) {
|
||||
return "object";
|
||||
}
|
||||
|
||||
// Method call: something.method() - infer from method return type
|
||||
if (expr.contains(".") && expr.contains("(")) {
|
||||
return inferTypeFromMethodCall(expr);
|
||||
}
|
||||
|
||||
// Variable reference
|
||||
if (variableTypes.containsKey(expr)) {
|
||||
return variableTypes.get(expr);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer type from a method call chain.
|
||||
*/
|
||||
private String inferTypeFromMethodCall(String expr) {
|
||||
// Remove trailing parentheses and args for analysis
|
||||
int parenIndex = expr.indexOf('(');
|
||||
if (parenIndex > 0) {
|
||||
expr = expr.substring(0, parenIndex);
|
||||
}
|
||||
|
||||
String[] parts = expr.split("\\.");
|
||||
if (parts.length < 2) return null;
|
||||
|
||||
// Start with the receiver type
|
||||
String currentType = variableTypes.get(parts[0]);
|
||||
if (currentType == null) return null;
|
||||
|
||||
// Walk the chain
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
JSTypeInfo typeInfo = registry.getType(currentType);
|
||||
if (typeInfo == null) return null;
|
||||
|
||||
String member = parts[i];
|
||||
|
||||
// Check if it's a method
|
||||
JSMethodInfo method = typeInfo.getMethod(member);
|
||||
if (method != null) {
|
||||
currentType = method.getReturnType();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if it's a field
|
||||
JSFieldInfo field = typeInfo.getField(member);
|
||||
if (field != null) {
|
||||
currentType = field.getType();
|
||||
continue;
|
||||
}
|
||||
|
||||
return null; // Unknown member
|
||||
}
|
||||
|
||||
return currentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark member accesses (x.y.z) with type validation.
|
||||
*/
|
||||
private void markMemberAccesses(List<ScriptLine.Mark> marks) {
|
||||
Matcher m = MEMBER_ACCESS_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
if (isExcluded(m.start())) continue;
|
||||
|
||||
String fullAccess = m.group(0);
|
||||
String[] parts = fullAccess.split("\\.");
|
||||
|
||||
if (parts.length < 2) continue;
|
||||
|
||||
// Get receiver type
|
||||
String receiverName = parts[0];
|
||||
String currentType = variableTypes.get(receiverName);
|
||||
|
||||
int pos = m.start();
|
||||
|
||||
// Mark receiver
|
||||
if (currentType != null) {
|
||||
JSTypeInfo typeInfo = registry.getType(currentType);
|
||||
marks.add(new ScriptLine.Mark(pos, pos + receiverName.length(), TokenType.LOCAL_FIELD,
|
||||
new JSHoverInfo.VariableInfo(receiverName, currentType, typeInfo)));
|
||||
}
|
||||
|
||||
pos += receiverName.length() + 1; // +1 for the dot
|
||||
|
||||
// Walk the chain and mark each member
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
String member = parts[i];
|
||||
int memberStart = pos;
|
||||
int memberEnd = pos + member.length();
|
||||
|
||||
if (currentType != null) {
|
||||
JSTypeInfo typeInfo = registry.getType(currentType);
|
||||
if (typeInfo != null) {
|
||||
// Check method first
|
||||
JSMethodInfo method = typeInfo.getMethod(member);
|
||||
if (method != null) {
|
||||
marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.METHOD_CALL,
|
||||
new JSHoverInfo.MethodInfo(method, typeInfo)));
|
||||
currentType = method.getReturnType();
|
||||
} else {
|
||||
// Check field
|
||||
JSFieldInfo field = typeInfo.getField(member);
|
||||
if (field != null) {
|
||||
marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.GLOBAL_FIELD,
|
||||
new JSHoverInfo.FieldInfo(field, typeInfo)));
|
||||
currentType = field.getType();
|
||||
} else {
|
||||
// Unknown member - mark as undefined
|
||||
marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.UNDEFINED_VAR,
|
||||
"Unknown member '" + member + "' on type " + typeInfo.getFullName()));
|
||||
currentType = null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
currentType = null;
|
||||
}
|
||||
}
|
||||
|
||||
pos = memberEnd + 1; // +1 for the next dot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark method calls.
|
||||
*/
|
||||
private void markMethodCalls(List<ScriptLine.Mark> marks) {
|
||||
Matcher m = METHOD_CALL_PATTERN.matcher(text);
|
||||
while (m.find()) {
|
||||
if (isExcluded(m.start())) continue;
|
||||
|
||||
String callExpr = m.group(1);
|
||||
if (!callExpr.contains(".")) {
|
||||
// Simple function call
|
||||
int nameStart = m.start(1);
|
||||
int nameEnd = m.end(1);
|
||||
|
||||
if (registry.isHook(callExpr)) {
|
||||
// It's a known hook being called
|
||||
marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL,
|
||||
new JSHoverInfo.FunctionInfo(callExpr, registry.getHookSignatures(callExpr))));
|
||||
}
|
||||
}
|
||||
// Chained calls are handled in markMemberAccesses
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add pattern-based marks.
|
||||
*/
|
||||
private void addPatternMarks(List<ScriptLine.Mark> marks, Pattern pattern, TokenType type) {
|
||||
Matcher m = pattern.matcher(text);
|
||||
while (m.find()) {
|
||||
marks.add(new ScriptLine.Mark(m.start(), m.end(), type));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the inferred type of a variable at a position.
|
||||
*/
|
||||
public String getVariableType(String varName) {
|
||||
return variableTypes.get(varName);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Represents a TypeScript interface/type parsed from .d.ts files.
|
||||
* This is the JS equivalent of TypeInfo for Java types.
|
||||
*/
|
||||
public class JSTypeInfo {
|
||||
|
||||
private final String simpleName; // e.g., "InteractEvent"
|
||||
private final String fullName; // e.g., "IPlayerEvent.InteractEvent"
|
||||
private final String namespace; // e.g., "IPlayerEvent" (parent namespace, null for top-level)
|
||||
|
||||
// Members
|
||||
private final Map<String, JSMethodInfo> methods = new LinkedHashMap<>();
|
||||
private final Map<String, JSFieldInfo> fields = new LinkedHashMap<>();
|
||||
|
||||
// Inheritance
|
||||
private String extendsType; // The type this interface extends
|
||||
private JSTypeInfo resolvedParent; // Resolved parent type (after registry is built)
|
||||
|
||||
// Inner types (for namespaces)
|
||||
private final Map<String, JSTypeInfo> innerTypes = new LinkedHashMap<>();
|
||||
private JSTypeInfo parentType; // The containing type (for inner types)
|
||||
|
||||
// Documentation
|
||||
private String documentation;
|
||||
|
||||
public JSTypeInfo(String simpleName, String namespace) {
|
||||
this.simpleName = simpleName;
|
||||
this.namespace = namespace;
|
||||
this.fullName = namespace != null ? namespace + "." + simpleName : simpleName;
|
||||
}
|
||||
|
||||
// Builder methods
|
||||
public JSTypeInfo setExtends(String extendsType) {
|
||||
this.extendsType = extendsType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSTypeInfo setDocumentation(String documentation) {
|
||||
this.documentation = documentation;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void addMethod(JSMethodInfo method) {
|
||||
// Handle overloads - store with index if name already exists
|
||||
String key = method.getName();
|
||||
if (methods.containsKey(key)) {
|
||||
// Find next available key for overload
|
||||
int index = 1;
|
||||
while (methods.containsKey(key + "$" + index)) {
|
||||
index++;
|
||||
}
|
||||
methods.put(key + "$" + index, method);
|
||||
} else {
|
||||
methods.put(key, method);
|
||||
}
|
||||
}
|
||||
|
||||
public void addField(JSFieldInfo field) {
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
public void addInnerType(JSTypeInfo inner) {
|
||||
inner.parentType = this;
|
||||
innerTypes.put(inner.getSimpleName(), inner);
|
||||
}
|
||||
|
||||
public void setResolvedParent(JSTypeInfo parent) {
|
||||
this.resolvedParent = parent;
|
||||
}
|
||||
|
||||
// Getters
|
||||
public String getSimpleName() { return simpleName; }
|
||||
public String getFullName() { return fullName; }
|
||||
public String getNamespace() { return namespace; }
|
||||
public String getExtendsType() { return extendsType; }
|
||||
public JSTypeInfo getResolvedParent() { return resolvedParent; }
|
||||
public String getDocumentation() { return documentation; }
|
||||
public JSTypeInfo getParentType() { return parentType; }
|
||||
|
||||
public Map<String, JSMethodInfo> getMethods() { return methods; }
|
||||
public Map<String, JSFieldInfo> getFields() { return fields; }
|
||||
public Map<String, JSTypeInfo> getInnerTypes() { return innerTypes; }
|
||||
|
||||
/**
|
||||
* Get a method by name, including inherited methods.
|
||||
*/
|
||||
public JSMethodInfo getMethod(String name) {
|
||||
JSMethodInfo method = methods.get(name);
|
||||
if (method != null) return method;
|
||||
|
||||
// Check parent
|
||||
if (resolvedParent != null) {
|
||||
return resolvedParent.getMethod(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all methods with a given name (for overloads).
|
||||
*/
|
||||
public List<JSMethodInfo> getMethodOverloads(String name) {
|
||||
List<JSMethodInfo> overloads = new ArrayList<>();
|
||||
|
||||
// Get from this type
|
||||
if (methods.containsKey(name)) {
|
||||
overloads.add(methods.get(name));
|
||||
}
|
||||
// Get numbered overloads
|
||||
int index = 1;
|
||||
while (methods.containsKey(name + "$" + index)) {
|
||||
overloads.add(methods.get(name + "$" + index));
|
||||
index++;
|
||||
}
|
||||
|
||||
// Get from parent
|
||||
if (resolvedParent != null) {
|
||||
overloads.addAll(resolvedParent.getMethodOverloads(name));
|
||||
}
|
||||
|
||||
return overloads;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this type has a method (including inherited).
|
||||
*/
|
||||
public boolean hasMethod(String name) {
|
||||
return getMethod(name) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a field by name, including inherited fields.
|
||||
*/
|
||||
public JSFieldInfo getField(String name) {
|
||||
JSFieldInfo field = fields.get(name);
|
||||
if (field != null) return field;
|
||||
|
||||
// Check parent
|
||||
if (resolvedParent != null) {
|
||||
return resolvedParent.getField(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this type has a field (including inherited).
|
||||
*/
|
||||
public boolean hasField(String name) {
|
||||
return getField(name) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an inner type by name.
|
||||
*/
|
||||
public JSTypeInfo getInnerType(String name) {
|
||||
return innerTypes.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JSTypeInfo{" + fullName + "}";
|
||||
}
|
||||
}
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Central registry for all TypeScript types parsed from .d.ts files.
|
||||
* Also manages hook function signatures and type aliases.
|
||||
*/
|
||||
public class JSTypeRegistry {
|
||||
|
||||
private static JSTypeRegistry INSTANCE;
|
||||
|
||||
// Resource location for the API definitions
|
||||
private static final String API_RESOURCE_PATH = "customnpcs:api/";
|
||||
|
||||
// All registered types by full name (e.g., "IPlayerEvent.InteractEvent")
|
||||
private final Map<String, JSTypeInfo> types = new LinkedHashMap<>();
|
||||
|
||||
// Type aliases (simple name -> full type name)
|
||||
private final Map<String, String> typeAliases = new HashMap<>();
|
||||
|
||||
// Hook function signatures: functionName -> list of (paramName, paramType) pairs
|
||||
// Multiple entries for overloaded hooks
|
||||
private final Map<String, List<HookSignature>> hooks = new LinkedHashMap<>();
|
||||
|
||||
// Primitive types
|
||||
private static final Set<String> PRIMITIVES = new HashSet<>(Arrays.asList(
|
||||
"number", "string", "boolean", "void", "any", "null", "undefined", "never", "object"
|
||||
));
|
||||
|
||||
private boolean initialized = false;
|
||||
private boolean initializationAttempted = false;
|
||||
|
||||
public static JSTypeRegistry getInstance() {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = new JSTypeRegistry();
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private JSTypeRegistry() {}
|
||||
|
||||
/**
|
||||
* Initialize the registry from the embedded resources.
|
||||
* This loads .d.ts files from assets/customnpcs/api/
|
||||
*/
|
||||
public void initializeFromResources() {
|
||||
if (initialized || initializationAttempted) return;
|
||||
initializationAttempted = true;
|
||||
|
||||
try {
|
||||
TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this);
|
||||
|
||||
// Load hooks.d.ts first (defines function parameter types)
|
||||
loadResourceFile(parser, "hooks.d.ts");
|
||||
|
||||
// Load index.d.ts (type aliases)
|
||||
loadResourceFile(parser, "index.d.ts");
|
||||
|
||||
// Load main API files
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/entity/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/event/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/handler/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/item/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/block/");
|
||||
loadResourceDirectory(parser, "noppes/npcs/api/gui/");
|
||||
|
||||
resolveInheritance();
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from resources");
|
||||
} catch (Exception e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load type definitions from resources: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a specific .d.ts file from resources.
|
||||
*/
|
||||
private void loadResourceFile(TypeScriptDefinitionParser parser, String fileName) {
|
||||
try {
|
||||
ResourceLocation loc = new ResourceLocation("customnpcs", "api/" + fileName);
|
||||
InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream();
|
||||
if (is != null) {
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line).append("\n");
|
||||
}
|
||||
parser.parseDefinitionFile(sb.toString(), fileName);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// File might not exist, that's ok
|
||||
System.out.println("[JSTypeRegistry] Could not load " + fileName + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all .d.ts files from a resource directory.
|
||||
*/
|
||||
private void loadResourceDirectory(TypeScriptDefinitionParser parser, String dirPath) {
|
||||
// In Minecraft resources, we can't list directory contents directly
|
||||
// So we'll try to load known files from a manifest or just try common patterns
|
||||
// For now, let's try loading specific known files
|
||||
String[] knownFiles = getKnownFilesForDirectory(dirPath);
|
||||
for (String file : knownFiles) {
|
||||
loadResourceFile(parser, dirPath + file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of known .d.ts files for a directory.
|
||||
* This is a workaround since we can't list resource directories.
|
||||
*/
|
||||
private String[] getKnownFilesForDirectory(String dirPath) {
|
||||
// These are the known API files based on the actual file structure
|
||||
if (dirPath.endsWith("noppes/npcs/api/")) {
|
||||
return new String[]{
|
||||
"AbstractNpcAPI.d.ts", "IBlock.d.ts", "ICommand.d.ts", "IContainer.d.ts",
|
||||
"IDamageSource.d.ts", "INbt.d.ts", "IParticle.d.ts", "IPixelmonPlayerData.d.ts",
|
||||
"IPos.d.ts", "IScreenSize.d.ts", "ISkinOverlay.d.ts", "ITileEntity.d.ts",
|
||||
"ITimers.d.ts", "IWorld.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("entity/")) {
|
||||
return new String[]{
|
||||
"ICustomNpc.d.ts", "IEntity.d.ts", "IEntityItem.d.ts", "IEntityLiving.d.ts",
|
||||
"IEntityLivingBase.d.ts", "IPlayer.d.ts", "IProjectile.d.ts", "IAnimal.d.ts",
|
||||
"IAnimatable.d.ts", "IArrow.d.ts", "IDBCPlayer.d.ts", "IFishHook.d.ts",
|
||||
"IMonster.d.ts", "IPixelmon.d.ts", "IThrowable.d.ts", "IVillager.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("event/")) {
|
||||
return new String[]{
|
||||
"INpcEvent.d.ts", "IPlayerEvent.d.ts", "IItemEvent.d.ts", "IBlockEvent.d.ts",
|
||||
"IDialogEvent.d.ts", "IQuestEvent.d.ts", "ICustomGuiEvent.d.ts",
|
||||
"IAnimationEvent.d.ts", "ICustomNPCsEvent.d.ts", "IFactionEvent.d.ts",
|
||||
"IForgeEvent.d.ts", "ILinkedItemEvent.d.ts", "IPartyEvent.d.ts",
|
||||
"IProjectileEvent.d.ts", "IRecipeEvent.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("handler/")) {
|
||||
return new String[]{
|
||||
"ICloneHandler.d.ts", "IDialogHandler.d.ts", "IFactionHandler.d.ts",
|
||||
"IQuestHandler.d.ts", "IRecipeHandler.d.ts", "ITagHandler.d.ts",
|
||||
"IAnimationHandler.d.ts", "IActionManager.d.ts", "IAttributeHandler.d.ts",
|
||||
"ICustomEffectHandler.d.ts", "IMagicHandler.d.ts", "INaturalSpawnsHandler.d.ts",
|
||||
"IOverlayHandler.d.ts", "IPartyHandler.d.ts", "IPlayerBankData.d.ts",
|
||||
"IPlayerData.d.ts", "IPlayerDialogData.d.ts", "IPlayerFactionData.d.ts",
|
||||
"IPlayerItemGiverData.d.ts", "IPlayerMailData.d.ts", "IPlayerQuestData.d.ts",
|
||||
"IPlayerTransportData.d.ts", "IProfileHandler.d.ts", "ITransportHandler.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("item/")) {
|
||||
return new String[]{
|
||||
"IItemStack.d.ts", "IItemArmor.d.ts", "IItemBook.d.ts", "IItemBlock.d.ts",
|
||||
"IItemCustom.d.ts", "IItemCustomizable.d.ts", "IItemLinked.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("block/")) {
|
||||
return new String[]{
|
||||
"IBlockScripted.d.ts", "ITextPlane.d.ts"
|
||||
};
|
||||
} else if (dirPath.endsWith("gui/")) {
|
||||
return new String[]{
|
||||
"IButton.d.ts", "ICustomGui.d.ts", "ILabel.d.ts", "ITextField.d.ts",
|
||||
"ITexturedRect.d.ts", "IScroll.d.ts", "IItemSlot.d.ts", "ICustomGuiComponent.d.ts",
|
||||
"ILine.d.ts"
|
||||
};
|
||||
}
|
||||
return new String[]{};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the registry from a directory containing .d.ts files.
|
||||
*/
|
||||
public void initializeFromDirectory(File directory) {
|
||||
if (initialized) return;
|
||||
|
||||
try {
|
||||
TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this);
|
||||
parser.parseDirectory(directory);
|
||||
resolveInheritance();
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks");
|
||||
} catch (IOException e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load type definitions: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the registry from a VSIX file.
|
||||
*/
|
||||
public void initializeFromVsix(File vsixFile) {
|
||||
if (initialized) return;
|
||||
|
||||
try {
|
||||
TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this);
|
||||
parser.parseVsixArchive(vsixFile);
|
||||
resolveInheritance();
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from VSIX");
|
||||
} catch (IOException e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load VSIX: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a type.
|
||||
*/
|
||||
public void registerType(JSTypeInfo type) {
|
||||
types.put(type.getFullName(), type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a type alias.
|
||||
*/
|
||||
public void registerTypeAlias(String alias, String fullType) {
|
||||
typeAliases.put(alias, fullType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a hook function signature.
|
||||
*/
|
||||
public void registerHook(String functionName, String paramName, String paramType) {
|
||||
hooks.computeIfAbsent(functionName, k -> new ArrayList<>())
|
||||
.add(new HookSignature(paramName, paramType));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a type by name (handles aliases and primitives).
|
||||
*/
|
||||
public JSTypeInfo getType(String name) {
|
||||
return getType(name, new HashSet<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method with cycle detection for type aliases.
|
||||
*/
|
||||
private JSTypeInfo getType(String name, Set<String> visited) {
|
||||
if (name == null || name.isEmpty()) return null;
|
||||
|
||||
// Strip array brackets for lookup
|
||||
String baseName = name.replace("[]", "").trim();
|
||||
|
||||
// Check if primitive
|
||||
if (PRIMITIVES.contains(baseName)) {
|
||||
return null; // Primitives don't have JSTypeInfo
|
||||
}
|
||||
|
||||
// Detect circular alias references
|
||||
if (visited.contains(baseName)) {
|
||||
System.err.println("[JSTypeRegistry] Circular type alias detected: " + baseName);
|
||||
return null;
|
||||
}
|
||||
visited.add(baseName);
|
||||
|
||||
// Direct lookup
|
||||
if (types.containsKey(baseName)) {
|
||||
return types.get(baseName);
|
||||
}
|
||||
|
||||
// Check type aliases
|
||||
if (typeAliases.containsKey(baseName)) {
|
||||
String resolved = typeAliases.get(baseName);
|
||||
return getType(resolved, visited);
|
||||
}
|
||||
|
||||
// Try simple name lookup (for types like "IEntity" without namespace)
|
||||
for (JSTypeInfo type : types.values()) {
|
||||
if (type.getSimpleName().equals(baseName)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a type name is a known primitive.
|
||||
*/
|
||||
public boolean isPrimitive(String typeName) {
|
||||
return PRIMITIVES.contains(typeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get hook signatures for a function name.
|
||||
*/
|
||||
public List<HookSignature> getHookSignatures(String functionName) {
|
||||
return hooks.getOrDefault(functionName, Collections.emptyList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a function name is a known hook.
|
||||
*/
|
||||
public boolean isHook(String functionName) {
|
||||
return hooks.containsKey(functionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the parameter type for a hook function.
|
||||
* If multiple overloads exist, returns the first one.
|
||||
*/
|
||||
public String getHookParameterType(String functionName) {
|
||||
List<HookSignature> sigs = hooks.get(functionName);
|
||||
if (sigs != null && !sigs.isEmpty()) {
|
||||
return sigs.get(0).paramType;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve inheritance relationships between types.
|
||||
*/
|
||||
private void resolveInheritance() {
|
||||
for (JSTypeInfo type : types.values()) {
|
||||
String extendsType = type.getExtendsType();
|
||||
if (extendsType != null) {
|
||||
JSTypeInfo parent = getType(extendsType);
|
||||
if (parent != null) {
|
||||
type.setResolvedParent(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered types.
|
||||
*/
|
||||
public Collection<JSTypeInfo> getAllTypes() {
|
||||
return types.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered hooks.
|
||||
*/
|
||||
public Map<String, List<HookSignature>> getAllHooks() {
|
||||
return hooks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if initialized.
|
||||
*/
|
||||
public boolean isInitialized() {
|
||||
return initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the registry (for reloading).
|
||||
*/
|
||||
public void clear() {
|
||||
types.clear();
|
||||
typeAliases.clear();
|
||||
hooks.clear();
|
||||
initialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a hook function signature.
|
||||
*/
|
||||
public static class HookSignature {
|
||||
public final String paramName;
|
||||
public final String paramType;
|
||||
|
||||
public HookSignature(String paramName, String paramType) {
|
||||
this.paramName = paramName;
|
||||
this.paramType = paramType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return paramName + ": " + paramType;
|
||||
}
|
||||
}
|
||||
}
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
/**
|
||||
* Parses TypeScript definition files (.d.ts) to extract type information.
|
||||
* Can read from individual files, directories, or .vsix archives.
|
||||
*/
|
||||
public class TypeScriptDefinitionParser {
|
||||
|
||||
// Patterns for parsing .d.ts content
|
||||
private static final Pattern INTERFACE_PATTERN = Pattern.compile(
|
||||
"export\\s+interface\\s+(\\w+)(?:\\s+extends\\s+([\\w.]+))?\\s*\\{");
|
||||
|
||||
private static final Pattern NAMESPACE_PATTERN = Pattern.compile(
|
||||
"export\\s+namespace\\s+(\\w+)\\s*\\{");
|
||||
|
||||
private static final Pattern TYPE_ALIAS_PATTERN = Pattern.compile(
|
||||
"export\\s+type\\s+(\\w+)\\s*=\\s*([^;]+);");
|
||||
|
||||
private static final Pattern METHOD_PATTERN = Pattern.compile(
|
||||
"^\\s*(\\w+)\\s*\\(([^)]*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
|
||||
|
||||
private static final Pattern FIELD_PATTERN = Pattern.compile(
|
||||
"^\\s*(readonly\\s+)?(\\w+)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
|
||||
|
||||
private static final Pattern GLOBAL_FUNCTION_PATTERN = Pattern.compile(
|
||||
"function\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*:\\s*([^;]+);");
|
||||
|
||||
private static final Pattern GLOBAL_TYPE_ALIAS_PATTERN = Pattern.compile(
|
||||
"type\\s+(\\w+)\\s*=\\s*import\\(['\"]([^'\"]+)['\"]\\)\\.([\\w.]+);");
|
||||
|
||||
private final JSTypeRegistry registry;
|
||||
|
||||
public TypeScriptDefinitionParser(JSTypeRegistry registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse all .d.ts files from a VSIX archive.
|
||||
*/
|
||||
public void parseVsixArchive(File vsixFile) throws IOException {
|
||||
try (ZipFile zip = new ZipFile(vsixFile)) {
|
||||
Enumeration<? extends ZipEntry> entries = zip.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (entry.getName().endsWith(".d.ts")) {
|
||||
try (InputStream is = zip.getInputStream(entry);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
|
||||
String content = readFully(reader);
|
||||
String fileName = entry.getName();
|
||||
parseDefinitionFile(content, fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse all .d.ts files from a directory recursively.
|
||||
*/
|
||||
public void parseDirectory(File directory) throws IOException {
|
||||
if (!directory.isDirectory()) {
|
||||
throw new IllegalArgumentException("Not a directory: " + directory);
|
||||
}
|
||||
parseDirectoryRecursive(directory);
|
||||
}
|
||||
|
||||
private void parseDirectoryRecursive(File dir) throws IOException {
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) return;
|
||||
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
parseDirectoryRecursive(file);
|
||||
} else if (file.getName().endsWith(".d.ts")) {
|
||||
parseFile(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a single .d.ts file.
|
||||
*/
|
||||
public void parseFile(File file) throws IOException {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String content = readFully(reader);
|
||||
parseDefinitionFile(content, file.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a .d.ts file content.
|
||||
*/
|
||||
public void parseDefinitionFile(String content, String fileName) {
|
||||
// Special handling for hooks.d.ts - extract function signatures
|
||||
if (fileName.contains("hooks.d.ts")) {
|
||||
parseHooksFile(content);
|
||||
return;
|
||||
}
|
||||
|
||||
// Special handling for index.d.ts - extract global type aliases
|
||||
if (fileName.contains("index.d.ts")) {
|
||||
parseIndexFile(content);
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse regular interface files
|
||||
parseInterfaceFile(content, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse hooks.d.ts to extract function signatures for JS hooks.
|
||||
*/
|
||||
private void parseHooksFile(String content) {
|
||||
Matcher m = GLOBAL_FUNCTION_PATTERN.matcher(content);
|
||||
while (m.find()) {
|
||||
String funcName = m.group(1);
|
||||
String params = m.group(2);
|
||||
String returnType = m.group(3).trim();
|
||||
|
||||
// Parse parameter - format is "paramName: TypeName"
|
||||
if (!params.isEmpty()) {
|
||||
String[] parts = params.split(":\\s*", 2);
|
||||
if (parts.length == 2) {
|
||||
String paramName = parts[0].trim();
|
||||
String paramType = parts[1].trim();
|
||||
registry.registerHook(funcName, paramName, paramType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse index.d.ts to extract global type aliases.
|
||||
*/
|
||||
private void parseIndexFile(String content) {
|
||||
Matcher m = GLOBAL_TYPE_ALIAS_PATTERN.matcher(content);
|
||||
while (m.find()) {
|
||||
String aliasName = m.group(1);
|
||||
String importPath = m.group(2);
|
||||
String typeName = m.group(3);
|
||||
registry.registerTypeAlias(aliasName, typeName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse interface definitions from content.
|
||||
*/
|
||||
private void parseInterfaceFile(String content, String parentNamespace) {
|
||||
// Find interfaces
|
||||
Matcher interfaceMatcher = INTERFACE_PATTERN.matcher(content);
|
||||
while (interfaceMatcher.find()) {
|
||||
String interfaceName = interfaceMatcher.group(1);
|
||||
String extendsType = interfaceMatcher.group(2);
|
||||
|
||||
JSTypeInfo typeInfo = new JSTypeInfo(interfaceName, parentNamespace);
|
||||
if (extendsType != null) {
|
||||
typeInfo.setExtends(extendsType);
|
||||
}
|
||||
|
||||
// Find the body of this interface
|
||||
int bodyStart = interfaceMatcher.end();
|
||||
int bodyEnd = findMatchingBrace(content, bodyStart - 1);
|
||||
if (bodyEnd > bodyStart) {
|
||||
String body = content.substring(bodyStart, bodyEnd);
|
||||
parseInterfaceBody(body, typeInfo);
|
||||
}
|
||||
|
||||
registry.registerType(typeInfo);
|
||||
}
|
||||
|
||||
// Find namespaces (which contain inner types)
|
||||
Matcher namespaceMatcher = NAMESPACE_PATTERN.matcher(content);
|
||||
while (namespaceMatcher.find()) {
|
||||
String namespaceName = namespaceMatcher.group(1);
|
||||
|
||||
// Find the body of this namespace
|
||||
int bodyStart = namespaceMatcher.end();
|
||||
int bodyEnd = findMatchingBrace(content, bodyStart - 1);
|
||||
if (bodyEnd > bodyStart) {
|
||||
String body = content.substring(bodyStart, bodyEnd);
|
||||
|
||||
// Recursively parse inner types with namespace prefix
|
||||
String fullNamespace = parentNamespace != null ?
|
||||
parentNamespace + "." + namespaceName : namespaceName;
|
||||
parseInterfaceFile(body, fullNamespace);
|
||||
|
||||
// Also handle type aliases within namespace
|
||||
parseTypeAliases(body, fullNamespace);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle top-level type aliases
|
||||
if (parentNamespace == null) {
|
||||
parseTypeAliases(content, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse type aliases (export type X = Y).
|
||||
*/
|
||||
private void parseTypeAliases(String content, String namespace) {
|
||||
Matcher m = TYPE_ALIAS_PATTERN.matcher(content);
|
||||
while (m.find()) {
|
||||
String aliasName = m.group(1);
|
||||
String targetType = m.group(2).trim();
|
||||
|
||||
// Create a simple type that extends the target
|
||||
JSTypeInfo typeInfo = new JSTypeInfo(aliasName, namespace);
|
||||
typeInfo.setExtends(targetType);
|
||||
registry.registerType(typeInfo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the body of an interface to extract methods and fields.
|
||||
*/
|
||||
private void parseInterfaceBody(String body, JSTypeInfo typeInfo) {
|
||||
// Parse methods
|
||||
Matcher methodMatcher = METHOD_PATTERN.matcher(body);
|
||||
while (methodMatcher.find()) {
|
||||
String methodName = methodMatcher.group(1);
|
||||
String params = methodMatcher.group(2);
|
||||
String returnType = cleanType(methodMatcher.group(3));
|
||||
|
||||
List<JSMethodInfo.JSParameterInfo> parameters = parseParameters(params);
|
||||
JSMethodInfo method = new JSMethodInfo(methodName, returnType, parameters);
|
||||
typeInfo.addMethod(method);
|
||||
}
|
||||
|
||||
// Parse fields (that aren't method signatures)
|
||||
Matcher fieldMatcher = FIELD_PATTERN.matcher(body);
|
||||
while (fieldMatcher.find()) {
|
||||
String fieldText = fieldMatcher.group(0);
|
||||
// Skip if this looks like a method (has parentheses in the match)
|
||||
if (fieldText.contains("(")) continue;
|
||||
|
||||
boolean readonly = fieldMatcher.group(1) != null;
|
||||
String fieldName = fieldMatcher.group(2);
|
||||
String fieldType = cleanType(fieldMatcher.group(3));
|
||||
|
||||
JSFieldInfo field = new JSFieldInfo(fieldName, fieldType, readonly);
|
||||
typeInfo.addField(field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse parameters string into list of parameter info.
|
||||
*/
|
||||
private List<JSMethodInfo.JSParameterInfo> parseParameters(String params) {
|
||||
List<JSMethodInfo.JSParameterInfo> result = new ArrayList<>();
|
||||
if (params == null || params.trim().isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Split by comma, but be careful of nested types like Map<K, V>
|
||||
List<String> paramParts = splitParameters(params);
|
||||
|
||||
for (String part : paramParts) {
|
||||
part = part.trim();
|
||||
if (part.isEmpty()) continue;
|
||||
|
||||
// Format: name: type or name?: type
|
||||
int colonIndex = part.indexOf(':');
|
||||
if (colonIndex > 0) {
|
||||
String name = part.substring(0, colonIndex).trim().replace("?", "");
|
||||
String type = cleanType(part.substring(colonIndex + 1).trim());
|
||||
result.add(new JSMethodInfo.JSParameterInfo(name, type));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split parameters respecting nested angle brackets.
|
||||
*/
|
||||
private List<String> splitParameters(String params) {
|
||||
List<String> result = new ArrayList<>();
|
||||
int depth = 0;
|
||||
int start = 0;
|
||||
|
||||
for (int i = 0; i < params.length(); i++) {
|
||||
char c = params.charAt(i);
|
||||
if (c == '<' || c == '(' || c == '[') {
|
||||
depth++;
|
||||
} else if (c == '>' || c == ')' || c == ']') {
|
||||
depth--;
|
||||
} else if (c == ',' && depth == 0) {
|
||||
result.add(params.substring(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (start < params.length()) {
|
||||
result.add(params.substring(start));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up a type string (remove import() syntax, trim, etc.).
|
||||
*/
|
||||
private String cleanType(String type) {
|
||||
if (type == null) return "any";
|
||||
type = type.trim();
|
||||
|
||||
// Handle import('./path').TypeName syntax
|
||||
if (type.startsWith("import(")) {
|
||||
// Extract the type name after the import
|
||||
int dotIndex = type.lastIndexOf(").");
|
||||
if (dotIndex > 0) {
|
||||
type = type.substring(dotIndex + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle arrays
|
||||
type = type.replace("[]", "[]");
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the matching closing brace.
|
||||
*/
|
||||
private int findMatchingBrace(String text, int openBracePos) {
|
||||
int depth = 1;
|
||||
for (int i = openBracePos + 1; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '{') depth++;
|
||||
else if (c == '}') {
|
||||
depth--;
|
||||
if (depth == 0) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read entire content from reader.
|
||||
*/
|
||||
private String readFully(BufferedReader reader) throws IOException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line).append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user