-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNaturalArray.java
More file actions
1790 lines (1500 loc) · 60.8 KB
/
Copy pathNaturalArray.java
File metadata and controls
1790 lines (1500 loc) · 60.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 cod.range;
import cod.ast.node.*;
import cod.error.InternalError;
import cod.error.ProgramError;
import cod.interpreter.Evaluator;
import cod.interpreter.context.ExecutionContext;
import cod.interpreter.handler.TypeHandler;
import cod.math.AutoStackingNumber;
import cod.range.formula.*;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class NaturalArray {
private final Range baseRange;
private final Evaluator evaluator;
private ExecutionContext context;
private Map<Long, Object> cache;
private boolean isMutable = false;
// Element type and type handler
private final String elementType;
private final TypeHandler typeHandler;
// Conversion support for [text] = [int range]
private boolean convertToString = false;
private String targetElementType = null;
// Cached values as AutoStackingNumber
private AutoStackingNumber cachedStart = null;
private AutoStackingNumber cachedEnd = null;
private AutoStackingNumber cachedStep = null;
private Long cachedSize = null;
// Recent index cache for sequential access
private static final int RECENT_CACHE_SIZE = 64;
private Object[] recentCache = new Object[RECENT_CACHE_SIZE];
private long recentCacheStart = -1;
private boolean recentCacheValid = false;
private boolean isLexicographicalRange = false;
private String startString = null;
private String endString = null;
// Lex range indices
private long startIndex = 0;
private long endIndex = 0;
private long maxIndex = 0;
private boolean isUp = true;
// Single-element cache
private transient Long lastIndex = null;
private transient Object lastValue = null;
private static final long[] POWERS_26 = new long[11];
private static final long[] POWERS_2 = new long[11];
private static final long[] TOTAL_UP_TO_LENGTH = new long[11];
// Formula collections
private List<SequenceFormula> sequenceFormulas = new ArrayList<SequenceFormula>();
private List<ConditionalFormula> conditionalFormulas = new ArrayList<ConditionalFormula>();
private List<LinearRecurrenceFormula> linearRecurrenceFormulas = new ArrayList<LinearRecurrenceFormula>();
private List<VectorRecurrenceBinding> vectorRecurrenceFormulas = new ArrayList<VectorRecurrenceBinding>();
private Map<Long, Object> computedCache = new HashMap<Long, Object>();
// Pending updates for lazy assignment
private List<PendingRangeUpdate> pendingUpdates = new ArrayList<PendingRangeUpdate>();
private boolean hasPendingUpdates = false;
// Output cache
private Map<Long, List<Object>> outputCache = new HashMap<Long, List<Object>>();
private boolean hasOutputs = false;
// ========== ARRAY TRACKING FIELDS ==========
private final int arrayId;
private static final AtomicInteger nextArrayId = new AtomicInteger(1);
private boolean tracked = false;
static {
POWERS_26[0] = 1;
POWERS_2[0] = 1;
for (int i = 1; i <= 10; i++) {
POWERS_26[i] = POWERS_26[i - 1] * 26;
POWERS_2[i] = POWERS_2[i - 1] * 2;
}
TOTAL_UP_TO_LENGTH[0] = 0;
for (int len = 1; len <= 10; len++) {
TOTAL_UP_TO_LENGTH[len] = TOTAL_UP_TO_LENGTH[len - 1] + POWERS_2[len] * POWERS_26[len];
}
}
// ========== PROCESSED RANGE CLASS ==========
/**
* Immutable, pre-processed range with all values converted to longs
* Created ONCE, used everywhere
*/
public static class ProcessedRange {
public final long start;
public final long end;
public final long step;
public final boolean valid;
public final String error; // For debugging
public ProcessedRange(Object range) {
long s = 0, e = 0, st = 0;
boolean ok = true;
String err = null;
try {
s = toLongIndex(RangeObjects.getStart(range));
e = toLongIndex(RangeObjects.getEnd(range));
st = calculateStep(range);
} catch (Exception ex) {
ok = false;
err = ex.getMessage();
}
this.start = s;
this.end = e;
this.step = st;
this.valid = ok;
this.error = err;
}
public ProcessedRange(long start, long end, long step) {
this.start = start;
this.end = end;
this.step = step;
this.valid = true;
this.error = null;
}
public ProcessedRange(Object start, Object end, Object step) {
long s = 0, e = 0, st = 0;
boolean ok = true;
String err = null;
try {
s = toLongIndex(start);
e = toLongIndex(end);
if (step != null) {
st = toLongIndex(step);
} else {
st = (s < e) ? 1L : -1L;
}
} catch (Exception ex) {
ok = false;
err = ex.getMessage();
}
this.start = s;
this.end = e;
this.step = st;
this.valid = ok;
this.error = err;
}
// Helper methods using pre-processed values
public boolean contains(long index) {
if (!valid) return false;
if (step > 0) {
return index >= start && index <= end &&
(index - start) % step == 0;
} else {
return index <= start && index >= end &&
(start - index) % Math.abs(step) == 0;
}
}
public long size() {
if (!valid) return 0;
if (step == 0) return 0;
if (step > 0) {
return ((end - start) / step) + 1;
}
return ((start - end) / Math.abs(step)) + 1;
}
public long indexAt(long offset) {
if (!valid) return -1;
if (offset < 0 || offset >= size()) return -1;
if (step > 0) {
return start + (offset * step);
}
return start - (offset * Math.abs(step));
}
public boolean isAdjacent(ProcessedRange other) {
if (!valid || !other.valid) return false;
if (step != other.step) return false;
if (step > 0) {
return end + step == other.start;
}
return end + step == other.start; // For negative step, end < start
}
public ProcessedRange merge(ProcessedRange other) {
if (!isAdjacent(other)) {
throw new IllegalArgumentException("Ranges are not adjacent");
}
long newEnd = (step > 0) ? Math.max(end, other.end) : Math.min(end, other.end);
return new ProcessedRange(start, newEnd, step);
}
}
// ========== PENDING UPDATE CLASS ==========
private static class PendingRangeUpdate implements Comparable<PendingRangeUpdate> {
final ProcessedRange range;
final Object value;
PendingRangeUpdate(Object spec, Object value) {
this.range = new ProcessedRange(spec); // Process ONCE
this.value = value;
}
PendingRangeUpdate(ProcessedRange range, Object value) {
this.range = range;
this.value = value;
}
boolean contains(long index) {
return range.contains(index);
}
@Override
public int compareTo(PendingRangeUpdate other) {
if (this.range.start < other.range.start) return -1;
if (this.range.start > other.range.start) return 1;
return 0;
}
}
private static class VectorRecurrenceBinding {
final VectorRecurrenceFormula formula;
final int sequenceIndex;
VectorRecurrenceBinding(VectorRecurrenceFormula formula, int sequenceIndex) {
this.formula = formula;
this.sequenceIndex = sequenceIndex;
}
}
// ========== CONSTRUCTORS ==========
public NaturalArray(Range range, Evaluator evaluator, ExecutionContext context) {
if (range == null) {
throw new InternalError("NaturalArray constructed with null range");
}
if (evaluator == null) {
throw new InternalError("NaturalArray constructed with null evaluator");
}
if (context == null) {
throw new InternalError("NaturalArray constructed with null context");
}
this.baseRange = range;
this.evaluator = evaluator;
this.context = context;
// Get type handler and element type from context
this.typeHandler = context.getTypeHandler();
if (this.typeHandler == null) {
throw new InternalError("NaturalArray constructed with context that has null typeHandler");
}
// ========== ARRAY TRACKING INITIALIZATION ==========
this.arrayId = nextArrayId.getAndIncrement();
this.tracked = false;
// Determine element type from range
this.elementType = determineElementType();
this.cache = null;
this.isMutable = false;
this.maxIndex = TOTAL_UP_TO_LENGTH[10] - 1;
// Initialize recent cache
clearRecentCache();
Object rawStart = evaluator.evaluate(baseRange.start, context);
Object rawEnd = evaluator.evaluate(baseRange.end, context);
if (rawStart instanceof String && rawEnd instanceof String) {
// LEXICOGRAPHICAL RANGE
this.isLexicographicalRange = true;
this.startString = (String) rawStart;
this.endString = (String) rawEnd;
if (!isValidLexString(startString) || !isValidLexString(endString)) {
throw new ProgramError(
"Lexicographical range bounds must contain only letters (a-z, A-Z). " +
"Got: '" + startString + "' to '" + endString + "'"
);
}
this.startIndex = hierarchicalSequenceToIndex(startString);
this.endIndex = hierarchicalSequenceToIndex(endString);
if (startIndex <= endIndex) {
this.isUp = true;
if (baseRange.step == null) {
this.cachedStep = AutoStackingNumber.one(1);
} else {
Object stepObj = evaluator.evaluate(baseRange.step, context);
AutoStackingNumber stepNum = typeHandler.toAutoStackingNumber(stepObj);
if (stepNum.compareTo(AutoStackingNumber.zero(1)) <= 0) {
throw new ProgramError("Step must be positive for forward lex range");
}
this.cachedStep = stepNum;
}
} else {
this.isUp = false;
if (baseRange.step == null) {
this.cachedStep = AutoStackingNumber.minusOne(1);
} else {
Object stepObj = evaluator.evaluate(baseRange.step, context);
AutoStackingNumber stepNum = typeHandler.toAutoStackingNumber(stepObj);
if (stepNum.compareTo(AutoStackingNumber.zero(1)) >= 0) {
throw new ProgramError("Step must be negative for reverse lex range");
}
this.cachedStep = stepNum;
}
}
this.cachedStart = AutoStackingNumber.fromLong(startIndex);
this.cachedEnd = AutoStackingNumber.fromLong(endIndex);
} else {
this.isLexicographicalRange = false;
// Convert to AutoStackingNumber
this.cachedStart = typeHandler.toAutoStackingNumber(rawStart);
this.cachedEnd = typeHandler.toAutoStackingNumber(rawEnd);
// Validate that start/end match element type
validateRangeBound(cachedStart, "start");
validateRangeBound(cachedEnd, "end");
if (baseRange.step != null) {
Object stepObj = evaluator.evaluate(baseRange.step, context);
this.cachedStep = typeHandler.toAutoStackingNumber(stepObj);
}
}
// ========== REGISTER WITH TRACKER IF IN A LOOP ==========
if (ArrayTracker.getCurrentLoopId() != 0) {
ArrayTracker.registerArray(this);
this.tracked = true;
}
}
// Constructor with target type for conversion
public NaturalArray(Range range, Evaluator evaluator, ExecutionContext context, String targetType) {
this(range, evaluator, context);
// arrayId already set by main constructor
// If target type is [text] but actual type is not text, mark for conversion
if (targetType != null && targetType.startsWith("[") && targetType.endsWith("]")) {
String expectedElementType = targetType.substring(1, targetType.length() - 1);
if (expectedElementType.equals("text") && !this.elementType.equals("text")) {
this.convertToString = true;
this.targetElementType = expectedElementType;
// Force size recalculation with correct element type
this.cachedSize = null;
this.cachedStart = null;
this.cachedEnd = null;
this.cachedStep = null;
}
}
}
// ========== ARRAY TRACKING METHODS ==========
/**
* Get the unique integer ID of this array
*/
public int getArrayId() {
return arrayId;
}
/**
* Check if this array is being tracked
*/
public boolean isTracked() {
return tracked;
}
/**
* Enable tracking for this array
*/
public void enableTracking() {
if (!tracked) {
tracked = true;
if (ArrayTracker.getCurrentLoopId() != 0) {
ArrayTracker.registerArray(this);
}
}
}
/**
* Disable tracking for this array
*/
public void disableTracking() {
tracked = false;
}
// Determine element type from range
private String determineElementType() {
Object start = evaluator.evaluate(baseRange.start, context);
Object end = evaluator.evaluate(baseRange.end, context);
String startType = typeHandler.getConcreteType(start);
String endType = typeHandler.getConcreteType(end);
if (startType.equals(endType)) {
return startType;
}
// Mixed numeric types become float
if ((startType.equals("int") || startType.equals("float")) &&
(endType.equals("int") || endType.equals("float"))) {
return "float";
}
// Default to text for mixed types
return "text";
}
// Validate range bound matches element type
private void validateRangeBound(AutoStackingNumber bound, String boundName) {
if (!typeHandler.validateType(elementType, bound)) {
throw new ProgramError(
"Range " + boundName + " type does not match inferred element type " + elementType
);
}
}
// ========== CACHE SIZE METHODS ==========
/**
* Invalidates the cached size when array changes
*/
private void invalidateSize() {
cachedSize = null;
}
/**
* Calculates the actual size (called when cache is invalid)
*/
private long calculateSizeInternal() {
try {
if (isLexicographicalRange) {
return calculateLexSize();
}
AutoStackingNumber startVal = getStart();
AutoStackingNumber endVal = getEnd();
AutoStackingNumber stepVal = getStep();
if (stepVal.isZero()) {
return 0L;
}
boolean increasing = stepVal.isPositive();
if ((increasing && startVal.compareTo(endVal) > 0) ||
(!increasing && startVal.compareTo(endVal) < 0)) {
return 0L;
}
// Calculate: ((end - start) / step) + 1
AutoStackingNumber diff = endVal.subtract(startVal);
AutoStackingNumber steps = diff.divide(stepVal);
AutoStackingNumber sizeNum = steps.add(AutoStackingNumber.one(1));
if (sizeNum.compareTo(AutoStackingNumber.fromLong(Long.MAX_VALUE)) > 0) {
throw new ProgramError("Array size too large: " + sizeNum);
}
return sizeNum.longValue();
} catch (ProgramError e) {
throw e;
} catch (Exception e) {
throw new InternalError("Failed to calculate array size", e);
}
}
// ========== RECENT CACHE METHODS ==========
private void clearRecentCache() {
recentCacheValid = false;
recentCacheStart = -1;
for (int i = 0; i < RECENT_CACHE_SIZE; i++) {
recentCache[i] = null;
}
}
private void updateRecentCache(long index, Object value) {
if (!recentCacheValid || index < recentCacheStart ||
index >= recentCacheStart + RECENT_CACHE_SIZE) {
// Shift cache window to center around this index
recentCacheStart = Math.max(0, index - RECENT_CACHE_SIZE / 2);
recentCacheValid = true;
// Clear the cache - will be filled on subsequent gets
for (int i = 0; i < RECENT_CACHE_SIZE; i++) {
recentCache[i] = null;
}
}
// Store in cache if within range
if (index >= recentCacheStart && index < recentCacheStart + RECENT_CACHE_SIZE) {
int cacheIndex = (int)(index - recentCacheStart);
recentCache[cacheIndex] = value;
}
}
private Object getFromRecentCache(long index) {
if (!recentCacheValid) return null;
if (index >= recentCacheStart && index < recentCacheStart + RECENT_CACHE_SIZE) {
int cacheIndex = (int)(index - recentCacheStart);
return recentCache[cacheIndex];
}
return null;
}
private void invalidateRecentCache(long index) {
if (!recentCacheValid) return;
if (index >= recentCacheStart && index < recentCacheStart + RECENT_CACHE_SIZE) {
int cacheIndex = (int)(index - recentCacheStart);
recentCache[cacheIndex] = null;
}
}
// ========== LAZY RANGE VIEWS ==========
private class LazyRangeView extends AbstractList<Object> {
private final WeakReference<NaturalArray> parentRef;
private final ProcessedRange range;
private final long size;
public LazyRangeView(Object spec) {
if (spec == null) {
throw new InternalError("LazyRangeView constructed with null range");
}
this.parentRef = new WeakReference<NaturalArray>(NaturalArray.this);
// Process range ONCE
ProcessedRange rawRange = new ProcessedRange(spec);
long arraySize = NaturalArray.this.size();
// Adjust negative indices
long adjStart = rawRange.start;
long adjEnd = rawRange.end;
if (adjStart < 0) adjStart = arraySize + adjStart;
if (adjEnd < 0) adjEnd = arraySize + adjEnd;
// Validate bounds
if (adjStart < 0 || adjStart >= arraySize) {
throw new ProgramError("Start index out of bounds: " + adjStart);
}
if (adjEnd < 0 || adjEnd >= arraySize) {
throw new ProgramError("End index out of bounds: " + adjEnd);
}
// Create adjusted range if needed
if (adjStart != rawRange.start || adjEnd != rawRange.end) {
this.range = new ProcessedRange(adjStart, adjEnd, rawRange.step);
} else {
this.range = rawRange;
}
long calculatedSize = this.range.size();
if (calculatedSize > Integer.MAX_VALUE) {
throw new ProgramError("Range view size too large: " + calculatedSize);
}
this.size = calculatedSize;
}
@Override
public Object get(int index) {
if (index < 0 || index >= size) {
throw new ProgramError("Index: " + index + ", Size: " + size);
}
NaturalArray parent = parentRef.get();
if (parent == null) {
throw new ProgramError("Cannot access view - original array was garbage collected");
}
long actualIndex = range.indexAt(index);
return parent.get(actualIndex);
}
@Override
public int size() {
return (int) size;
}
@Override
public Iterator<Object> iterator() {
return new LazyRangeIterator();
}
private class LazyRangeIterator implements Iterator<Object> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size;
}
@Override
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return get(currentIndex++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
private class LazyMultiRangeView extends AbstractList<Object> {
private final WeakReference<NaturalArray> parentRef;
private final List<LazyRangeView> rangeViews;
private final int totalSize;
private final int[] rangeOffsets;
private final int[] rangeForIndex; // Precomputed mapping
public LazyMultiRangeView(Object multiRange) {
if (multiRange == null) {
throw new InternalError("LazyMultiRangeView constructed with null multiRange");
}
this.parentRef = new WeakReference<NaturalArray>(NaturalArray.this);
this.rangeViews = new ArrayList<LazyRangeView>();
int total = 0;
for (Object range : RangeObjects.getRanges(multiRange)) {
if (range == null) {
throw new InternalError("Null range in MultiRangeSpec");
}
LazyRangeView view = new LazyRangeView(range);
rangeViews.add(view);
total += view.size();
}
this.totalSize = total;
// Precompute offsets and mapping for O(1) lookup
this.rangeOffsets = new int[rangeViews.size()];
this.rangeForIndex = new int[total];
int offset = 0;
for (int i = 0; i < rangeViews.size(); i++) {
rangeOffsets[i] = offset;
int viewSize = rangeViews.get(i).size();
for (int j = 0; j < viewSize; j++) {
rangeForIndex[offset + j] = i;
}
offset += viewSize;
}
}
@Override
public Object get(int index) {
if (index < 0 || index >= totalSize) {
throw new ProgramError("Index: " + index + ", Size: " + totalSize);
}
NaturalArray parent = parentRef.get();
if (parent == null) {
throw new ProgramError("Cannot access multi-range view - original array was garbage collected");
}
// O(1) direct lookup instead of binary search
int rangeIdx = rangeForIndex[index];
int offset = index - rangeOffsets[rangeIdx];
return rangeViews.get(rangeIdx).get(offset);
}
@Override
public int size() {
NaturalArray parent = parentRef.get();
if (parent == null) {
throw new ProgramError("Cannot access multi-range view - original array was garbage collected");
}
return totalSize;
}
@Override
public Iterator<Object> iterator() {
return new LazyMultiRangeIterator();
}
private class LazyMultiRangeIterator implements Iterator<Object> {
private int currentRange = 0;
private Iterator<Object> currentIterator;
private int visited = 0;
public LazyMultiRangeIterator() {
if (!rangeViews.isEmpty()) {
currentIterator = rangeViews.get(0).iterator();
}
}
@Override
public boolean hasNext() {
NaturalArray parent = parentRef.get();
if (parent == null) {
throw new ProgramError("Cannot iterate multi-range view - original array was garbage collected");
}
return visited < totalSize;
}
@Override
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
while (currentIterator != null && !currentIterator.hasNext()) {
currentRange++;
if (currentRange < rangeViews.size()) {
currentIterator = rangeViews.get(currentRange).iterator();
} else {
currentIterator = null;
}
}
if (currentIterator == null) {
throw new NoSuchElementException();
}
visited++;
return currentIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
// ========== CORE ARRAY OPERATIONS ==========
public long size() {
if (cachedSize == null) {
cachedSize = calculateSizeInternal();
}
return cachedSize;
}
public Object get(long index) {
if (index < 0) {
long size = size();
index = size + index;
}
checkBounds(index);
// ========== TRACKING ==========
if (tracked) {
ArrayTracker.recordArrayAccess(this);
}
// Check recent cache first (fastest)
Object recent = getFromRecentCache(index);
if (recent != null) {
if (tracked) ArrayTracker.recordCacheHit(this);
lastIndex = index;
lastValue = recent;
return maybeConvert(recent);
}
if (tracked) ArrayTracker.recordCacheMiss(this);
// Apply any pending updates that affect this index
applyPendingUpdatesForIndex(index);
if (lastIndex != null && lastIndex == index) {
Object val = maybeConvert(lastValue);
updateRecentCache(index, val);
return val;
}
if (isMutable && cache != null && cache.containsKey(index)) {
Object val = cache.get(index);
lastIndex = index;
lastValue = val;
updateRecentCache(index, val);
return maybeConvert(val);
}
if (computedCache != null && computedCache.containsKey(index)) {
Object cached = computedCache.get(index);
lastIndex = index;
lastValue = cached;
updateRecentCache(index, cached);
return maybeConvert(cached);
}
// Try sequence formulas first (most specific)
Object sequenceResult = evaluateSequenceFormulas(index);
if (sequenceResult != null) {
if (computedCache == null) computedCache = new HashMap<Long, Object>();
computedCache.put(index, sequenceResult);
lastIndex = index;
lastValue = sequenceResult;
updateRecentCache(index, sequenceResult);
return maybeConvert(sequenceResult);
}
// Then conditional formulas
Object conditionalResult = evaluateConditionalFormulas(index);
if (conditionalResult != null) {
if (computedCache == null) computedCache = new HashMap<Long, Object>();
computedCache.put(index, conditionalResult);
lastIndex = index;
lastValue = conditionalResult;
updateRecentCache(index, conditionalResult);
return maybeConvert(conditionalResult);
}
// Then linear recurrence formulas
Object vectorRecurrenceResult = evaluateVectorRecurrenceFormulas(index);
if (vectorRecurrenceResult != null) {
lastIndex = index;
lastValue = vectorRecurrenceResult;
updateRecentCache(index, vectorRecurrenceResult);
return maybeConvert(vectorRecurrenceResult);
}
// Then scalar linear recurrence formulas
Object recurrenceResult = evaluateLinearRecurrenceFormulas(index);
if (recurrenceResult != null) {
lastIndex = index;
lastValue = recurrenceResult;
updateRecentCache(index, recurrenceResult);
return maybeConvert(recurrenceResult);
}
// Finally, base calculation
Object result = calculateValue(index);
lastIndex = index;
lastValue = result;
updateRecentCache(index, result);
return maybeConvert(result);
}
// Get with explicit conversion control
public Object get(long index, boolean withConversion) {
Object value = get(index);
if (withConversion && convertToString) {
return convertToString(value);
}
return value;
}
/**
* Returns a previously materialized value for an index without triggering
* formula evaluation.
*/
public Object peekMaterialized(long index) {
if (index < 0) {
long size = size();
index = size + index;
}
checkBounds(index);
if (isMutable && cache != null && cache.containsKey(index)) {
return cache.get(index);
}
if (computedCache != null && computedCache.containsKey(index)) {
return computedCache.get(index);
}
return null;
}
// Convert value to string based on its type
private Object convertToString(Object value) {
if (value == null) return "none";
if (value instanceof String) return value;
if (value instanceof Integer) return String.valueOf(value);
if (value instanceof Long) return String.valueOf(value);
if (value instanceof AutoStackingNumber) {
return value.toString();
}
if (value instanceof Boolean) return String.valueOf(value);
if (value instanceof IntLiteral) {
return ((IntLiteral) value).value.toString();
}
if (value instanceof FloatLiteral) {
return ((FloatLiteral) value).value.toString();
}
if (value instanceof BoolLiteral) {
return String.valueOf(((BoolLiteral) value).value);
}
if (value instanceof TextLiteral) {
return ((TextLiteral) value).value;
}
return String.valueOf(value);
}
// Apply conversion if needed - with caching
private Object maybeConvert(Object value) {
if (convertToString) {
return convertToString(value);
}
return value;
}
public void set(long index, Object value) {
if (index < 0) {
long size = size();
index = size + index;
}
try {
checkBounds(index);
} catch (ProgramError e) {
throw e;
}
// ========== TRACKING ==========
if (tracked) {
ArrayTracker.recordArrayModification(this);
}
// Type check before assignment - use target element type if converting
String checkType = convertToString ? targetElementType : elementType;
if (!typeHandler.validateType(checkType, value)) {
throw new ProgramError(
"Type mismatch: cannot assign " +
typeHandler.getConcreteType(value) +
" to array of type " + (convertToString ? "[" + targetElementType + "]" : "[" + elementType + "]")
);
}
lastIndex = null;
lastValue = null;
// Invalidate caches
invalidateRecentCache(index);
if (computedCache != null) {
computedCache.remove(index);
}
invalidateSize(); // Size might change if index >= old size
if (!isMutable) {
becomeMutable();
}
if (cache == null) {
cache = new HashMap<Long, Object>();
}
cache.put(index, value);
}
private void checkBounds(long index) {
if (index < 0) {
throw new ProgramError("Negative index: " + index);
}
long size = size();
if (index >= size) {
throw new ProgramError("Index: " + index + ", Size: " + size);
}
}
// ========== OPTIMIZED RANGE OPERATIONS ==========
public List<Object> getRange(Object range) {
if (range == null) {
throw new InternalError("getRange called with null range");
}
return new LazyRangeView(range);
}
public List<Object> getMultiRange(Object multiRange) {
if (multiRange == null) {