mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-24 15:14:26 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a981947b76 | ||
|
|
a59d2d0088 | ||
|
|
9c82fabf1b |
No files matched your search
@@ -288,9 +288,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
|
||||
// Set the script context for context-aware hook autocomplete
|
||||
activeArea.setScriptContext(getScriptContext());
|
||||
activeArea.enableCodeHighlighting();
|
||||
|
||||
updateScriptDocumentImports(activeArea, container);
|
||||
|
||||
activeArea.enableCodeHighlighting();
|
||||
|
||||
// Setup fullscreen key binding
|
||||
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
|
||||
@@ -299,7 +299,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
}
|
||||
});
|
||||
|
||||
activeArea.enableCodeHighlighting();
|
||||
this.addTextField(activeArea);
|
||||
|
||||
// ==================== FULLSCREEN BUTTON ====================
|
||||
@@ -458,7 +457,10 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
|
||||
previousHookClicked = "";
|
||||
|
||||
updateScriptDocumentImports(getActiveScriptArea(), container);
|
||||
GuiScriptTextArea activeArea = getActiveScriptArea();
|
||||
updateScriptDocumentImports(activeArea, container);
|
||||
activeArea.enableCodeHighlighting();
|
||||
|
||||
} else {
|
||||
previousHookClicked = hook;
|
||||
}
|
||||
@@ -484,10 +486,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
for (String fqn : ctx.getNamespaceFQNs())
|
||||
wildcardImports.add(fqn + ".*");
|
||||
activeArea.addImplicitImports(wildcardImports.toArray(new String[0]));
|
||||
|
||||
|
||||
// Format to update which implicit imports are actually used
|
||||
activeArea.formatCodeText();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3504,9 +3504,6 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
public void setLanguage(String language) {
|
||||
if (this.container != null) {
|
||||
this.container.setLanguage(language);
|
||||
if (this.enableCodeHighlighting) {
|
||||
this.container.formatCodeText();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+288
-155
@@ -159,6 +159,50 @@ public class ScriptDocument {
|
||||
// Populated in inferLambdaParameterTypes() (method calls, constructors, field assignments).
|
||||
// Consumed by resolveExpressionType() to avoid re-inferring lambda context.
|
||||
private final Map<Integer, LambdaCacheEntry> lambdaCache = new HashMap<>();
|
||||
|
||||
// Per-format-cycle cache for resolveSimpleName results.
|
||||
// Avoids repeated wildcard-package Class.forName() scans for the same simple name.
|
||||
// Key: simple name, Value: resolved TypeInfo (may be unresolved for cached misses).
|
||||
// Cleared at start of each formatCodeText() cycle.
|
||||
private final Map<String, TypeInfo> simpleNameCache = new HashMap<>();
|
||||
|
||||
// Profiler accumulators for resolve chain diagnosis (active only when ScriptProfiler.isEnabled())
|
||||
private long profResolveTypePosNs, profResolveTypeNs, profSubstituteNs, profFindEnclosingNs;
|
||||
private long profTrackUsageOverheadNs, profResolveBaseNs, profCachedSimpleNs;
|
||||
private int profResolveTypePosCalls, profResolveTypeCalls, profFindEnclosingCalls;
|
||||
private int profCacheHits, profCacheMisses;
|
||||
private int profResolveBasePrimitive, profResolveBaseString, profResolveBaseScript;
|
||||
private int profResolveBaseDotName, profResolveBaseSimple;
|
||||
|
||||
private void resetResolveProfiler() {
|
||||
profResolveTypePosNs = profResolveTypeNs = profSubstituteNs = profFindEnclosingNs = 0;
|
||||
profTrackUsageOverheadNs = profResolveBaseNs = profCachedSimpleNs = 0;
|
||||
profResolveTypePosCalls = profResolveTypeCalls = profFindEnclosingCalls = 0;
|
||||
profCacheHits = profCacheMisses = 0;
|
||||
profResolveBasePrimitive = profResolveBaseString = profResolveBaseScript = 0;
|
||||
profResolveBaseDotName = profResolveBaseSimple = 0;
|
||||
}
|
||||
|
||||
private void printResolveProfiler() {
|
||||
System.out.println(" [resolve-profiler] ---- resolve chain breakdown ----");
|
||||
emitAccumulatedNanos("resolveType(name,pos) TOTAL", profResolveTypePosNs);
|
||||
System.out.println(String.format(" [resolve-profiler] calls: %d", profResolveTypePosCalls));
|
||||
emitAccumulatedNanos(" resolveType(name) inner", profResolveTypeNs);
|
||||
System.out.println(String.format(" [resolve-profiler] calls: %d", profResolveTypeCalls));
|
||||
emitAccumulatedNanos(" substituteTypeParams", profSubstituteNs);
|
||||
emitAccumulatedNanos(" findEnclosingScriptType", profFindEnclosingNs);
|
||||
System.out.println(String.format(" [resolve-profiler] findEnclosing calls: %d", profFindEnclosingCalls));
|
||||
emitAccumulatedNanos(" trackUsage overhead", profTrackUsageOverheadNs);
|
||||
emitAccumulatedNanos(" resolveBase lambda", profResolveBaseNs);
|
||||
emitAccumulatedNanos(" cachedResolveSimpleName", profCachedSimpleNs);
|
||||
System.out.println(String.format(" [resolve-profiler] cache hits: %d, misses: %d, rate: %.1f%%",
|
||||
profCacheHits, profCacheMisses,
|
||||
(profCacheHits + profCacheMisses) > 0 ? 100.0 * profCacheHits / (profCacheHits + profCacheMisses) : 0));
|
||||
System.out.println(String.format(" [resolve-profiler] resolveBase branches: primitive=%d string=%d script=%d dotName=%d simple=%d",
|
||||
profResolveBasePrimitive, profResolveBaseString, profResolveBaseScript,
|
||||
profResolveBaseDotName, profResolveBaseSimple));
|
||||
System.out.println(" [resolve-profiler] ---- end ----");
|
||||
}
|
||||
|
||||
// Thread-local to communicate SAM conflict errors from resolveIdentifier back to parseMethodArguments
|
||||
// Set when injectSamParameterTypes detects a conflict, cleared after argument is created
|
||||
@@ -368,45 +412,54 @@ public class ScriptDocument {
|
||||
* fieldAccesses, etc.) are shared between languages.
|
||||
*/
|
||||
public void formatCodeText() {
|
||||
// Clear previous state (same for both languages)
|
||||
errors.clear();
|
||||
imports.clear();
|
||||
methods.clear();
|
||||
globalFields.clear();
|
||||
wildcardPackages.clear();
|
||||
excludedRanges.clear();
|
||||
methodLocals.clear();
|
||||
topLevelLocals.clear();
|
||||
scriptTypes.clear();
|
||||
scriptTypesByFullName.clear();
|
||||
scriptTypesByDotName.clear();
|
||||
innerScopes.clear();
|
||||
methodCalls.clear();
|
||||
externalFieldAssignments.clear();
|
||||
declarationErrors.clear();
|
||||
scriptMethodSamContexts.clear();
|
||||
objectLiterals.clear();
|
||||
lambdaCache.clear();
|
||||
|
||||
// Unified pipeline for both languages
|
||||
List<ScriptLine.Mark> marks = formatUnified();
|
||||
ScriptProfiler.begin("formatCodeText");
|
||||
try {
|
||||
errors.clear();
|
||||
imports.clear();
|
||||
methods.clear();
|
||||
globalFields.clear();
|
||||
wildcardPackages.clear();
|
||||
excludedRanges.clear();
|
||||
methodLocals.clear();
|
||||
topLevelLocals.clear();
|
||||
scriptTypes.clear();
|
||||
scriptTypesByFullName.clear();
|
||||
scriptTypesByDotName.clear();
|
||||
innerScopes.clear();
|
||||
methodCalls.clear();
|
||||
externalFieldAssignments.clear();
|
||||
declarationErrors.clear();
|
||||
scriptMethodSamContexts.clear();
|
||||
objectLiterals.clear();
|
||||
lambdaCache.clear();
|
||||
simpleNameCache.clear();
|
||||
|
||||
// Phase 5: Resolve conflicts and sort
|
||||
marks = resolveConflicts(marks);
|
||||
List<ScriptLine.Mark> marks = formatUnified();
|
||||
|
||||
// Phase 6: Build tokens for each line
|
||||
for (ScriptLine line : lines) {
|
||||
line.buildTokensFromMarks(marks, text, this);
|
||||
ScriptProfiler.begin("resolveConflicts");
|
||||
marks = resolveConflicts(marks);
|
||||
ScriptProfiler.end("resolveConflicts");
|
||||
|
||||
ScriptProfiler.begin("buildTokensPerLine");
|
||||
for (ScriptLine line : lines) {
|
||||
line.buildTokensFromMarks(marks, text, this);
|
||||
}
|
||||
ScriptProfiler.end("buildTokensPerLine");
|
||||
|
||||
ScriptProfiler.begin("removeUnusedImplicitImports");
|
||||
removeUnusedImplicitImports();
|
||||
ScriptProfiler.end("removeUnusedImplicitImports");
|
||||
|
||||
ScriptProfiler.begin("computeIndentGuides");
|
||||
computeIndentGuides(marks);
|
||||
ScriptProfiler.end("computeIndentGuides");
|
||||
|
||||
ScriptProfiler.begin("populateErrors");
|
||||
populateErrors();
|
||||
ScriptProfiler.end("populateErrors");
|
||||
} finally {
|
||||
ScriptProfiler.end("formatCodeText");
|
||||
}
|
||||
|
||||
// Phase 6.5: Now that tokens are built, remove implicit imports that aren't actually used
|
||||
removeUnusedImplicitImports();
|
||||
|
||||
// Phase 7: Compute indent guides
|
||||
computeIndentGuides(marks);
|
||||
|
||||
// Phase 8: Populate centralized error list from all error sources
|
||||
populateErrors();
|
||||
}
|
||||
|
||||
// Store the last JS analyzer for autocomplete (deprecated - use methods/globalFields/methodLocals instead)
|
||||
@@ -428,17 +481,23 @@ public class ScriptDocument {
|
||||
private List<ScriptLine.Mark> formatUnified() {
|
||||
TypeChecker.enterTypeCheckingContext(isJavaScript());
|
||||
|
||||
// Phase 1: Find excluded regions (strings/comments) - same for both
|
||||
ScriptProfiler.begin("findExcludedRanges");
|
||||
findExcludedRanges();
|
||||
ScriptProfiler.end("findExcludedRanges");
|
||||
|
||||
// Phase 2: Parse imports (Java only, JS skips this)
|
||||
ScriptProfiler.begin("parseImports");
|
||||
parseImports();
|
||||
ScriptProfiler.end("parseImports");
|
||||
|
||||
// Phase 3: Parse structure (methods, fields, locals) - language aware
|
||||
ScriptProfiler.begin("parseStructure");
|
||||
parseStructure();
|
||||
ScriptProfiler.end("parseStructure");
|
||||
|
||||
// Phase 4: Build marks - language aware
|
||||
return buildMarks();
|
||||
ScriptProfiler.begin("buildMarks");
|
||||
List<ScriptLine.Mark> result = buildMarks();
|
||||
ScriptProfiler.end("buildMarks");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -737,41 +796,48 @@ public class ScriptDocument {
|
||||
* Uses the SAME logic and data structures for both Java and JavaScript.
|
||||
*/
|
||||
private void parseStructure() {
|
||||
// Clear import references before re-parsing
|
||||
for (ImportData imp : imports) {
|
||||
imp.clearReferences();
|
||||
}
|
||||
|
||||
// Parse script-defined types (classes, interfaces, enums) - Java only
|
||||
if (!isJavaScript()) {
|
||||
ScriptProfiler.begin("parseScriptTypes");
|
||||
parseScriptTypes();
|
||||
ScriptProfiler.end("parseScriptTypes");
|
||||
}
|
||||
|
||||
// Parse methods/functions - UNIFIED for both languages
|
||||
ScriptProfiler.begin("parseMethodDeclarations");
|
||||
parseMethodDeclarations();
|
||||
ScriptProfiler.end("parseMethodDeclarations");
|
||||
|
||||
// Parse inner callable scopes (lambdas, JS function expressions)
|
||||
ScriptProfiler.begin("parseInnerCallableScopes");
|
||||
parseInnerCallableScopes();
|
||||
ScriptProfiler.end("parseInnerCallableScopes");
|
||||
|
||||
// Parse local variables inside methods/functions - UNIFIED for both languages
|
||||
ScriptProfiler.begin("parseLocalVariables");
|
||||
parseLocalVariables();
|
||||
ScriptProfiler.end("parseLocalVariables");
|
||||
|
||||
// Parse global fields (outside methods) - UNIFIED for both languages
|
||||
ScriptProfiler.begin("parseGlobalFields");
|
||||
parseGlobalFields();
|
||||
ScriptProfiler.end("parseGlobalFields");
|
||||
|
||||
// Must run before parseAssignments: sets inferredType on lambda params so that
|
||||
// body variable resolution (e.g. "act" in "int x = act.getData()") works correctly.
|
||||
ScriptProfiler.begin("inferLambdaParameterTypes");
|
||||
inferLambdaParameterTypes();
|
||||
ScriptProfiler.end("inferLambdaParameterTypes");
|
||||
|
||||
// Parse and validate assignments (reassignments) - UNIFIED for both languages
|
||||
ScriptProfiler.begin("parseAssignments");
|
||||
parseAssignments();
|
||||
ScriptProfiler.end("parseAssignments");
|
||||
|
||||
// Cache object literals after globals/locals are available for accurate value-type inference
|
||||
ScriptProfiler.begin("parseObjectLiterals");
|
||||
parseObjectLiterals();
|
||||
ScriptProfiler.end("parseObjectLiterals");
|
||||
|
||||
// Detect method overrides and interface implementations for script types - Java only
|
||||
if (!isJavaScript()) {
|
||||
ScriptProfiler.begin("detectMethodInheritance");
|
||||
detectMethodInheritance();
|
||||
ScriptProfiler.end("detectMethodInheritance");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4298,10 +4364,7 @@ public class ScriptDocument {
|
||||
}
|
||||
|
||||
public TypeInfo resolveType(String typeName) {
|
||||
/**
|
||||
* Resolve a JS type name to unified TypeInfo.
|
||||
* Handles JS primitives, .d.ts defined types, and falls back to Java types.
|
||||
*/
|
||||
profResolveTypeCalls++;
|
||||
if (isJavaScript())
|
||||
return typeResolver.resolveJSType(typeName);
|
||||
|
||||
@@ -4373,12 +4436,22 @@ public class ScriptDocument {
|
||||
* @return The resolved TypeInfo, or an unresolved TypeInfo if not found
|
||||
*/
|
||||
public TypeInfo resolveType(String typeName, int position) {
|
||||
// First: delegate to the standard (positionless) resolver
|
||||
TypeInfo resolved = resolveType(typeName);
|
||||
boolean p = ScriptProfiler.isEnabled();
|
||||
long t0 = p ? System.nanoTime() : 0;
|
||||
profResolveTypePosCalls++;
|
||||
|
||||
long t1 = p ? System.nanoTime() : 0;
|
||||
TypeInfo resolved = resolveType(typeName);
|
||||
if (p) profResolveTypeNs += System.nanoTime() - t1;
|
||||
|
||||
// If already resolved, no need for positional fallback
|
||||
if (resolved != null && resolved.isResolved()) {
|
||||
return substituteTypeParams(resolved, position);
|
||||
long tSub = p ? System.nanoTime() : 0;
|
||||
TypeInfo result = substituteTypeParams(resolved, position);
|
||||
if (p) {
|
||||
profSubstituteNs += System.nanoTime() - tSub;
|
||||
profResolveTypePosNs += System.nanoTime() - t0;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (typeName != null && !typeName.contains(".")) {
|
||||
@@ -4386,27 +4459,30 @@ public class ScriptDocument {
|
||||
String baseTypeName = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
long tEnc = p ? System.nanoTime() : 0;
|
||||
profFindEnclosingCalls++;
|
||||
ScriptTypeInfo enclosing = findEnclosingScriptType(position);
|
||||
if (p) profFindEnclosingNs += System.nanoTime() - tEnc;
|
||||
|
||||
while (enclosing != null) {
|
||||
// Check if the name is a declared type parameter on this class (e.g., E in class Box<E>)
|
||||
TypeParamInfo typeParam = enclosing.getDeclaredTypeParam(baseTypeName);
|
||||
if (typeParam != null) {
|
||||
TypeInfo result = TypeInfo.typeParameter(baseTypeName, typeParam);
|
||||
for (int i = 0; i < arrayDims; i++) result = TypeInfo.arrayOf(result);
|
||||
if (p) profResolveTypePosNs += System.nanoTime() - t0;
|
||||
return result;
|
||||
}
|
||||
|
||||
// Check inner classes
|
||||
ScriptTypeInfo inner = enclosing.getInnerClass(typeName);
|
||||
if (inner != null) {
|
||||
if (p) profResolveTypePosNs += System.nanoTime() - t0;
|
||||
return inner;
|
||||
}
|
||||
// Move up to the parent type — inner classes of outer types are also in scope
|
||||
enclosing = enclosing.getOuterClass();
|
||||
}
|
||||
}
|
||||
|
||||
// Return whatever resolveType() returned (possibly unresolved)
|
||||
if (p) profResolveTypePosNs += System.nanoTime() - t0;
|
||||
return resolved;
|
||||
}
|
||||
|
||||
@@ -4416,48 +4492,50 @@ public class ScriptDocument {
|
||||
* Used for Java/Groovy scripts.
|
||||
*/
|
||||
private TypeInfo resolveTypeAndTrackUsage(String typeName) {
|
||||
boolean p = ScriptProfiler.isEnabled();
|
||||
long tOverhead = p ? System.nanoTime() : 0;
|
||||
|
||||
if (typeName == null || typeName.isEmpty())
|
||||
return TypeInfo.unresolved(typeName, typeName);
|
||||
|
||||
final String normalized = typeName.trim();
|
||||
final String normalizedFinal = stripLeadingModifiers(normalized);
|
||||
|
||||
// Split array suffixes first
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalizedFinal);
|
||||
String baseExpr = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
// Base type resolver with import tracking
|
||||
if (p) profTrackUsageOverheadNs += System.nanoTime() - tOverhead;
|
||||
|
||||
Function<String, TypeInfo> resolveBase = baseName -> {
|
||||
boolean pp = ScriptProfiler.isEnabled();
|
||||
long tBase = pp ? System.nanoTime() : 0;
|
||||
TypeInfo resolved;
|
||||
|
||||
// Primitives
|
||||
if (TypeResolver.isPrimitiveType(baseName)) {
|
||||
profResolveBasePrimitive++;
|
||||
resolved = TypeInfo.fromPrimitive(baseName);
|
||||
}
|
||||
// Common java.lang.String
|
||||
else if ("String".equals(baseName)) {
|
||||
profResolveBaseString++;
|
||||
resolved = typeResolver.resolveFullName("java.lang.String");
|
||||
}
|
||||
// Script-defined types (simple names only)
|
||||
else if (!baseName.contains(".") && scriptTypes.containsKey(baseName)) {
|
||||
profResolveBaseScript++;
|
||||
resolved = scriptTypes.get(baseName);
|
||||
}
|
||||
// Script-defined inner types (dot-separated, e.g., "Outer.Inner")
|
||||
// Checked before Java full-name resolution so script types shadow Java types
|
||||
else if (baseName.contains(".") && scriptTypesByDotName.containsKey(baseName)) {
|
||||
profResolveBaseScript++;
|
||||
resolved = scriptTypesByDotName.get(baseName);
|
||||
}
|
||||
// Fully-qualified Java types
|
||||
else if (baseName.contains(".")) {
|
||||
profResolveBaseDotName++;
|
||||
resolved = typeResolver.resolveFullName(baseName);
|
||||
// Fallback: "SimpleName.InnerClass" where SimpleName is a known import
|
||||
// e.g., "Map.Entry" when java.util.Map is imported → java.util.Map$Entry
|
||||
if (resolved == null || !resolved.isResolved()) {
|
||||
int firstDot = baseName.indexOf('.');
|
||||
String outerSimple = baseName.substring(0, firstDot);
|
||||
String innerPath = baseName.substring(firstDot + 1);
|
||||
TypeInfo outerType = typeResolver.resolveSimpleName(outerSimple, importsBySimpleName, wildcardPackages);
|
||||
TypeInfo outerType = cachedResolveSimpleName(outerSimple);
|
||||
if (outerType != null && outerType.isResolved() && outerType.getJavaClass() != null) {
|
||||
Class<?> currentClass = outerType.getJavaClass();
|
||||
for (String part : innerPath.split("\\.")) {
|
||||
@@ -4473,7 +4551,6 @@ public class ScriptDocument {
|
||||
}
|
||||
if (currentClass != null) {
|
||||
resolved = TypeInfo.fromClass(currentClass);
|
||||
// Track import usage for the outer class
|
||||
ImportData usedImport = importsBySimpleName.get(outerSimple);
|
||||
if (usedImport != null) {
|
||||
usedImport.incrementUsage();
|
||||
@@ -4490,11 +4567,12 @@ public class ScriptDocument {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Imported/simple
|
||||
else {
|
||||
resolved = typeResolver.resolveSimpleName(baseName, importsBySimpleName, wildcardPackages);
|
||||
profResolveBaseSimple++;
|
||||
long tSimple = pp ? System.nanoTime() : 0;
|
||||
resolved = cachedResolveSimpleName(baseName);
|
||||
if (pp) profCachedSimpleNs += System.nanoTime() - tSimple;
|
||||
|
||||
// Track import usage
|
||||
if (resolved != null && resolved.isResolved()) {
|
||||
ImportData usedImport = importsBySimpleName.get(baseName);
|
||||
if (usedImport != null) {
|
||||
@@ -4511,23 +4589,20 @@ public class ScriptDocument {
|
||||
}
|
||||
}
|
||||
|
||||
if (pp) profResolveBaseNs += System.nanoTime() - tBase;
|
||||
return resolved != null ? resolved : TypeInfo.unresolved(baseName, normalizedFinal);
|
||||
};
|
||||
|
||||
TypeInfo resolved;
|
||||
|
||||
// Fast path: no generics - skip expensive parsing
|
||||
if (!baseExpr.contains("<")) {
|
||||
resolved = resolveBase.apply(baseExpr);
|
||||
} else {
|
||||
// Slow path: parse and resolve generics
|
||||
GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(baseExpr);
|
||||
if (parsed != null) {
|
||||
// Normalize whitespace around dots in base name
|
||||
String baseName = parsed.baseName.replaceAll("\\s*\\.\\s*", ".").trim();
|
||||
resolved = resolveBase.apply(baseName);
|
||||
|
||||
// Apply generic arguments
|
||||
if (parsed.hasTypeArgs() && resolved != null && resolved.isResolved()) {
|
||||
List<TypeInfo> resolvedArgs = new ArrayList<>();
|
||||
for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) {
|
||||
@@ -4544,11 +4619,9 @@ public class ScriptDocument {
|
||||
}
|
||||
}
|
||||
} else
|
||||
// Fallback: treat as simple type
|
||||
resolved = resolveBase.apply(baseExpr);
|
||||
}
|
||||
|
||||
// Apply array dimensions
|
||||
for (int i = 0; i < arrayDims; i++) {
|
||||
resolved = TypeInfo.arrayOf(resolved);
|
||||
}
|
||||
@@ -4556,6 +4629,21 @@ public class ScriptDocument {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached wrapper for typeResolver.resolveSimpleName() that avoids repeated
|
||||
* wildcard-package scanning for the same simple name within a format cycle.
|
||||
*/
|
||||
private TypeInfo cachedResolveSimpleName(String simpleName) {
|
||||
if (simpleNameCache.containsKey(simpleName)) {
|
||||
profCacheHits++;
|
||||
return simpleNameCache.get(simpleName);
|
||||
}
|
||||
profCacheMisses++;
|
||||
TypeInfo result = typeResolver.resolveSimpleName(simpleName, importsBySimpleName, wildcardPackages);
|
||||
simpleNameCache.put(simpleName, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip only LEADING Java modifiers from a type expression.
|
||||
* This avoids breaking generic argument lists which may contain whitespace.
|
||||
@@ -4593,80 +4681,91 @@ public class ScriptDocument {
|
||||
private List<ScriptLine.Mark> buildMarks() {
|
||||
List<ScriptLine.Mark> marks = new ArrayList<>();
|
||||
|
||||
// Strings first to protect their content
|
||||
ScriptProfiler.begin("markStrings");
|
||||
addPatternMarks(marks, STRING_PATTERN, TokenType.STRING);
|
||||
ScriptProfiler.end("markStrings");
|
||||
|
||||
// JSDoc comments with fragmented marking (avoids conflicts with @tags and {Type})
|
||||
ScriptProfiler.begin("markJSDocElements");
|
||||
markJSDocElements(marks);
|
||||
ScriptProfiler.end("markJSDocElements");
|
||||
|
||||
// Regular comments (non-JSDoc)
|
||||
ScriptProfiler.begin("markComments");
|
||||
markNonJSDocComments(marks);
|
||||
ScriptProfiler.end("markComments");
|
||||
|
||||
// Keywords - same for both languages (KEYWORD_PATTERN includes JS keywords like function, var, let, const)
|
||||
ScriptProfiler.begin("markKeywords");
|
||||
addPatternMarks(marks, KEYWORD_PATTERN, TokenType.KEYWORD);
|
||||
if(isJavaScript())
|
||||
addPatternMarks(marks, KEYWORD_JS_PATTERN, TokenType.KEYWORD);
|
||||
ScriptProfiler.end("markKeywords");
|
||||
|
||||
// Numbers - same for both languages
|
||||
addPatternMarks(marks, NUMBER_PATTERN, TokenType.LITERAL);
|
||||
|
||||
if (isJavaScript()) {
|
||||
markObjectLiteralKeys(marks);
|
||||
}
|
||||
|
||||
// Import statements - Java only
|
||||
if (!isJavaScript()) {
|
||||
markImports(marks);
|
||||
}
|
||||
|
||||
// Class/interface/enum declarations - Java only
|
||||
if (!isJavaScript()) {
|
||||
markClassDeclarations(marks);
|
||||
markEnumConstants(marks);
|
||||
}
|
||||
|
||||
// Modifiers - Java only
|
||||
if (!isJavaScript()) {
|
||||
addPatternMarks(marks, MODIFIER_PATTERN, TokenType.KEYWORD);
|
||||
}
|
||||
|
||||
// Type declarations and usages - Java only (JS doesn't have explicit types)
|
||||
if (!isJavaScript()) {
|
||||
ScriptProfiler.begin("markTypeDeclarations");
|
||||
markTypeDeclarations(marks);
|
||||
ScriptProfiler.end("markTypeDeclarations");
|
||||
}
|
||||
|
||||
// Methods/functions - UNIFIED (uses shared 'methods' list)
|
||||
ScriptProfiler.begin("markMethodDeclarations");
|
||||
markMethodDeclarations(marks);
|
||||
ScriptProfiler.end("markMethodDeclarations");
|
||||
|
||||
// Method calls - UNIFIED (stores in shared 'methodCalls' list)
|
||||
ScriptProfiler.begin("markMethodCalls");
|
||||
markMethodCalls(marks);
|
||||
ScriptProfiler.end("markMethodCalls");
|
||||
|
||||
// Variables and fields - UNIFIED (uses shared globalFields, methodLocals)
|
||||
ScriptProfiler.begin("markVariables");
|
||||
markVariables(marks);
|
||||
ScriptProfiler.end("markVariables");
|
||||
|
||||
// Chained field accesses - UNIFIED (uses resolveVariable which handles both)
|
||||
ScriptProfiler.begin("markChainedFieldAccesses");
|
||||
markChainedFieldAccesses(marks);
|
||||
ScriptProfiler.end("markChainedFieldAccesses");
|
||||
|
||||
ScriptProfiler.begin("markImportedClassUsages");
|
||||
markImportedClassUsages(marks);
|
||||
ScriptProfiler.end("markImportedClassUsages");
|
||||
|
||||
// Java-specific final passes
|
||||
if (!isJavaScript()) {
|
||||
ScriptProfiler.begin("markCastTypes");
|
||||
markCastTypes(marks);
|
||||
ScriptProfiler.end("markCastTypes");
|
||||
|
||||
markUnusedImports(marks);
|
||||
// Mark method reference expressions (target::methodName)
|
||||
markMethodReferences(marks);
|
||||
}
|
||||
|
||||
// Mark lambda and method reference operators (-> and ::)
|
||||
markLambdaOperators(marks);
|
||||
|
||||
// Mark lambda/function parameters with type info
|
||||
ScriptProfiler.begin("markInnerScopeParams");
|
||||
markInnerScopeParameters(marks);
|
||||
ScriptProfiler.end("markInnerScopeParams");
|
||||
|
||||
// Validate lambda return types
|
||||
ScriptProfiler.begin("validateLambdaReturnTypes");
|
||||
validateLambdaReturnTypes(marks);
|
||||
ScriptProfiler.end("validateLambdaReturnTypes");
|
||||
|
||||
// Final pass: Mark any remaining unmarked identifiers as undefined
|
||||
ScriptProfiler.begin("markUndefinedIdentifiers");
|
||||
markUndefinedIdentifiers(marks);
|
||||
ScriptProfiler.end("markUndefinedIdentifiers");
|
||||
|
||||
return marks;
|
||||
}
|
||||
@@ -9824,73 +9923,83 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
}
|
||||
|
||||
private void markImportedClassUsages(List<ScriptLine.Mark> marks) {
|
||||
// Find uppercase identifiers followed by dot (static method calls, field access)
|
||||
boolean profiling = ScriptProfiler.isEnabled();
|
||||
if (profiling) resetResolveProfiler();
|
||||
|
||||
// ── Loop 1: classUsage ── identifiers followed by dot
|
||||
long loop1RegexNs = 0, loop1ExcludedNs = 0, loop1ResolveNs = 0;
|
||||
int loop1Matches = 0, loop1Resolved = 0, loop1Skipped = 0;
|
||||
|
||||
long t0 = profiling ? System.nanoTime() : 0;
|
||||
Pattern classUsage = Pattern.compile("\\b([A-Za-z][a-zA-Z0-9_]*)\\s*\\.");
|
||||
Matcher m = classUsage.matcher(text);
|
||||
if (profiling) loop1RegexNs = System.nanoTime() - t0;
|
||||
|
||||
while (m.find()) {
|
||||
loop1Matches++;
|
||||
String className = m.group(1);
|
||||
int start = m.start(1);
|
||||
int end = m.end(1);
|
||||
|
||||
if (isExcluded(start))
|
||||
continue;
|
||||
long tExcl = profiling ? System.nanoTime() : 0;
|
||||
boolean excluded = isExcluded(start);
|
||||
if (!excluded) excluded = isInImportOrPackage(start);
|
||||
if (profiling) loop1ExcludedNs += System.nanoTime() - tExcl;
|
||||
if (excluded) { loop1Skipped++; continue; }
|
||||
|
||||
// Skip in import/package statements
|
||||
if (isInImportOrPackage(start))
|
||||
continue;
|
||||
|
||||
// For JavaScript, first check synthetic types (Nashorn built-ins like Java, print, etc.)
|
||||
if (isJavaScript()) {
|
||||
if (typeResolver.isSyntheticType(className)) {
|
||||
SyntheticType syntheticType = typeResolver.getSyntheticType(className);
|
||||
// Mark as IMPORTED_CLASS since it's a type reference
|
||||
// Pass the TypeInfo (which the hover system can display)
|
||||
marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.IMPORTED_CLASS,
|
||||
syntheticType.getTypeInfo()));
|
||||
continue;
|
||||
}
|
||||
JSTypeRegistry jsRegistry = JSTypeRegistry.getInstance();
|
||||
if (jsRegistry.isGlobalImport(className)) {
|
||||
// Mark as IMPORTED_CLASS since it's a type reference
|
||||
TypeInfo globalType = TypeInfo.fromJSTypeInfo(jsRegistry.getGlobalImportType(className));
|
||||
marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.INTERFACE_DECL, globalType));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Use position-aware resolution so inner class names (e.g., OrbBuilder inside Outer)
|
||||
// resolve via the positional fallback that walks enclosing.getInnerClass(name).
|
||||
long tRes = profiling ? System.nanoTime() : 0;
|
||||
TypeInfo info = resolveType(className, start);
|
||||
if (profiling) loop1ResolveNs += System.nanoTime() - tRes;
|
||||
|
||||
if (info != null && info.isResolved()) {
|
||||
loop1Resolved++;
|
||||
marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info));
|
||||
} else {
|
||||
// Unknown type - mark as undefined
|
||||
marks.add(new ScriptLine.Mark(start, end, TokenType.UNDEFINED_VAR));
|
||||
}
|
||||
}
|
||||
|
||||
// Also mark uppercase identifiers in type positions (new X(), X variable, etc.)
|
||||
// ── Loop 2: typeUsage ── identifiers in type positions (new, decl, etc.)
|
||||
long loop2RegexNs = 0, loop2ExcludedNs = 0, loop2ResolveNs = 0;
|
||||
long loop2CtorParseNs = 0, loop2CtorMatchNs = 0, loop2CtorValidateNs = 0;
|
||||
long loop2QualWalkNs = 0;
|
||||
int loop2Matches = 0, loop2Resolved = 0, loop2Skipped = 0;
|
||||
int loop2CtorCalls = 0, loop2CtorSecondPass = 0;
|
||||
|
||||
t0 = profiling ? System.nanoTime() : 0;
|
||||
Pattern typeUsage = Pattern.compile("\\b(new\\s+)?([A-Za-z][a-zA-Z0-9_]*)(?:\\s*<[^>]*>)?\\s*(?:\\(|\\[|\\b[a-z])");
|
||||
Matcher tm = typeUsage.matcher(text);
|
||||
if (profiling) loop2RegexNs = System.nanoTime() - t0;
|
||||
|
||||
while (tm.find()) {
|
||||
loop2Matches++;
|
||||
String className = tm.group(2);
|
||||
String newKeyword = tm.group(1);
|
||||
int start = tm.start(2);
|
||||
int end = tm.end(2);
|
||||
|
||||
if (isExcluded(start))
|
||||
continue;
|
||||
long tExcl = profiling ? System.nanoTime() : 0;
|
||||
boolean excluded = isExcluded(start);
|
||||
if (!excluded) excluded = isInImportOrPackage(start);
|
||||
if (profiling) loop2ExcludedNs += System.nanoTime() - tExcl;
|
||||
if (excluded) { loop2Skipped++; continue; }
|
||||
|
||||
// Skip in import/package statements
|
||||
if (isInImportOrPackage(start))
|
||||
continue;
|
||||
|
||||
// When the class name is preceded by a dot (e.g., OrbBuilder in AbilityLine.OrbBuilder),
|
||||
// walk backwards to reconstruct the full qualified name and resolve via scriptTypesByDotName.
|
||||
// resolveType(simpleNameOnly) fails outside the enclosing class body; the qualified name always works.
|
||||
// We also track outerQualStart so we can detect 'new' before the full qualified name.
|
||||
long tQual = profiling ? System.nanoTime() : 0;
|
||||
String resolveKey = className;
|
||||
int outerQualStart = start;
|
||||
if (isPrecededByDot(start)) {
|
||||
@@ -9907,18 +10016,21 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--;
|
||||
}
|
||||
}
|
||||
if (profiling) loop2QualWalkNs += System.nanoTime() - tQual;
|
||||
|
||||
long tRes = profiling ? System.nanoTime() : 0;
|
||||
TypeInfo info = resolveType(resolveKey, start);
|
||||
if (info == null || !info.isResolved()) {
|
||||
info = resolveType(className, start);
|
||||
}
|
||||
if (profiling) loop2ResolveNs += System.nanoTime() - tRes;
|
||||
|
||||
boolean isClassTypeInfo = false;
|
||||
ClassTypeInfo classRef = null;
|
||||
FieldInfo varInfo = null;
|
||||
// If not a class name, check if it's a variable holding a ClassTypeInfo
|
||||
if ((info == null || !info.isResolved()) && isJavaScript()) {
|
||||
varInfo = resolveVariable(className, start);
|
||||
if (varInfo != null && varInfo.getTypeInfo() instanceof ClassTypeInfo) {
|
||||
// Variable holds a class reference (like var File = Java.type("java.io.File"))
|
||||
classRef = (ClassTypeInfo) varInfo.getTypeInfo();
|
||||
info = classRef.getInstanceType();
|
||||
isClassTypeInfo = true;
|
||||
@@ -9926,10 +10038,8 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
}
|
||||
|
||||
if (info != null && info.isResolved()) {
|
||||
loop2Resolved++;
|
||||
boolean isNewCreation = newKeyword != null && newKeyword.trim().equals("new");
|
||||
// For dot-qualified types like 'new AbilityLine.OrbBuilder(...)', the regex never
|
||||
// captures 'new' in group 1 because 'new' precedes 'AbilityLine', not 'OrbBuilder'.
|
||||
// Detect it by checking whether outerQualStart is preceded by the 'new' keyword.
|
||||
if (!isNewCreation && outerQualStart < start) {
|
||||
int checkPos = outerQualStart - 1;
|
||||
while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) checkPos--;
|
||||
@@ -9942,14 +10052,11 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
}
|
||||
boolean isConstructorDecl = info instanceof ScriptTypeInfo && className.equals(info.getSimpleName());
|
||||
|
||||
// Check if this is a "new" expression or constructor declaration
|
||||
if (isNewCreation || isConstructorDecl) {
|
||||
// Find opening paren after the class name
|
||||
int searchPos = end;
|
||||
while (searchPos < text.length() && Character.isWhitespace(text.charAt(searchPos)))
|
||||
searchPos++;
|
||||
|
||||
// Skip generic args or diamond operator (e.g., <Integer> or <>)
|
||||
if (searchPos < text.length() && text.charAt(searchPos) == '<') {
|
||||
int closeAngle = text.indexOf('>', searchPos);
|
||||
if (closeAngle >= 0) {
|
||||
@@ -9964,31 +10071,28 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
int closeParen = findMatchingParen(openParen);
|
||||
|
||||
if (closeParen >= 0) {
|
||||
// For constructor declarations, verify it's followed by opening brace
|
||||
if (isConstructorDecl && !isNewCreation) {
|
||||
int braceSearch = closeParen + 1;
|
||||
while (braceSearch < text.length() && Character.isWhitespace(text.charAt(braceSearch)))
|
||||
braceSearch++;
|
||||
|
||||
if (braceSearch >= text.length() || text.charAt(braceSearch) != '{') {
|
||||
// Not a constructor declaration, treat as normal type usage
|
||||
marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse arguments to find matching constructor
|
||||
loop2CtorCalls++;
|
||||
long tParse = profiling ? System.nanoTime() : 0;
|
||||
List<MethodCallInfo.Argument> arguments = parseMethodArguments(openParen + 1, closeParen,
|
||||
null, info);
|
||||
if (profiling) loop2CtorParseNs += System.nanoTime() - tParse;
|
||||
|
||||
int argCount = arguments.size();
|
||||
TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType)
|
||||
.toArray(TypeInfo[]::new);
|
||||
|
||||
|
||||
// Try to find matching constructor (may be null if not found).
|
||||
// First try exact type-match; if that fails but constructors exist, fall back to
|
||||
// arg-count match so validate() can fire a WRONG_ARG_TYPE error instead of
|
||||
// incorrectly treating the call as "no constructor matches N arguments".
|
||||
long tMatch = profiling ? System.nanoTime() : 0;
|
||||
MethodInfo constructor = null;
|
||||
if (info.hasConstructors()) {
|
||||
constructor = info.findConstructor(argTypes);
|
||||
@@ -9996,24 +10100,23 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
constructor = info.findConstructor(argCount);
|
||||
}
|
||||
}
|
||||
if (profiling) loop2CtorMatchNs += System.nanoTime() - tMatch;
|
||||
|
||||
// Second pass: re-parse arguments with expected parameter types from resolved constructor
|
||||
// This enables SAM type inference for lambda arguments (e.g., Consumer<T> parameters)
|
||||
if (constructor != null && constructor.getParameters().size() == arguments.size()) {
|
||||
loop2CtorSecondPass++;
|
||||
long tParse2 = profiling ? System.nanoTime() : 0;
|
||||
arguments = parseMethodArguments(openParen + 1, closeParen, constructor, info);
|
||||
if (profiling) loop2CtorParseNs += System.nanoTime() - tParse2;
|
||||
}
|
||||
|
||||
// Create MethodCallInfo for constructor
|
||||
// Use the actual variable name (className) for variables, not the class's simple name
|
||||
MethodCallInfo ctorCall;
|
||||
if (isClassTypeInfo) {
|
||||
// Use constructor directly with variable name
|
||||
ctorCall = new MethodCallInfo(
|
||||
className, // Use variable name, not class name
|
||||
className,
|
||||
start, end,
|
||||
openParen, closeParen,
|
||||
arguments,
|
||||
classRef, // The actual class type
|
||||
classRef,
|
||||
constructor,
|
||||
false
|
||||
).setConstructor(true);
|
||||
@@ -10024,9 +10127,11 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
);
|
||||
}
|
||||
|
||||
long tVal = profiling ? System.nanoTime() : 0;
|
||||
ctorCall.validate();
|
||||
methodCalls.add(ctorCall); // Add to methodCalls list for error tracking
|
||||
if (profiling) loop2CtorValidateNs += System.nanoTime() - tVal;
|
||||
|
||||
methodCalls.add(ctorCall);
|
||||
|
||||
TokenType type = isClassTypeInfo ? varInfo.isGlobal() ? TokenType.GLOBAL_FIELD
|
||||
: TokenType.LOCAL_FIELD : TokenType.METHOD_CALL;
|
||||
@@ -10038,10 +10143,38 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
|
||||
marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info));
|
||||
} else {
|
||||
// Unknown type - mark as undefined
|
||||
marks.add(new ScriptLine.Mark(start, end, TokenType.UNDEFINED_VAR));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Emit profiler sections from accumulated timings ──
|
||||
if (profiling) {
|
||||
emitAccumulatedNanos("classUsage.regexCompile", loop1RegexNs);
|
||||
emitAccumulatedNanos("classUsage.isExcluded", loop1ExcludedNs);
|
||||
emitAccumulatedNanos("classUsage.resolveType", loop1ResolveNs);
|
||||
emitAccumulatedNanos("typeUsage.regexCompile", loop2RegexNs);
|
||||
emitAccumulatedNanos("typeUsage.isExcluded", loop2ExcludedNs);
|
||||
emitAccumulatedNanos("typeUsage.qualWalk", loop2QualWalkNs);
|
||||
emitAccumulatedNanos("typeUsage.resolveType", loop2ResolveNs);
|
||||
emitAccumulatedNanos("typeUsage.ctorParse", loop2CtorParseNs);
|
||||
emitAccumulatedNanos("typeUsage.ctorMatch", loop2CtorMatchNs);
|
||||
emitAccumulatedNanos("typeUsage.ctorValidate", loop2CtorValidateNs);
|
||||
|
||||
System.out.println("[markImportedClassUsages] Loop1: " + loop1Matches + " matches, "
|
||||
+ loop1Skipped + " skipped, " + loop1Resolved + " resolved"
|
||||
+ " | Loop2: " + loop2Matches + " matches, " + loop2Skipped + " skipped, "
|
||||
+ loop2Resolved + " resolved, " + loop2CtorCalls + " ctors ("
|
||||
+ loop2CtorSecondPass + " 2nd-pass)");
|
||||
|
||||
printResolveProfiler();
|
||||
}
|
||||
}
|
||||
|
||||
private void emitAccumulatedNanos(String name, long nanos) {
|
||||
double ms = nanos / 1_000_000.0;
|
||||
if (ms >= 0.01) {
|
||||
System.out.println(String.format(" [profiler] %-30s %8.2f ms", name, ms));
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== PHASE 5: CONFLICT RESOLUTION ====================
|
||||
@@ -11014,7 +11147,7 @@ for (ScriptTypeInfo type:scriptTypes.values()) {
|
||||
Set<TypeInfo> types = new HashSet<>();
|
||||
for (ImportData imp : imports) {
|
||||
if (!imp.isWildcard() && imp.isResolved()) {
|
||||
TypeInfo type = typeResolver.resolveSimpleName(imp.getSimpleName(), importsBySimpleName, wildcardPackages);
|
||||
TypeInfo type = cachedResolveSimpleName(imp.getSimpleName());
|
||||
if (type != null && type.isResolved()) {
|
||||
types.add(type);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Profiler for the ScriptDocument parsing/marking pipeline.
|
||||
* <p>
|
||||
* <b>Usage:</b>
|
||||
* <pre>
|
||||
* ScriptProfiler.setEnabled(true);
|
||||
* ScriptProfiler.setReportingThresholdMs(5.0);
|
||||
* // Results auto-print to System.out when root section ends.
|
||||
* // Or: ScriptProfiler.getLastReport();
|
||||
* </pre>
|
||||
* <p>
|
||||
* When disabled, begin/end are single boolean checks with zero overhead.
|
||||
* Single-threaded only (Minecraft client thread).
|
||||
*/
|
||||
public final class ScriptProfiler {
|
||||
|
||||
private static boolean enabled = false;
|
||||
private static double reportingThresholdMs = 0.0;
|
||||
private static boolean autoPrint = true;
|
||||
private static int maxHistory = 50;
|
||||
|
||||
private static final Deque<ActiveSection> sectionStack = new ArrayDeque<>();
|
||||
private static final List<SectionResult> currentResults = new ArrayList<>();
|
||||
private static int currentDepth = 0;
|
||||
private static int beginSequence = 0;
|
||||
private static final Deque<ProfileSnapshot> history = new ArrayDeque<>();
|
||||
private static String lastReport = null;
|
||||
private static ProfileSnapshot lastSnapshot = null;
|
||||
private static final Map<String, AccumulatedStats> accumulatedStats = new LinkedHashMap<>();
|
||||
private static int invocationCount = 0;
|
||||
|
||||
public static void setEnabled(boolean enable) {
|
||||
enabled = enable;
|
||||
if (!enable) {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public static void setReportingThresholdMs(double thresholdMs) {
|
||||
reportingThresholdMs = thresholdMs;
|
||||
}
|
||||
|
||||
public static void setAutoPrint(boolean auto) {
|
||||
autoPrint = auto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin timing a named section. Sections nest: begin("A") -> begin("B") -> end("B") -> end("A").
|
||||
*/
|
||||
public static void begin(String name) {
|
||||
if (!enabled) return;
|
||||
sectionStack.push(new ActiveSection(name, System.nanoTime(), currentDepth, beginSequence++));
|
||||
currentDepth++;
|
||||
}
|
||||
|
||||
/**
|
||||
* End timing a named section. Must match the most recent begin().
|
||||
*/
|
||||
public static void end(String name) {
|
||||
if (!enabled) return;
|
||||
if (sectionStack.isEmpty()) {
|
||||
System.err.println("[ScriptProfiler] WARNING: end('" + name + "') called with no active section");
|
||||
return;
|
||||
}
|
||||
|
||||
ActiveSection active = sectionStack.pop();
|
||||
currentDepth--;
|
||||
|
||||
if (!active.name.equals(name)) {
|
||||
System.err.println("[ScriptProfiler] WARNING: end('" + name + "') doesn't match begin('" + active.name + "')");
|
||||
}
|
||||
|
||||
long elapsed = System.nanoTime() - active.startNano;
|
||||
currentResults.add(new SectionResult(active.name, active.depth, elapsed, active.beginOrder));
|
||||
|
||||
if (sectionStack.isEmpty()) {
|
||||
finalizeReport();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: time a Runnable.
|
||||
*/
|
||||
public static void time(String name, Runnable work) {
|
||||
begin(name);
|
||||
try {
|
||||
work.run();
|
||||
} finally {
|
||||
end(name);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getLastReport() {
|
||||
return lastReport;
|
||||
}
|
||||
|
||||
public static ProfileSnapshot getLastSnapshot() {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
public static List<ProfileSnapshot> getHistory() {
|
||||
return new ArrayList<>(history);
|
||||
}
|
||||
|
||||
public static Map<String, AccumulatedStats> getAccumulatedStats() {
|
||||
return Collections.unmodifiableMap(accumulatedStats);
|
||||
}
|
||||
|
||||
public static int getInvocationCount() {
|
||||
return invocationCount;
|
||||
}
|
||||
|
||||
public static void reset() {
|
||||
sectionStack.clear();
|
||||
currentResults.clear();
|
||||
currentDepth = 0;
|
||||
beginSequence = 0;
|
||||
history.clear();
|
||||
lastReport = null;
|
||||
lastSnapshot = null;
|
||||
accumulatedStats.clear();
|
||||
invocationCount = 0;
|
||||
}
|
||||
|
||||
public static void resetStats() {
|
||||
history.clear();
|
||||
accumulatedStats.clear();
|
||||
invocationCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Summary of accumulated stats across all invocations -
|
||||
* identifies consistent bottlenecks vs. one-off spikes.
|
||||
*/
|
||||
public static String getAccumulatedReport() {
|
||||
if (accumulatedStats.isEmpty()) {
|
||||
return "[ScriptProfiler] No accumulated data.";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\n============================================================\n");
|
||||
sb.append(" SCRIPT PROFILER - ACCUMULATED STATS\n");
|
||||
sb.append(" Invocations: ").append(invocationCount).append("\n");
|
||||
sb.append("============================================================\n");
|
||||
sb.append(String.format(" %-30s | %7s | %7s | %7s\n", "Section", "Avg(ms)", "Max(ms)", "Min(ms)"));
|
||||
sb.append("------------------------------------------------------------\n");
|
||||
|
||||
for (Map.Entry<String, AccumulatedStats> entry : accumulatedStats.entrySet()) {
|
||||
AccumulatedStats stats = entry.getValue();
|
||||
String indent = getIndent(stats.depth);
|
||||
String label = indent + truncate(entry.getKey(), 30 - indent.length());
|
||||
sb.append(String.format(" %-30s | %7.2f | %7.2f | %7.2f\n",
|
||||
label, stats.getAverageMs(), stats.getMaxMs(), stats.getMinMs()));
|
||||
}
|
||||
|
||||
sb.append("============================================================\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// ======================== Internals ========================
|
||||
|
||||
private static void finalizeReport() {
|
||||
invocationCount++;
|
||||
|
||||
List<SectionResult> results = new ArrayList<>(currentResults);
|
||||
Collections.sort(results, new Comparator<SectionResult>() {
|
||||
public int compare(SectionResult a, SectionResult b) {
|
||||
return Integer.compare(a.beginOrder, b.beginOrder);
|
||||
}
|
||||
});
|
||||
ProfileSnapshot snapshot = new ProfileSnapshot(results, System.currentTimeMillis());
|
||||
lastSnapshot = snapshot;
|
||||
|
||||
history.addLast(snapshot);
|
||||
while (history.size() > maxHistory) {
|
||||
history.removeFirst();
|
||||
}
|
||||
|
||||
for (SectionResult r : results) {
|
||||
AccumulatedStats stats = accumulatedStats.get(r.name);
|
||||
if (stats == null) {
|
||||
stats = new AccumulatedStats(r.depth);
|
||||
accumulatedStats.put(r.name, stats);
|
||||
}
|
||||
stats.record(r.elapsedNanos);
|
||||
}
|
||||
|
||||
String report = buildReport(snapshot);
|
||||
lastReport = report;
|
||||
|
||||
if (autoPrint) {
|
||||
double totalMs = snapshot.getTotalMs();
|
||||
if (totalMs >= reportingThresholdMs) {
|
||||
System.out.println(report);
|
||||
}
|
||||
}
|
||||
|
||||
currentResults.clear();
|
||||
currentDepth = 0;
|
||||
beginSequence = 0;
|
||||
}
|
||||
|
||||
private static String buildReport(ProfileSnapshot snapshot) {
|
||||
List<SectionResult> results = snapshot.results;
|
||||
if (results.isEmpty()) return "[ScriptProfiler] Empty report.";
|
||||
|
||||
SectionResult root = null;
|
||||
for (SectionResult r : results) {
|
||||
if (r.depth == 0) {
|
||||
root = r;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (root == null) root = results.get(0);
|
||||
|
||||
double totalMs = root.elapsedNanos / 1_000_000.0;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\n================================================================\n");
|
||||
sb.append(" SCRIPT DOCUMENT PROFILER - Pipeline Breakdown\n");
|
||||
sb.append(" Total: ").append(String.format("%.2fms", totalMs));
|
||||
sb.append(" | Lines: ").append(getLineCount());
|
||||
sb.append(" | Chars: ").append(getCharCount());
|
||||
sb.append("\n================================================================\n");
|
||||
sb.append(String.format(" %-36s | %8s | %5s | %s\n", "Stage", "Time(ms)", " % ", "Bar"));
|
||||
sb.append("----------------------------------------------------------------\n");
|
||||
|
||||
for (SectionResult r : results) {
|
||||
double ms = r.elapsedNanos / 1_000_000.0;
|
||||
double pct = (root.elapsedNanos > 0) ? (100.0 * r.elapsedNanos / root.elapsedNanos) : 0;
|
||||
String indent = getIndent(r.depth);
|
||||
String label = indent + truncate(r.name, 36 - indent.length());
|
||||
String bar = makeBar(pct, 8);
|
||||
|
||||
String flag = "";
|
||||
if (r.depth > 0 && (pct > 20.0 || ms > 5.0)) {
|
||||
flag = " << SLOW";
|
||||
}
|
||||
|
||||
sb.append(String.format(" %-36s | %8.2f | %4.1f%% | %-8s %s\n",
|
||||
label, ms, pct, bar, flag));
|
||||
}
|
||||
|
||||
long childSum = 0;
|
||||
for (SectionResult r : results) {
|
||||
if (r.depth == 1) {
|
||||
childSum += r.elapsedNanos;
|
||||
}
|
||||
}
|
||||
if (root.elapsedNanos > 0) {
|
||||
long unaccounted = root.elapsedNanos - childSum;
|
||||
if (unaccounted > 0) {
|
||||
double uMs = unaccounted / 1_000_000.0;
|
||||
double uPct = 100.0 * unaccounted / root.elapsedNanos;
|
||||
sb.append(String.format(" %-36s | %8.2f | %4.1f%% | %-8s\n",
|
||||
" (overhead/unlisted)", uMs, uPct, makeBar(uPct, 8)));
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("================================================================\n");
|
||||
sb.append(buildBottleneckSummary(results, root.elapsedNanos));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String buildBottleneckSummary(List<SectionResult> results, long totalNanos) {
|
||||
if (results.size() <= 1) return "";
|
||||
|
||||
List<SectionResult> sorted = new ArrayList<>();
|
||||
for (SectionResult r : results) {
|
||||
if (r.depth > 0) sorted.add(r);
|
||||
}
|
||||
Collections.sort(sorted, new Comparator<SectionResult>() {
|
||||
public int compare(SectionResult a, SectionResult b) {
|
||||
return Long.compare(b.elapsedNanos, a.elapsedNanos);
|
||||
}
|
||||
});
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(" Top bottlenecks:\n");
|
||||
int count = Math.min(3, sorted.size());
|
||||
for (int i = 0; i < count; i++) {
|
||||
SectionResult r = sorted.get(i);
|
||||
double ms = r.elapsedNanos / 1_000_000.0;
|
||||
double pct = totalNanos > 0 ? (100.0 * r.elapsedNanos / totalNanos) : 0;
|
||||
sb.append(String.format(" %d. %-30s %7.2fms (%4.1f%%)\n", i + 1, r.name, ms, pct));
|
||||
}
|
||||
sb.append("\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String getIndent(int depth) {
|
||||
if (depth <= 0) return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < depth; i++) sb.append(" ");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String truncate(String s, int max) {
|
||||
if (max <= 0) return "";
|
||||
if (s.length() <= max) return s;
|
||||
return s.substring(0, max - 2) + "..";
|
||||
}
|
||||
|
||||
private static String makeBar(double pct, int maxLen) {
|
||||
int filled = (int) Math.round(pct / 100.0 * maxLen);
|
||||
filled = Math.min(filled, maxLen);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < filled; i++) sb.append('#');
|
||||
for (int i = filled; i < maxLen; i++) sb.append('.');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String pad(int n) {
|
||||
if (n <= 0) return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < n; i++) sb.append(' ');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static int getLineCount() {
|
||||
ScriptDocument doc = ScriptDocument.INSTANCE;
|
||||
return doc != null ? doc.getLines().size() : 0;
|
||||
}
|
||||
|
||||
private static int getCharCount() {
|
||||
ScriptDocument doc = ScriptDocument.INSTANCE;
|
||||
return doc != null ? doc.getText().length() : 0;
|
||||
}
|
||||
|
||||
// ======================== Data Classes ========================
|
||||
|
||||
private static class ActiveSection {
|
||||
final String name;
|
||||
final long startNano;
|
||||
final int depth;
|
||||
final int beginOrder;
|
||||
|
||||
ActiveSection(String name, long startNano, int depth, int beginOrder) {
|
||||
this.name = name;
|
||||
this.startNano = startNano;
|
||||
this.depth = depth;
|
||||
this.beginOrder = beginOrder;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SectionResult {
|
||||
public final String name;
|
||||
public final int depth;
|
||||
public final long elapsedNanos;
|
||||
final int beginOrder;
|
||||
|
||||
SectionResult(String name, int depth, long elapsedNanos, int beginOrder) {
|
||||
this.name = name;
|
||||
this.depth = depth;
|
||||
this.elapsedNanos = elapsedNanos;
|
||||
this.beginOrder = beginOrder;
|
||||
}
|
||||
|
||||
public double getElapsedMs() {
|
||||
return elapsedNanos / 1_000_000.0;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProfileSnapshot {
|
||||
public final List<SectionResult> results;
|
||||
public final long timestampMs;
|
||||
|
||||
ProfileSnapshot(List<SectionResult> results, long timestampMs) {
|
||||
this.results = Collections.unmodifiableList(results);
|
||||
this.timestampMs = timestampMs;
|
||||
}
|
||||
|
||||
public double getTotalMs() {
|
||||
if (results.isEmpty()) return 0;
|
||||
return results.get(0).getElapsedMs();
|
||||
}
|
||||
|
||||
public double getSectionMs(String name) {
|
||||
for (SectionResult r : results) {
|
||||
if (r.name.equals(name)) return r.getElapsedMs();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public static class AccumulatedStats {
|
||||
public final int depth;
|
||||
private long totalNanos;
|
||||
private long maxNanos;
|
||||
private long minNanos;
|
||||
private int count;
|
||||
|
||||
AccumulatedStats(int depth) {
|
||||
this.depth = depth;
|
||||
this.totalNanos = 0;
|
||||
this.maxNanos = Long.MIN_VALUE;
|
||||
this.minNanos = Long.MAX_VALUE;
|
||||
this.count = 0;
|
||||
}
|
||||
|
||||
void record(long nanos) {
|
||||
totalNanos += nanos;
|
||||
if (nanos > maxNanos) maxNanos = nanos;
|
||||
if (nanos < minNanos) minNanos = nanos;
|
||||
count++;
|
||||
}
|
||||
|
||||
public double getAverageMs() {
|
||||
return count > 0 ? (totalNanos / (double) count) / 1_000_000.0 : 0;
|
||||
}
|
||||
|
||||
public double getMaxMs() {
|
||||
return maxNanos != Long.MIN_VALUE ? maxNanos / 1_000_000.0 : 0;
|
||||
}
|
||||
|
||||
public double getMinMs() {
|
||||
return minNanos != Long.MAX_VALUE ? minNanos / 1_000_000.0 : 0;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
private ScriptProfiler() {}
|
||||
}
|
||||
@@ -190,6 +190,9 @@ public class ScriptTextContainer extends JavaTextContainer {
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. initScriptEditor.setLanguage
|
||||
* 2. initScriptEditorTab.enableCodeHighlighting
|
||||
* 3. initScriptEditor.updateScriptDocumentImports
|
||||
* Main formatting entry point - matches JavaTextContainer signature.
|
||||
*/
|
||||
@Override
|
||||
@@ -199,7 +202,9 @@ public class ScriptTextContainer extends JavaTextContainer {
|
||||
return;
|
||||
}
|
||||
|
||||
ScriptProfiler.setEnabled(true);
|
||||
document.formatCodeText();
|
||||
ScriptProfiler.setEnabled(false);
|
||||
rebuildLineData();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user