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
|
/*******************************************************************************
* Copyright (c) 2011 Vrije Universiteit Brussel.
* Copyright (c) 2023 Dennis Wagelaar.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* Contributors:
* Dennis Wagelaar, Vrije Universiteit Brussel - initial API and
* implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.m2m.atl.emftvm.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.m2m.atl.emftvm.CodeBlock;
import org.eclipse.m2m.atl.emftvm.ExecEnv;
/**
* Immutable {@link Collection} that supports lazy evaluation.
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
*
* @param <E>
*/
public class LazyBag<E> extends LazyCollection<E> {
/**
* {@link LazyBag} that implements the "including" operation.
*/
public static class IncludingBag<E> extends LazyBag<E> {
protected final E object;
/**
* Creates a new {@link IncludingBag}.
* @param object the object to include
* @param dataSource the underlying collection
*/
public IncludingBag(final E object, final LazyCollection<E> dataSource) {
super(dataSource);
this.object = object;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final Object o) {
return (object == null ? o == null : object.equals(o)) ||
((Collection<E>)dataSource).contains(o);
}
/**
* {@inheritDoc}
*/
@Override
public int count(final Object o) {
return ((object == null ? o == null : object.equals(o)) ? 1 : 0)
+ ((LazyCollection<E>) dataSource).count(o);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<E> iterator() {
return new AppendIterator(object);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return ((Collection<E>)dataSource).size() + 1;
}
}
/**
* {@link LazyBag} that implements the "union" operation.
*/
public static class UnionBag<E> extends LazyBag<E> {
protected final LazyCollection<? extends E> other;
/**
* Creates a new {@link UnionBag}.
* @param other the collection to union with <pre>dataSource</pre>
* @param dataSource the underlying collection
*/
public UnionBag(final LazyCollection<? extends E> other, final LazyCollection<E> dataSource) {
super(dataSource);
this.other = other;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final Object o) {
return ((Collection<E>)dataSource).contains(o) || other.contains(o);
}
/**
* {@inheritDoc}
*/
@Override
public int count(final Object object) {
return ((LazyCollection<E>)dataSource).count(object) + other.count(object);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return ((Collection<?>)dataSource).isEmpty() && other.isEmpty();
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<E> iterator() {
return new UnionIterator(other);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return ((Collection<E>)dataSource).size() + other.size();
}
}
/**
* {@link LazyBag} that represents a range running from a first to last {@link Integer}.
*
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
*/
public static class IntegerRangeBag extends LazyBag<Integer> {
protected final int first;
protected final int last;
/**
* Creates a new {@link IntegerRangeBag}.
*
* @param first
* the first object of the range to include
* @param last
* the last object of the range to include
*/
public IntegerRangeBag(final int first, final int last) {
super();
if (first > last) {
throw new IllegalArgumentException(String.format("The first element of a range (%d) cannot be greater than the last (%d)",
first, last));
}
this.first = first;
this.last = last;
}
/**
* {@inheritDoc}
*/
@Override
protected void createCache() {
// no caching
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final Object o) {
if (o instanceof Integer) {
final Integer obj = (Integer) o;
return (obj >= first && obj <= last);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int count(final Object object) {
// All elements of a range are unique
return contains(object) ? 1 : 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
// Empty ranges are not allowed
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<Integer> iterator() {
return new IntegerRangeListIterator(first, last);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return last - first + 1;
}
}
/**
* {@link LazyBag} that represents a range running from a first to last {@link Long}.
*
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
*/
public static class LongRangeBag extends LazyBag<Long> {
protected final long first;
protected final long last;
/**
* Creates a new {@link LongRangeBag}.
*
* @param first
* the first object of the range to include
* @param last
* the last object of the range to include
*/
public LongRangeBag(final long first, final long last) {
super();
if (first > last) {
throw new IllegalArgumentException(String.format("The first element of a range (%d) cannot be greater than the last (%d)",
first, last));
}
this.first = first;
this.last = last;
}
/**
* {@inheritDoc}
*/
@Override
protected void createCache() {
// no caching
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final Object o) {
if (o instanceof Long) {
final Long obj = (Long) o;
return (obj >= first && obj <= last);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int count(final Object object) {
// All elements of a range are unique
return contains(object) ? 1 : 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
// Empty ranges are not allowed
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<Long> iterator() {
return new LongRangeListIterator(first, last);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return (int) (last - first + 1);
}
}
/**
* {@link ReadOnlyIterator} that returns only elements contained in both underlying collections,
* where the element occurs as often as in the collection with the least occurrences of the element.
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
*/
public class BagIntersectionIterator extends CachingIterator {
final Collection<E> s;
final Map<E, Integer> sOcc;
E next;
boolean nextSet;
/**
* Creates a new {@link BagIntersectionIterator} on this and <code>s</code>.
* @param s the collection to intersect with this
*/
public BagIntersectionIterator(final LazyCollection<E> s) {
super(dataSource.iterator());
this.s = s;
if (s.occurrences != null) {
sOcc = new HashMap<E, Integer>(s.occurrences);
} else {
sOcc = new HashMap<E, Integer>();
for (final E e : s) {
if (sOcc.containsKey(e)) {
sOcc.put(e, sOcc.get(e) + 1);
} else {
sOcc.put(e, 1);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
synchronized (cache) {
if (i < cache.size()) {
return true;
} else if (dataSource == null) {
return false;
}
}
if (!nextSet && inner.hasNext()) {
next = inner.next(); // support null values for next
nextSet = true;
}
while (nextSet && (!sOcc.containsKey(next) || sOcc.get(next) == 0) && inner.hasNext()) {
next = inner.next();
}
final boolean hasNext = nextSet && sOcc.containsKey(next) && sOcc.get(next) > 0;
if (!hasNext) {
dataSource = null; // cache complete
assert i == cache.size();
}
return hasNext;
}
/**
* {@inheritDoc}
*/
@Override
public E next() {
if (!nextSet) {
next = inner.next(); // support null values for next
} else {
nextSet = false;
}
while (!sOcc.containsKey(next) || sOcc.get(next) == 0) {
next = inner.next();
}
assert !nextSet && sOcc.containsKey(next) && sOcc.get(next) > 0;
sOcc.put(next, sOcc.get(next) - 1);
updateCache(next);
return next;
}
}
/**
* Creates an empty {@link LazyBag}.
*/
public LazyBag() {
super();
}
/**
* Creates a {@link LazyBag} around <code>dataSource</code>.
* @param dataSource the underlying collection
*/
public LazyBag(final Iterable<E> dataSource) {
super(dataSource);
}
/* *********************************************************************
* Non-lazy operations *
* *********************************************************************/
/**
* {@inheritDoc}
*/
@Override
protected void createCache() {
super.createCache();
if (this.cache == null) {
this.cache = new ArrayList<E>();
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof LazyCollection<?>)) {
return false;
}
try {
final LazyCollection<E> other = (LazyCollection<E>)o;
final LazySet<E> keys = asSet().union(other.asSet());
for (final E e : keys) {
if (count(e) != other.count(e)) {
return false;
}
}
return true;
} catch (final ClassCastException unused) {
return false;
} catch (final NullPointerException unused) {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hashCode = 0;
for (final E obj : this) {
if (obj != null) {
hashCode += obj.hashCode();
}
}
return hashCode;
}
/**
* {@inheritDoc}
*/
@Override
public String asString(final ExecEnv env) {
return appendElements(new StringBuffer("Bag{"), env).append('}').toString();
}
/* *********************************************************************
* Lazy operations *
* *********************************************************************/
/**
* Returns the union of self and <code>bag</code>.
* <p><i>Lazy operation.</i></p>
* @param bag the collection to union with this
* @return The union of self and <code>bag</code>.
*/
public LazyBag<E> union(final LazyBag<? extends E> bag) {
return new UnionBag<E>(bag, this);
}
/**
* Returns the union of self and <code>set</code>.
* <p><i>Lazy operation.</i></p>
* @param set the collection to union with this
* @return The union of self and <code>set</code>.
*/
public LazyBag<E> union(final LazySet<E> set) {
return new UnionBag<E>(set, this);
}
/**
* Returns the intersection of self and <code>bag</code>
* (i.e, the bag of all elements that are in both self and <code>s</code>,
* where the element occurs as often as in the bag with the least element occurrences).
* <p><i>Lazy operation.</i></p>
* @param bag the collection to intersect with this
* @return The intersection of self and <code>bag</code>.
*/
public LazyBag<E> intersection(final LazyBag<E> bag) {
return new LazyBag<E>(this) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new BagIntersectionIterator(bag);
}
};
}
/**
* Returns the intersection of self and <code>set</code>.
* <p><i>Lazy operation.</i></p>
* @param set the collection to intersect with this
* @return The intersection of self and <code>set</code>.
*/
public LazySet<E> intersection(final LazySet<E> set) {
final LazyBag<E> inner = this;
return new LazySet<E>(set) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new IntersectionIterator(inner);
}
};
}
/**
* Returns the bag containing all elements of self plus <code>object</code>.
* <p><i>Lazy operation.</i></p>
* @param object the object to include
* @return The bag containing all elements of self plus <code>object</code>.
*/
@Override
public LazyBag<E> including(final E object) {
return new IncludingBag<E>(object, this);
}
/**
* Returns the collection containing all elements of self plus <code>object</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param object
* the object to include
* @param index
* the index at which to insert <code>coll</code> (starting at 1)
* @return The collection containing all elements of self plus <code>object</code>.
*/
@Override
public LazyBag<E> including(final E object, final int index) {
throw new UnsupportedOperationException("Cannot specify index for adding values to unordered collections");
}
/**
* Returns the collection containing all elements of self plus <code>coll</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param coll
* the collection to include
* @return The collection containing all elements of self plus <code>coll</code>.
*/
@Override
public LazyBag<E> includingAll(final Collection<? extends E> coll) {
return union(LazyCollections.asLazyBag(coll));
}
/**
* Returns the collection containing all elements of self plus <code>coll</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param coll
* the collection to include
* @param index
* the index at which to insert <code>coll</code> (starting at 1)
* @return The collection containing all elements of self plus <code>coll</code>.
* @throws UnsupportedOperationException
*/
@Override
public LazyBag<E> includingAll(final Collection<? extends E> coll, final int index) {
throw new UnsupportedOperationException("Cannot specify index for adding values to unordered collections");
}
/**
* Returns the bag containing all elements of self apart from all occurrences of <code>object</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param object
* the object to exclude
* @return The bag containing all elements of self apart from all occurrences of <code>object</code>.
*/
@Override
public LazyBag<E> excluding(final Object object) {
return new LazyBag<E>(this) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new ExcludingIterator(object);
}
};
}
/**
* Returns the collection containing all elements of self minus <code>coll</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param coll
* the collection to exclude
* @return The collection containing all elements of self minus <code>coll</code>.
*/
@Override
public LazyBag<E> excludingAll(final Collection<?> coll) {
return new LazyBag<E>(this) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new SubtractionIterator(coll);
}
};
}
/**
* If the element type is not a collection type this results in the same self. If the element type is a collection type, the result is
* the sequence containing all the elements of all the elements of self. The order of the elements is partial.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @return <b>if</b> self.type.elementType.oclIsKindOf(CollectionType) <b>then</b><br>
* self->iterate(c; acc : Bag() = Bag{} |<br>
* acc->union(c->asBag() ) )<br>
* <b>else</b><br>
* self<br>
* <b>endif</b>
*/
public LazyBag<?> flatten() {
final LazyBag<E> inner = this;
return new LazyBag<Object>(new Iterable<Object>() {
public Iterator<Object> iterator() {
return new FlattenIterator(inner);
}
});
}
/**
* Returns a Bag identical to self. This operation exists for convenience reasons.
* <p><i>Lazy operation.</i></p>
* @return A Bag identical to self. This operation exists for convenience reasons.
*/
@Override
public LazyBag<E> asBag() {
return this;
}
/**
* Returns the bag containing all elements of self plus the bag of <code>first</code> running to <code>last</code>.
* <p>
* <i>Lazy operation.</i>
* </p>
*
* @param first
* the first object of the range to include
* @param last
* the last object of the range to include
* @return The bag containing all elements of self plus the bag of <code>first</code> running to <code>last</code>
*/
@Override
@SuppressWarnings("unchecked")
public LazyBag<E> includingRange(final E first, final E last) {
if (first instanceof Integer && last instanceof Integer) {
return union((LazyBag<E>) new IntegerRangeBag((Integer)first, (Integer)last));
}
if (first instanceof Long && last instanceof Long) {
return union((LazyBag<E>) new LongRangeBag((Long)first, (Long)last));
}
throw new IllegalArgumentException(String.format("includingRange() not supported for arguments of type %s and %s", first.getClass()
.getName(), last.getClass().getName()));
}
/* *********************************************************************
* Lazy, higher-order operations *
* *********************************************************************/
/**
* Selects all elements from this collection for which the
* <code>condition</code> evaluates to <code>true</code>.
* @param condition the condition function
* @return a new lazy bag with only the selected elements.
*/
public LazyBag<E> select(final CodeBlock condition) {
// Parent frame may change after this method returns!
final StackFrame parentFrame = condition.getParentFrame();
condition.setParentFrame(null);
return new LazyBag<E>(this) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new SelectIterator(condition, parentFrame);
}
};
}
/**
* Rejects all elements from this collection for which the
* <code>condition</code> evaluates to <code>true</code>.
* @param condition the condition function
* @return a new lazy bag without the rejected elements.
*/
public LazyBag<E> reject(final CodeBlock condition) {
// Parent frame may change after this method returns!
final StackFrame parentFrame = condition.getParentFrame();
condition.setParentFrame(null);
return new LazyBag<E>(this) {
@Override
public Iterator<E> iterator() {
if (dataSource == null) {
return Collections.unmodifiableCollection(cache).iterator();
}
return new RejectIterator(condition, parentFrame);
}
};
}
/**
* Collects the return values of <code>function</code> for
* each of the elements of this collection.
* @param function the return value function
* @return a new lazy bag with the <code>function</code> return values.
* @param <T> the element type
*/
public <T> LazyBag<T> collect(final CodeBlock function) {
// Parent frame may change after this method returns!
final StackFrame parentFrame = function.getParentFrame();
function.setParentFrame(null);
final LazyBag<E> inner = this;
return new LazyBag<T>(new Iterable<T>() {
public Iterator<T> iterator() {
return new CollectIterator<T>(inner, function, parentFrame);
}
});
}
/**
* {@inheritDoc}
*/
@Override
public LazyList<E> sortedBy(final CodeBlock body) {
// Parent frame may change after this method returns!
final StackFrame parentFrame = body.getParentFrame();
body.setParentFrame(null);
return new LazyList<E>(this) {
@SuppressWarnings("unchecked")
@Override
public Iterator<E> iterator() {
final Collection<E> inner = (Collection<E>) dataSource;
if (inner != null) {
final Iterator<Comparable<Object>> sortingKeys = new CollectIterator<Comparable<Object>>(inner, body, parentFrame);
final Object[] innerCopy = inner.toArray();
final Map<Object, Comparable<Object>> elementsToKeys = new HashMap<Object, Comparable<Object>>(innerCopy.length);
for (final Object o : innerCopy) {
elementsToKeys.put(o, sortingKeys.next());
}
assert !sortingKeys.hasNext();
Arrays.sort(innerCopy, new Comparator<Object>() {
public int compare(final Object o1, final Object o2) {
return elementsToKeys.get(o1).compareTo(elementsToKeys.get(o2));
}
});
cache = (Collection<E>) Arrays.asList(innerCopy);
dataSource = null;
}
return super.iterator();
}
@Override
public int size() {
if (dataSource == null) {
return cache.size();
}
return ((Collection<E>) dataSource).size();
}
};
}
//TODO provide other iterator operations: collectNested
}
|