-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathJavaTextContainer.java
More file actions
1316 lines (1152 loc) · 58.8 KB
/
Copy pathJavaTextContainer.java
File metadata and controls
1316 lines (1152 loc) · 58.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.ClientProxy;
import noppes.npcs.client.gui.util.TextContainer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaTextContainer extends TextContainer {
public static final Pattern MODIFIER = Pattern.compile(
"\\b(public|protected|private|static|final|abstract|synchronized|native|default)\\b");
public static final Pattern KEYWORD = Pattern.compile(
"\\b(null|boolean|int|float|double|long|char|byte|short|void|if|else|switch|case|for|while|do|try|catch|finally|return|throw|var|let|const|function|continue|break|this|new|typeof|instanceof|import)\\b");
public static final Pattern CLASS_DECL = Pattern.compile("\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)");
public static final Pattern NEW_TYPE = Pattern.compile("\\bnew\\s+([A-Za-z_][a-zA-Z0-9_]*)");
;
public static final Pattern METHOD_DECL = Pattern.compile("\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name
);
public static final Pattern METHOD_CALL = Pattern.compile("([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(");
// Class-level global fields
public static final Pattern GLOBAL_FIELD_DECL = Pattern.compile(
"\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
// Local fields inside methods (simplified)
public static final Pattern LOCAL_FIELD_DECL = Pattern.compile(
"\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
public static final Pattern STRING = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1");
public static final Pattern COMMENT = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*|#.*");
public static final Pattern NUMBER = Pattern.compile(
"\\b-?(?:0[xX][\\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?(?:[fFbBdDlLsS])?|NaN|null|Infinity|true|false)\\b");
// Import statement: import [static] package.path.ClassName [.*]; (semicolon optional for live typing)
// Allows optional whitespace (including newlines) around the dots so wrapped imports match.
// Match imports while allowing optional whitespace/newlines around dots.
public static final Pattern IMPORT = Pattern.compile(
"(?m)\\bimport\\s+(?:static\\s+)?([A-Za-z_][A-Za-z0-9_]*(?:\\s*\\.\\s*[A-Za-z_][A-Za-z0-9_]*)*)(?:\\s*\\.\\s*\\*?)?\\s*(?:;|$)");
// ClassPathFinder for resolving imports and determining class types
private final ClassPathFinder classPathFinder = new ClassPathFinder();
public List<LineData> lines = new ArrayList<>();
public List<MethodBlock> methodBlocks = new ArrayList<>();
public JavaTextContainer(String text) {
super(text);
}
// Map an offset into the normalized path (tokens joined with '.') back to
// an absolute index in the original substring `orig` (absolute positions start at pathStart).
// The normalization removes whitespace/newlines around dots; this function
// advances a normalized counter when it encounters identifier chars or dots
// and returns the corresponding original index (absolute).
private int mapNormalizedOffsetToOriginal(String orig, int normalizedOffset, int pathStart) {
if (orig == null || orig.isEmpty()) return pathStart;
int norm = 0;
for (int i = 0; i < orig.length(); i++) {
char c = orig.charAt(i);
if (Character.isLetterOrDigit(c) || c == '_' || c == '.') {
norm++;
}
if (norm >= normalizedOffset) {
return pathStart + i;
}
}
return pathStart + orig.length();
}
public void init(String text, int width, int height) {
this.text = text == null ? "" : text.replaceAll("\\r?\\n|\\r", "\n");
lines.clear();
String[] split = this.text.split("\n", -1);
int totalChars = 0;
for (String l : split) {
StringBuilder line = new StringBuilder();
// Break the source line `l` into layout-friendly segments using `regexWord`.
// `regexWord` finds word tokens (letters/numbers/underscore/hyphen), newlines
// or the end-of-line. The loop takes substrings from the previous match
// index `i` up to the current `m.start()` so each `word` contains the
// next token plus any following delimiters (spaces, punctuation).
// This lets us measure and wrap at token boundaries rather than mid-word.
Matcher m = regexWord.matcher(l);
int i = 0;
while (m.find()) {
String word = l.substring(i, m.start());
if (ClientProxy.Font.width(line + word) > width - 10) {
// Note: `end` is an exclusive offset into the full text (start..end).
// For wrapped lines we record the current `totalChars` as the start
// and compute the exclusive end as `start + line.length()`.
lines.add(new LineData(line.toString(), totalChars, totalChars += line.length()));
line = new StringBuilder();
}
line.append(word);
i = m.start();
}
lines.add(new LineData(line.toString(), totalChars, totalChars += line.length() + 1));
}
linesCount = lines.size();
totalHeight = linesCount * lineHeight;
// Number of fully-visible lines that fit in the given viewport height.
// Use floor division and ensure at least 1 line is visible.
// Don't forget -1, fixes enter auto-scrolling properly
visibleLines = Math.max(height / lineHeight - 1, 1);
}
private List<String> globalFields = new ArrayList<>();
private List<String> localFields = new ArrayList<>();
private java.util.Map<String, String> importedClasses = new java.util.HashMap<>(); // simpleName -> fullName
private java.util.Set<String> importedPackages = new java.util.HashSet<>(); // wildcard imports
private java.util.Set<String> unresolvedClasses = new java.util.HashSet<>(); // classes that failed to resolve
private java.util.List<ImportEntry> importEntries = new java.util.ArrayList<>();
private static class ImportEntry {
public final String fullPath; // normalized path (no trailing . or *)
public final String matchText; // full matched import text
public final int pathStart; // start of the path group
public final int pathEnd; // end of the path group
public final int importKwStart; // start of the 'import' keyword
public final int importKwEnd; // end of the 'import' keyword
public final int starPos; // absolute pos of '*' in matchText, or -1
public final boolean isWildcard;
// Cached resolve result (may be null for wildcard imports or if not resolved yet)
public ClassPathFinder.ResolveResult resolveResult;
public ImportEntry(String fullPath, String matchText, int pathStart, int pathEnd, int importKwStart, int importKwEnd, int starPos, boolean isWildcard) {
this.fullPath = fullPath;
this.matchText = matchText;
this.pathStart = pathStart;
this.pathEnd = pathEnd;
this.importKwStart = importKwStart;
this.importKwEnd = importKwEnd;
this.starPos = starPos;
this.isWildcard = isWildcard;
}
}
private void collectImports() {
importedClasses.clear();
importedPackages.clear();
importEntries.clear();
unresolvedClasses.clear();
classPathFinder.clearCache();
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
Matcher m = IMPORT.matcher(text);
while (m.find()) {
if (isInExcludedRange(m.start(), excluded))
continue;
String fullPath = m.group(1).trim();
String matchText = m.group(0);
int pathStart = m.start(1);
int pathEnd = m.end(1);
int importKwStart = m.start();
int importKwEnd = Math.min(importKwStart + 6, text.length());
boolean isWildcard = matchText.contains("*");
int starIndex = matchText.indexOf('*');
int absStar = starIndex != -1 ? m.start() + starIndex : -1;
// Record entry for finalization later
importEntries.add(new ImportEntry(fullPath, matchText, pathStart, pathEnd, importKwStart, importKwEnd, absStar, isWildcard));
// For wildcard imports we register the package for resolution; final marking deferred
if (isWildcard) {
importedPackages.add(fullPath);
} else {
// Resolve the import to get the proper class name (so simple-name lookups can work now)
ClassPathFinder.ResolveResult result = classPathFinder.resolve(fullPath);
// Extract simple name (last segment)
int lastDot = fullPath.lastIndexOf('.');
String simpleName = lastDot >= 0 ? fullPath.substring(lastDot + 1) : fullPath;
if (!simpleName.isEmpty()) {
if (result.found && result.classInfo != null) {
// Store with resolved name (has $ for inner classes)
importedClasses.put(simpleName, result.classInfo.resolvedName);
} else {
// Store original path for unresolved imports
importedClasses.put(simpleName, fullPath);
// Track this as an unresolved class
unresolvedClasses.add(simpleName);
}
}
// Cache the full ResolveResult on the ImportEntry for reuse in finalizeImports
ImportEntry last = importEntries.get(importEntries.size() - 1);
last.resolveResult = result;
}
}
}
/**
* Parse and highlight generic type parameters using ClassPathFinder.
* Handles arbitrarily nested generics like "Map<String, List<Map<String, String>>>".
*/
private void highlightGenericTypes(String genericContent, int contentStart, List<Mark> marks, List<int[]> excluded) {
if (genericContent == null || genericContent.isEmpty()) return;
List<ClassPathFinder.TypeOccurrence> occurrences = classPathFinder.parseGenericTypes(genericContent, importedClasses, importedPackages);
for (ClassPathFinder.TypeOccurrence occ : occurrences) {
int absStart = contentStart + occ.startOffset;
int absEnd = contentStart + occ.endOffset;
if (!isInExcludedRange(absStart, excluded)) {
TokenType tokenType;
switch (occ.type) {
case INTERFACE:
tokenType = TokenType.INTERFACE_DECL;
break;
case ENUM:
tokenType = TokenType.ENUM_DECL;
break;
default:
tokenType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(absStart, absEnd, tokenType));
}
}
}
private void collectFields() {
globalFields.clear();
localFields.clear();
methodBlocks.clear();
// Extract method blocks first
methodBlocks = MethodBlock.collectMethodBlocks(text);
// Get excluded ranges (strings and comments) for the entire text
List<int[]> excludedRanges = MethodBlock.getExcludedRanges(text);
// Global fields (excluding those inside methods, strings, and comments)
Matcher mGlobal = GLOBAL_FIELD_DECL.matcher(text);
while (mGlobal.find()) {
String varName = mGlobal.group(2);
int varPosition = mGlobal.start(2);
// Skip if inside a string or comment
if (isInExcludedRange(varPosition, excludedRanges)) {
continue;
}
// Check if this variable is inside a method
boolean isInsideMethod = false;
for (MethodBlock block : methodBlocks) {
if (block.containsPosition(varPosition)) {
isInsideMethod = true;
break;
}
}
// Only add as global if it's not inside any method
if (!isInsideMethod) {
globalFields.add(varName);
}
}
// Extract local variables from each method block
for (MethodBlock block : methodBlocks) {
// localVariables are already extracted in MethodBlock constructor
for (String var : block.localVariables) {
if (!globalFields.contains(var) && !localFields.contains(var)) {
localFields.add(var);
}
}
}
}
// Find which method block contains a given position
private MethodBlock findMethodBlockAtPosition(int position) {
for (MethodBlock block : methodBlocks) {
if (block.containsPosition(position)) {
return block;
}
}
return null;
}
private void highlightVariableReferences(List<Mark> marks) {
// Known Java keywords and types that shouldn't be flagged as undefined
java.util.Set<String> knownIdentifiers = new java.util.HashSet<>(java.util.Arrays.asList(
// Primitive types
"boolean", "int", "float", "double", "long", "char", "byte", "short", "void",
// Keywords
"null", "true", "false", "if", "else", "switch", "case", "for", "while", "do",
"try", "catch", "finally", "return", "throw", "var", "let", "const", "function",
"continue", "break", "this", "new", "typeof", "instanceof", "class", "interface",
"extends", "implements", "import", "package", "public", "private", "protected",
"static", "final", "abstract", "synchronized", "native", "default", "enum",
"throws", "super", "assert", "volatile", "transient", "strictfp", "goto",
// Common JS/scripting keywords
"undefined", "NaN", "Infinity", "arguments", "prototype", "constructor",
// Common types (first letter uppercase pattern handles most)
"String", "Object", "Array", "Math", "System", "Integer", "Double", "Float",
"Boolean", "Long", "Byte", "Short", "Character", "List", "Map", "Set"
));
// First pass: handle field accesses (this.field and obj.field patterns)
Pattern thisFieldPattern = Pattern.compile("\\bthis\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)");
Matcher thisFieldMatcher = thisFieldPattern.matcher(text);
while (thisFieldMatcher.find()) {
String fieldName = thisFieldMatcher.group(1);
int fieldPos = thisFieldMatcher.start(1);
// Highlight as GLOBAL_FIELD if it exists, UNDEFINED_VAR otherwise
if (globalFields.contains(fieldName)) {
marks.add(new Mark(fieldPos, thisFieldMatcher.end(1), TokenType.GLOBAL_FIELD));
} else {
marks.add(new Mark(fieldPos, thisFieldMatcher.end(1), TokenType.UNDEFINED_VAR));
}
}
// Handle identifier.field patterns (e.g., obj.field, global.field)
// The field part should be highlighted as GLOBAL_FIELD (light blue)
// Also, detect chained accesses like `a.b.c` and treat subsequent segments
// as fields when the root `a` is a known variable (parameter/local/global/this).
// Collect function parameters from JS-style `function name(a, b)` declarations
// so script parameters (e.g., `function tick(e)`) are recognized as known roots.
java.util.Set<String> scriptFunctionParams = new java.util.HashSet<>();
Pattern funcPattern = Pattern.compile("\\bfunction\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*\\(([^)]*)\\)");
Matcher funcM = funcPattern.matcher(text);
while (funcM.find()) {
String inside = funcM.group(1);
if (inside != null && !inside.trim().isEmpty()) {
for (String p : inside.split(",")) {
String pn = p.trim();
if (!pn.isEmpty()) scriptFunctionParams.add(pn);
}
}
}
Pattern chainPattern = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*(?:\\s*\\.\\s*[a-zA-Z_][a-zA-Z0-9_]*)+)\\b");
Matcher chainMatcher = chainPattern.matcher(text);
while (chainMatcher.find()) {
if (isInExcludedRange(chainMatcher.start(), MethodBlock.getExcludedRanges(text))) continue;
String chain = chainMatcher.group(1);
int absStart = chainMatcher.start(1);
java.util.List<String> segs = new java.util.ArrayList<>();
java.util.List<Integer> segPos = new java.util.ArrayList<>();
Matcher segM = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*").matcher(chain);
while (segM.find()) {
segs.add(segM.group());
segPos.add(absStart + segM.start());
}
if (segs.size() < 2) continue;
String root = segs.get(0);
if (Character.isUpperCase(root.charAt(0))) continue;
boolean rootIsKnown = false;
if (globalFields.contains(root) || localFields.contains(root)) rootIsKnown = true;
MethodBlock mbForRoot = findMethodBlockAtPosition(segPos.get(0));
if (mbForRoot != null && mbForRoot.parameters.contains(root)) rootIsKnown = true;
if (scriptFunctionParams.contains(root)) rootIsKnown = true;
if ("this".equals(root)) rootIsKnown = true;
if (rootIsKnown) {
for (int si = 1; si < segs.size(); si++) {
int sAbs = segPos.get(si);
int sEnd = sAbs + segs.get(si).length();
marks.add(new Mark(sAbs, sEnd, TokenType.GLOBAL_FIELD));
}
}
}
// Fallback: simple two-part identifier.field patterns
Pattern objFieldPattern = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)");
Matcher objFieldMatcher = objFieldPattern.matcher(text);
while (objFieldMatcher.find()) {
String fieldName = objFieldMatcher.group(2);
int fieldPos = objFieldMatcher.start(2);
String objName = objFieldMatcher.group(1);
if (!objName.equals("this")) {
marks.add(new Mark(fieldPos, objFieldMatcher.end(2), TokenType.GLOBAL_FIELD));
}
}
Pattern identifier = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b");
Matcher m = identifier.matcher(text);
while (m.find()) {
String name = m.group(1);
int position = m.start(1);
// Skip known keywords
if (knownIdentifiers.contains(name)) continue;
// Skip field access (identifier preceded by a dot) - these should be gray/default
if (isFieldAccess(position)) continue;
// Never treat parts of import/package statements as undefined variables
if (isInImportOrPackageStatement(position)) continue;
// Check if inside a method
MethodBlock methodBlock = findMethodBlockAtPosition(position);
if (methodBlock != null) {
// Inside a method - first check parameters, locals, and globals (respecting registrations)
if (methodBlock.parameters.contains(name)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.PARAMETER));
continue;
}
if (methodBlock.isLocalDeclaredAtPosition(name, position) || localFields.contains(name)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.LOCAL_FIELD));
continue;
}
if (globalFields.contains(name)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD));
continue;
}
// If it's an uppercase identifier that hasn't been registered as a local/param/global,
// treat it as a type reference (skip) rather than an undefined variable.
if (Character.isUpperCase(name.charAt(0))) continue;
// Unknown variable - mark as undefined but only if it's not a method call or type reference
if (!isMethodCall(position) && !isTypeReference(name, position)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.UNDEFINED_VAR));
}
} else {
// Outside any method - check global fields first
if (globalFields.contains(name) || localFields.contains(name)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD));
continue;
}
// Uppercase unregistered identifiers are likely type names; skip them
if (Character.isUpperCase(name.charAt(0))) continue;
if (!isMethodCall(position) && !isTypeReference(name, position)) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.UNDEFINED_VAR));
}
}
}
}
private boolean isInImportOrPackageStatement(int position) {
if (position < 0 || position >= text.length()) return false;
int lineStart = text.lastIndexOf('\n', position);
lineStart = (lineStart < 0) ? 0 : lineStart + 1;
int lineEnd = text.indexOf('\n', position);
lineEnd = (lineEnd < 0) ? text.length() : lineEnd;
// Quick scan of the line start for "import" or "package"
int i = lineStart;
while (i < lineEnd && Character.isWhitespace(text.charAt(i))) i++;
if (i + 6 <= lineEnd && text.startsWith("import", i)) {
// Ensure word boundary
int after = i + 6;
return after == lineEnd || Character.isWhitespace(text.charAt(after));
}
if (i + 7 <= lineEnd && text.startsWith("package", i)) {
int after = i + 7;
return after == lineEnd || Character.isWhitespace(text.charAt(after));
}
return false;
}
/**
* Check if the identifier at this position is a field access (preceded by a dot)
* e.g., in "obj.field", the "field" part is a field access
*/
private boolean isFieldAccess(int position) {
if (position <= 0) return false;
// Look backwards from position, skipping any whitespace
int i = position - 1;
while (i >= 0 && Character.isWhitespace(text.charAt(i))) {
i--;
}
// Check if preceded by a dot
return i >= 0 && text.charAt(i) == '.';
}
/**
* Check if the identifier at this position is a method call (followed by parenthesis)
*/
private boolean isMethodCall(int position) {
// Skip whitespace after identifier
int i = position;
// Note: parentheses needed to avoid evaluating text.charAt(i) when i >= text.length()
while (i < text.length() && (Character.isLetterOrDigit(text.charAt(i)) || text.charAt(i) == '_')) {
i++;
}
// Skip whitespace
while (i < text.length() && Character.isWhitespace(text.charAt(i))) {
i++;
}
// Check for opening paren
return i < text.length() && text.charAt(i) == '(';
}
/**
* Check if this looks like a type reference (e.g., part of a declaration or generic)
* But NOT a comparison like "i < container" which uses < as less-than operator
*/
private boolean isTypeReference(String name, int position) {
// Check if preceded by 'new '
if (position > 4) {
String before = text.substring(Math.max(0, position - 5), position);
if (before.endsWith("new ")) {
return true;
}
}
// Check if preceded by < but make sure it's a generic, not a comparison
// Generic: Type<Name or ,Name in generics
// Comparison: value < name (space before < means comparison)
if (position > 1) {
int checkPos = position - 1;
// Skip whitespace
while (checkPos > 0 && Character.isWhitespace(text.charAt(checkPos))) {
checkPos--;
}
if (checkPos >= 0 && text.charAt(checkPos) == '<') {
// Check what's before the <
int beforeLt = checkPos - 1;
while (beforeLt >= 0 && Character.isWhitespace(text.charAt(beforeLt))) {
beforeLt--;
}
if (beforeLt >= 0) {
char beforeChar = text.charAt(beforeLt);
// If it's a letter/digit/underscore (identifier) or ) followed by space + <, it's a comparison
// If it's a type name directly followed by <, it's a generic
// Check if there was whitespace between the identifier and <
boolean hasSpaceBeforeLt = (checkPos > 0 && Character.isWhitespace(text.charAt(checkPos - 1)));
if (hasSpaceBeforeLt && (Character.isLetterOrDigit(beforeChar) || beforeChar == '_' || beforeChar == ')')) {
// This is a comparison like "i < container" or "(x + 1) < y"
return false;
}
// Otherwise it's likely a generic like List<String>
if (Character.isLetter(beforeChar) || beforeChar == '>') {
return true;
}
}
}
// Check for comma in generics like Map<K, V>
if (checkPos >= 0 && text.charAt(checkPos) == ',') {
return true;
}
}
return false;
}
/**
* Check if position is in an excluded range (string or comment)
*/
private boolean isInExcludedRange(int pos, List<int[]> ranges) {
for (int[] range : ranges) {
if (pos >= range[0] && pos < range[1]) {
return true;
}
}
return false;
}
private void finalizeImports(List<Mark> marks) {
if (importEntries.isEmpty()) return;
for (ImportEntry ie : importEntries) {
// Highlight the 'import' keyword
marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.IMPORT_KEYWORD));
String fullPath = ie.fullPath;
int pathStart = ie.pathStart;
int pathEnd = ie.pathEnd;
String matchText = ie.matchText;
if (!ie.isWildcard) {
// Non-wildcard: reuse cached resolve result if available, otherwise resolve now
ClassPathFinder.ResolveResult result = classPathFinder.resolve(fullPath);
String orig = text.substring(pathStart, pathEnd);
List<String> tokens = new ArrayList<>();
List<Integer> tokenStarts = new ArrayList<>();
List<Integer> tokenEnds = new ArrayList<>();
Matcher idm = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*").matcher(orig);
while (idm.find()) {
tokens.add(idm.group());
tokenStarts.add(idm.start());
tokenEnds.add(idm.end());
}
int pkgSegments = result.packageSegmentCount;
boolean hasPackage = pkgSegments > 0;
if (result.found && result.invalidStartOffset < 0) {
if (hasPackage && pkgSegments <= tokenEnds.size()) {
int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1);
marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL));
}
if (result.classSegments != null && !result.classSegments.isEmpty()) {
int classTokenStart = hasPackage ? pkgSegments : 0;
for (int si = 0; si < result.classSegments.size(); si++) {
int tokIdx = classTokenStart + si;
if (tokIdx >= 0 && tokIdx < tokenStarts.size()) {
int s = pathStart + tokenStarts.get(tokIdx);
int e = pathStart + tokenEnds.get(tokIdx);
ClassPathFinder.ClassSegment seg = result.classSegments.get(si);
TokenType segType;
switch (seg.type) {
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(s, e, segType));
}
}
}
} else if (result.classSegments != null && !result.classSegments.isEmpty()) {
if (hasPackage && pkgSegments <= tokenEnds.size()) {
int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1);
marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL));
}
int classTokenStart = hasPackage ? pkgSegments : 0;
for (int si = 0; si < result.classSegments.size(); si++) {
int tokIdx = classTokenStart + si;
if (tokIdx >= 0 && tokIdx < tokenStarts.size()) {
int s = pathStart + tokenStarts.get(tokIdx);
int e = pathStart + tokenEnds.get(tokIdx);
ClassPathFinder.ClassSegment seg = result.classSegments.get(si);
TokenType segType;
switch (seg.type) {
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(s, e, segType));
}
}
if (result.invalidStartOffset >= 0) {
int invalidAbs = mapNormalizedOffsetToOriginal(orig, result.invalidStartOffset, pathStart);
if (invalidAbs < pathEnd) {
marks.add(new Mark(invalidAbs, pathEnd, TokenType.UNDEFINED_VAR));
}
}
} else {
if (result.invalidStartOffset >= 0 && hasPackage) {
if (pkgSegments <= tokenEnds.size()) {
int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1);
marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL));
}
int invalidAbs = mapNormalizedOffsetToOriginal(orig, result.invalidStartOffset, pathStart);
if (invalidAbs < pathEnd) {
marks.add(new Mark(invalidAbs, pathEnd, TokenType.UNDEFINED_VAR));
}
} else if (fullPath.endsWith(".") && hasPackage && result.invalidStartOffset < 0) {
marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL));
} else if (result.invalidStartOffset < 0 && hasPackage) {
marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL));
} else {
marks.add(new Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR));
}
}
// Highlight .* if present (shouldn't for non-wildcard, but keep behavior)
int starIndex = matchText.indexOf('*');
if (starIndex != -1) {
int absStar = ie.importKwStart + (starIndex - 0);
marks.add(new Mark(absStar, absStar + 1, TokenType.DEFAULT));
}
} else {
// Wildcard import: try to determine whether this is a valid package or
// a class whose inner types are being imported (Outer.*)
boolean marked = false;
// If package is known valid, mark as package
if (classPathFinder.isValidPackage(fullPath)) {
marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL));
marked = true;
} else {
// Probe uppercase identifiers in file to see if any inner types resolve
java.util.Set<String> uppercaseIds = new java.util.HashSet<>();
Matcher idm = Pattern.compile("\\b([A-Z][a-zA-Z0-9_]*)\\b").matcher(text);
while (idm.find()) uppercaseIds.add(idm.group(1));
for (String ident : uppercaseIds) {
String candInner = fullPath + "$" + ident;
ClassPathFinder.ClassInfo infoInner = classPathFinder.tryResolveClassName(candInner);
if (infoInner != null) {
// outer may be a class - try to get its info
ClassPathFinder.ClassInfo outerInfo = classPathFinder.tryResolveClassName(fullPath);
// mark package tokens (all but last) as TYPE_DECL and last as outer type
String orig = text.substring(pathStart, pathEnd);
List<String> tokens = new ArrayList<>();
List<Integer> tokenStarts = new ArrayList<>();
List<Integer> tokenEnds = new ArrayList<>();
Matcher tokm = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*").matcher(orig);
while (tokm.find()) {
tokens.add(tokm.group());
tokenStarts.add(tokm.start());
tokenEnds.add(tokm.end());
}
int tokenCount = tokenStarts.size();
if (tokenCount > 0) {
int pkgEnd = pathStart + (tokenEnds.get(Math.max(0, tokenCount - 2)));
if (tokenCount >= 2) {
// mark package (all except last)
marks.add(new Mark(pathStart, pathStart + tokenEnds.get(tokenCount - 2), TokenType.TYPE_DECL));
}
// mark outer class token (last)
int s = pathStart + tokenStarts.get(tokenCount - 1);
int e = pathStart + tokenEnds.get(tokenCount - 1);
TokenType segType = TokenType.IMPORTED_CLASS;
if (outerInfo != null) {
switch (outerInfo.type) {
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
}
marks.add(new Mark(s, e, segType));
}
marked = true;
// ensure package listed in importedPackages
importedPackages.add(fullPath);
break;
}
// Try package-like resolution: fullPath + "." + ident
String candDot = fullPath + "." + ident;
if (classPathFinder.tryResolveClassName(candDot) != null) {
marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL));
marked = true;
importedPackages.add(fullPath);
break;
}
}
}
if (!marked) {
// Unknown wildcard import - mark as undefined
marks.add(new Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR));
}
// highlight star
if (ie.starPos >= 0) marks.add(new Mark(ie.starPos, ie.starPos + 1, TokenType.DEFAULT));
}
}
}
private void collectImportedClassUsages(List<Mark> marks) {
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
// Find identifiers followed by dot (e.g., Math.min, ArrayList.class)
Pattern classUsage = Pattern.compile("\\b([A-Z][a-zA-Z0-9_]*)\\s*\\.");
Matcher m = classUsage.matcher(text);
while (m.find()) {
String className = m.group(1);
int start = m.start(1);
int end = m.end(1);
if (isInExcludedRange(start, excluded))
continue;
// Check if this class was imported but failed to resolve
if (unresolvedClasses.contains(className)) {
marks.add(new Mark(start, end, TokenType.UNDEFINED_VAR));
continue;
}
// Check if this is an imported class, wildcard match, or java.lang class
boolean isImported = importedClasses.containsKey(className) || ClassPathFinder.JAVA_LANG_CLASSES.contains(className);
if (!isImported && !importedPackages.isEmpty()) {
isImported = true; // Wildcard import present
}
// Also skip if it's a local/global field or parameter (avoid false positives)
MethodBlock block = findMethodBlockAtPosition(start);
boolean isShadowed = globalFields.contains(className) || localFields.contains(className);
if (block != null) {
isShadowed = isShadowed || block.parameters.contains(className) || block.isLocalDeclaredAtPosition(
className, start);
}
if (isImported && !isShadowed) {
// Resolve the class to determine its type
ClassPathFinder.ClassInfo info = classPathFinder.resolveSimpleName(className, importedClasses, importedPackages);
TokenType tokenType = TokenType.IMPORTED_CLASS;
if (info != null) {
switch (info.type) {
case INTERFACE:
tokenType = TokenType.INTERFACE_DECL;
break;
case ENUM:
tokenType = TokenType.ENUM_DECL;
break;
}
}
marks.add(new Mark(start, end, tokenType));
} else if (!isImported && !isShadowed) {
marks.add(new Mark(start, end, TokenType.UNDEFINED_VAR));
}
}
}
private void collectClassDeclarations(List<Mark> marks) {
Matcher m = CLASS_DECL.matcher(text);
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
while (m.find()) {
marks.add(new Mark(m.start(1), m.end(1), TokenType.CLASS_KEYWORD));
int nameStart = m.start(2);
int nameEnd = m.end(2);
if (isInExcludedRange(nameStart, excluded))
continue;
String kind = m.group(1);
if ("interface".equals(kind)) {
marks.add(new Mark(nameStart, nameEnd, TokenType.INTERFACE_DECL));
} else if ("enum".equals(kind)) {
marks.add(new Mark(nameStart, nameEnd, TokenType.ENUM_DECL));
} else {
marks.add(new Mark(nameStart, nameEnd, TokenType.CLASS_DECL));
}
}
}
public void formatCodeText() {
// Step 1: Tokenize the full text
List<Mark> marks = new ArrayList<>();
collectImports(); // Parse import statements first
collectFields(); // Extract global and local fields with method scoping
collectPatternMatches(marks, COMMENT, TokenType.COMMENT);
collectPatternMatches(marks, STRING, TokenType.STRING);
// Import marking is deferred until after type/usages are discovered.
// finalizeImports(marks) will create import marks later.
collectClassDeclarations(marks); // Highlight class/interface/enum declarations
// Highlight general keywords
collectPatternMatches(marks, KEYWORD, TokenType.KEYWORD);
collectPatternMatches(marks, MODIFIER, TokenType.MODIFIER);
collectTypeDeclarations(marks);
collectPatternMatches(marks, NEW_TYPE, TokenType.NEW_TYPE, 1);
collectMethodDeclarations(marks);
collectPatternMatches(marks, METHOD_CALL, TokenType.METHOD_CALL, 1);
collectPatternMatches(marks, NUMBER, TokenType.NUMBER);
highlightVariableReferences(marks);
collectImportedClassUsages(marks); // Highlight imported class usages (e.g., Math.min)
// Finalize import markings after usages/types have been discovered
finalizeImports(marks);
marks = resolveConflicts(marks);
// Compute indent guides based on matched braces, ignoring strings/comments
computeIndentGuides(marks);
// Step 2: Clear existing tokens
for (LineData line : lines) {
line.tokens.clear();
}
// Step 3: Assign tokens to the correct lines
for (LineData line : lines) {
int cursor = line.start;
// collectImportStatements used to create marks here; we now defer marking until types/usages are discovered
// so finalizeImports will create the visual marks from recorded import entries.
for (Mark mark : marks) {
if (mark.end <= line.start || mark.start >= line.end)
continue;
int tokenStart = Math.max(mark.start, line.start);
int tokenEnd = Math.min(mark.end, line.end);
tokenStart = Math.max(0, Math.min(tokenStart, text.length()));
tokenEnd = Math.max(0, Math.min(tokenEnd, text.length()));
// plain text before token
if (cursor < tokenStart) {
int end = Math.min(tokenStart, text.length());
line.tokens.add(
new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end));
}
// token text
if (tokenStart < tokenEnd) {
line.tokens.add(new Token(text.substring(tokenStart, Math.min(tokenEnd, text.length())), mark.type, tokenStart, Math.min(tokenEnd, text.length())));
}
cursor = tokenEnd;
}
// trailing plain text
if (cursor < line.end) {
int end = Math.min(line.end, text.length());
line.tokens.add(new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end));
}
}
}
private void collectMethodDeclarations(List<Mark> marks) {
Matcher m = METHOD_DECL.matcher(text);
while (m.find()) { // method name
marks.add(new Mark(m.start(2), m.end(2), TokenType.METHOD_DECARE));
// return type
marks.add(new Mark(m.start(1), m.end(1), TokenType.TYPE_DECL));
}
}
private void collectTypeDeclarations(List<Mark> marks) {
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
// Pattern to find type declarations: Type<...> variableName or Type variableName
// We'll manually parse the generic portion to handle arbitrary nesting
Pattern typeStart = Pattern.compile(
"(?:(?:public|private|protected|static|final|transient|volatile)\\s+)*" +
"([A-Z][a-zA-Z0-9_]*)\\s*" // Group 1 → type name (must start with uppercase)
);
for (LineData ld : lines) {
int lineStart = ld.start;
int lineEnd = ld.end;
if (lineStart >= lineEnd) continue;
String s = ld.text;
Matcher m = typeStart.matcher(s);
int searchFrom = 0;
while (m.find(searchFrom)) {
int typeNameStart = lineStart + m.start(1);
int typeNameEnd = lineStart + m.end(1);
// Skip if in excluded range
boolean skip = false;
for (int[] r : excluded) {
if (typeNameStart < r[1] && typeNameEnd > r[0]) {
skip = true;
break;
}
}
if (skip) {
searchFrom = m.end();
continue;
}
String typeName = m.group(1);
int posAfterType = m.end(1);
// Skip whitespace after type name
while (posAfterType < s.length() && Character.isWhitespace(s.charAt(posAfterType))) {
posAfterType++;
}
// Check for generic parameters
String genericContent = null;
int genericStart = -1;
int genericEnd = -1;
if (posAfterType < s.length() && s.charAt(posAfterType) == '<') {
genericStart = posAfterType;
int depth = 1;
int i = posAfterType + 1;
while (i < s.length() && depth > 0) {
char c = s.charAt(i);
if (c == '<') depth++;
else if (c == '>') depth--;
i++;