-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathre.zig
4545 lines (3689 loc) · 201 KB
/
re.zig
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
const std = @import("std");
const buildMode = @import("mode");
const cAllocer = std.heap.c_allocator;
const Allocator = std.mem.Allocator;
fn assert(condition:bool, comptime message:[]const u8, args:anytype) void {
if(buildMode.debug){
if (!condition) {
std.debug.print("\n-----------------------\nAssertion failed: " ++ message ++ "\n-----------------------\nTrace:\n", args);
unreachable;
}
}
}
fn debugLog(comptime message:[]const u8, args:anytype) void {
std.debug.print(message ++ "\n", args);
}
fn debugLogColor(comptime color:Termcolor, comptime message:[]const u8, args:anytype) void {
debugLog(color ++ message ++ Termcolors.Reset, args);
}
fn structFieldType(comptime T:type, comptime fieldIndex:comptime_int) type{
return @typeInfo(T).Struct.fields[fieldIndex].type;
}
test "semantically analyze relevant types without explicit calls" {
std.testing.refAllDeclsRecursive(RegEx);
std.testing.refAllDeclsRecursive(RegExDFA);
std.testing.refAllDeclsRecursive(RegExNFA);
// doesn't use a simple u32 array set, because that includes methods that assume a key-value type store, and thus an ArraySet(u2) intentionally doesn't pass semantic analysis for some methods
std.testing.refAllDeclsRecursive(ArraySet(Pair(u32, u32), keyCompare(Pair(u32, u32), makeOrder(u32))));
std.testing.refAllDeclsRecursive(UnionFind(u32, makeOrder(u32)));
std.testing.refAllDeclsRecursive(RangeMap(u32, makeOrder(u32), u32));
}
fn isOk(errUnionType: anytype) bool {
_ = errUnionType catch return false;
return true;
}
fn isErr(errUnionType: anytype) bool {
return !isOk(errUnionType);
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualDeep = std.testing.expectEqualDeep;
const expectError = std.testing.expectError;
fn expectAnyError(value:anytype) !void {
_ = value catch {
return;
};
try expect(false);
}
// unwraps the parser result, and checks that the diag contains the expected error
fn expectParserError(expectedError: anyerror, parserResult: anytype) !void {
const diag:Diag = parserResult[1];
defer diag.deinit();
for(diag.msgs.items) |msg| {
if(msg.kind.Error == expectedError)
return;
}
try expectAnyError(parserResult[0]);
}
// unwraps the optional and std.testing.expect's that its not null (similar to just doing .?, but with an explicit expect)
fn expectNotNull(value:anytype) !@typeInfo(@TypeOf(value)).Optional.child {
try expect(value != null);
return value.?;
}
fn expectOrSkip(condition:bool) !void{
if(!condition)
return error.SkipZigTest;
}
const Tuple = std.meta.Tuple;
fn Pair(comptime T:type, comptime U:type) type {
return Tuple(&[2]type{T, U});
}
const Order = std.math.Order;
fn initArrayListLikeWithElements(allocator:Allocator, comptime ArrayListType:type, elementsSlice:anytype) !ArrayListType{
var arrayListLike = try ArrayListType.initCapacity(allocator, elementsSlice.len);
errdefer arrayListLike.deinit();
try arrayListLike.appendSlice(elementsSlice);
return arrayListLike;
}
fn makeOrder(comptime T:type) fn (T, T) Order {
return struct {
pub fn f(a:T, b:T) Order {
return std.math.order(a, b);
}
}.f;
}
const Termcolor = [:0]const u8;
const Termcolors = struct{
const Reset = "\x1b[0m";
// use the defaults from GCC
const Red = "\x1b[01;31m";
const Error = Red;
const Magenta = "\x1b[01;35m";
const Warning = Magenta;
};
// sorted array set. Should not be used if removal is important, try to treat it as an insert-only set
// an insert-first-lookup-later sorted vector like map for performance (like https://www.llvm.org/docs/ProgrammersManual.html recommends)
pub fn ArraySet(comptime T:type, comptime comparatorFn:(fn (T, T) Order)) type {
return struct {
const Item = T;
items:[]T,
internalAllocator:Allocator,
internalSlice:[]T,
const InsertOpts = struct{
ReplaceExisting:bool = false, // important for example if this is a key/value map and comparator fn only compares the key
AssumeCapacity:bool = false,
LinearInsertionSearch:bool = false,
// TODO should maybe be 'JustAppendDontSort'
DontSort:bool = false,
};
pub fn init(allocator:Allocator) !@This() {
var self = @This(){
.items = undefined,
.internalSlice = try allocator.alloc(T, 0),
.internalAllocator = allocator,
};
self.items = self.internalSlice[0..];
return self;
}
pub fn initCapacity(allocator:Allocator, capacity:usize) Allocator.Error!@This() {
var self = @This(){
.items = undefined,
.internalSlice = try allocator.alloc(T, capacity),
.internalAllocator = allocator,
};
// pay attention not to use the internalSlice here as above, because the items slice should not be filled with undefined items, it should just have the capacity
self.items.ptr = self.internalSlice.ptr;
self.items.len = 0;
return self;
}
pub fn initElements(allocator:Allocator, elementsSlice:anytype) Allocator.Error!@This() {
var self = try initCapacity(allocator, elementsSlice.len);
for (elementsSlice) |item| {
try self.insert(item, .{.AssumeCapacity = true});
}
return self;
}
pub fn deinit(self:@This()) void {
self.internalAllocator.free(self.internalSlice);
}
pub fn ensureTotalCapacity(self:*@This(), minNewCapacity:usize) Allocator.Error!void {
if(minNewCapacity > self.internalSlice.len) {
// from array_list.zig
var betterCapacity = self.internalSlice.len;
while (betterCapacity < minNewCapacity){
// saturating addition
betterCapacity +|= betterCapacity / 2 + 8;
}
// can't/shouldn't use realloc:
// - can't use it on the items slice, because the size has to match the original allocation size
// - shouldn't use it on the internalSlice, because that would copy even the unused capacity
const old = self.internalSlice;
self.internalSlice = try self.internalAllocator.alloc(T, betterCapacity);
@memcpy(self.internalSlice[0..self.items.len], self.items);
self.internalAllocator.free(old);
self.items = self.internalSlice[0..self.items.len];
}
}
pub fn ensureUnusedCapacity(self:*@This(), newCapacity:usize) Allocator.Error!void {
try self.ensureTotalCapacity(self.items.len + newCapacity);
}
pub fn resize(self:*@This(), newSize:usize) Allocator.Error!void {
try self.ensureTotalCapacity(newSize);
self.items.len = newSize;
}
pub fn sort(self:*@This()) void {
std.sort.pdq(T ,self.items, .{}, struct{
pub fn f(_:@TypeOf(.{}), a:T, b:T) bool {
return comparatorFn(a, b) == Order.lt;
}
}.f);
}
const SpotInfo = struct{item_ptr:*T, found_existing:bool};
pub fn insert(self:*@This(), itemToInsert:T, comptime opts:InsertOpts) Allocator.Error!void{
_ = try insertAndGet(self, itemToInsert, opts);
}
pub fn insertAndGet(self:*@This(), itemToInsert:T, comptime opts:InsertOpts) Allocator.Error!SpotInfo {
if(opts.DontSort){
if(opts.LinearInsertionSearch)
@compileError("LinearInsertionSearch not applicable when DontSort is set");
if(opts.ReplaceExisting)
@compileError("ReplaceExisting not applicable when DontSort is set");
if(!opts.AssumeCapacity)
try self.ensureUnusedCapacity(1);
self.items.len += 1;
self.items[self.items.len-1] = itemToInsert;
return .{.item_ptr = &self.items[self.items.len-1], .found_existing = false};
}
const findResults = try self.findOrMakeSpot(itemToInsert, .{.AssumeCapacity = opts.AssumeCapacity, .LinearInsertionSearch = opts.LinearInsertionSearch});
// if we didnt find it, or we should replace it, write to it
if(!findResults.found_existing or opts.ReplaceExisting)
findResults.item_ptr.* = itemToInsert;
// results are still correct
return findResults;
}
// TODO would be great if this supported merging the individual elements of the two at some point, could parameterize it with 'shouldMerge' and 'merge' functions passed to this one
// invalidates pointers and capacity guarantees in all cases (!)
// this could also be done sort of in-place with sufficient guarantees, but that is unnecessarily complex for now
pub fn addAll(a:*@This(), b:@This()) Allocator.Error!void {
if(a.items.ptr == b.items.ptr){
assert(a.items.len == b.items.len, "addAll called on the same set with different lengths", .{});
return;
}else if(b.items.len == 0){
return;
}
var self = a;
// allocate a new array with the combined capacity, that will become the self.items array later
var newInternalSlice = try a.internalAllocator.alloc(T, a.items.len + b.items.len);
// merge the two basically like in mergesort, but take care to deduplicate them
var aI:usize = 0;
var bI:usize = 0;
var newI:usize = 0;
var actualNewLen:usize = newInternalSlice.len;
while(true) : (newI += 1) {
if(aI >= a.items.len){
// a is empty, just copy the rest of b (deduplicate the joint)
if(newI != 0 and comparatorFn(newInternalSlice[newI - 1], b.items[bI]) == Order.eq){
bI += 1;
actualNewLen -= 1;
}
if(bI >= b.items.len)
// b is empty too, we're done
break;
@memcpy(newInternalSlice[newI..actualNewLen], b.items[bI..]);
break;
}else if(bI >= b.items.len){
// same thing, b is empty, so copy the rest of a, with deduplication
if(newI != 0 and comparatorFn(newInternalSlice[newI - 1], a.items[aI]) == Order.eq){
aI += 1;
actualNewLen -= 1;
}
if(aI >= a.items.len)
// a is empty too, we're done
break;
@memcpy(newInternalSlice[newI..actualNewLen], a.items[aI..]);
break;
}else
// otherwise copy the smaller one
if(comparatorFn(a.items[aI], b.items[bI]) == Order.lt){
// deduplicate
if(newI != 0 and comparatorFn(newInternalSlice[newI - 1], a.items[aI]) == Order.eq){
actualNewLen -= 1;
// don't increment newI, so we overwrite the duplicate
newI -= 1;
}else{
newInternalSlice[newI] = a.items[aI];
}
aI += 1;
}else{
// deduplicate
if(newI != 0 and comparatorFn(newInternalSlice[newI - 1], b.items[bI]) == Order.eq){
actualNewLen -= 1;
// don't increment newI, so we overwrite the duplicate
newI -= 1;
}else{
newInternalSlice[newI] = b.items[bI];
}
bI += 1;
}
}
// replace the old self array with the new one
self.internalAllocator.free(self.internalSlice);
self.internalSlice = newInternalSlice;
self.items = newInternalSlice[0..actualNewLen];
}
// this is not very efficient, as this set is not really designed to have elements removed from frequently. Has to move O(n) elements in the worst case
// returns whether it removed something
// never shrinks the internal array
pub fn remove(self:*@This(), itemToRemove:T, comptime findOpts:struct{LinearInsertionSearch:bool = false}) bool {
const spot = self.findSpot(itemToRemove, .{.LinearInsertionSearch = findOpts.LinearInsertionSearch}) orelse return false;
if(spot.found_existing){
const i = (@intFromPtr(spot.item_ptr) - @intFromPtr(self.items.ptr))/@sizeOf(T);
std.mem.copyForwards(T, self.items[i..self.items.len-1], self.items[i+1..self.items.len]);
self.items.len -= 1;
return true;
}
return false;
}
/// DO NOT CHANGE THIS FUNCTION'S SIGNATURE WITHOUT CONSIDERING THE CODE GENERATION
/// returns whether the set contains the item finds the item using binary search
pub fn contains(self:*const @This(), itemToFind:T) bool {
const spot = self.findSpot(itemToFind, .{.LinearInsertionSearch = false}) orelse return false;
return spot.found_existing;
}
pub fn containsKey(self:*const @This(), keyToFind:@typeInfo(T).Struct.fields[0].type) bool {
return self.contains(.{keyToFind, undefined});
}
// finds the value of the first item that has a key greater than or equal to the key to compare against. If there is no greater or equal key, null is returned.
pub fn findByKey(self:*const @This(), keyToCompareAgainst:structFieldType(T, 0)) ?structFieldType(T, 1){
if(@typeInfo(T).Struct.fields.len != 2)
@compileError("findByKey only works when this set is being used as a key value map, i.e. with two-long tuple elements");
const spot = self.findSpot(.{keyToCompareAgainst, undefined}, .{.LinearInsertionSearch = false}) orelse return null;
return if(spot.found_existing) spot.item_ptr.*[1] else null;
}
// finds the first item that is greater than or equal to the item to find. If there is no greater or equal item, null is returned. If item_ptr.* is greater, found_existing is false. Otherwise, found_existing is true
pub fn findSpot(self:*const @This(), itemToCompareAgainst:T, comptime opts:struct{
LinearInsertionSearch:bool = false,
}) ?SpotInfo {
// can confidently @constCast, and ignore the error, because we don't modify anything (guaranteed by the implementation)
return @constCast(self).findSpotInternal(itemToCompareAgainst, .{.LinearInsertionSearch = opts.LinearInsertionSearch}) catch unreachable;
}
// finds the spot of the item that is equal to the item to find, or the spot where it should be inserted if it does not exist (expanding the array, possibly allocating new space)
pub fn findOrMakeSpot(self:*@This(), itemToCompareAgainst:T, comptime opts:struct{
AssumeCapacity:bool = false,
LinearInsertionSearch:bool = false,
}) !SpotInfo {
return (try self.findSpotInternal(itemToCompareAgainst, .{.MakeSpaceForNewIfNotFound = true, .AssumeCapacity = opts.AssumeCapacity, .LinearInsertionSearch = opts.LinearInsertionSearch})) orelse unreachable; // cannot be null, because we make space if it doesnt exist
}
// only use this if you know what you're doing, try to use `contains`, the other `find...` functions or `insert` if possible
// finds the first item that is greater than or equal to the item to find and returns a pointer to it or the place it should be inserted if it does not exist, as well as whether or not it exists
// if opts.MakeSpaceForNewIfNotFound is set, the array will be expanded and the returned pointer will point to the new item (undefined) item.
// if opts.MakeSpaceForNewIfNotFound is not set and .found_existing is false, the returned pointer is null, if the array contains no element greater than the passed element, and valid if there is such an element.
// can not return an error if opts.MakeSpaceForNewIfNotFound is not set
fn findSpotInternal(self:*@This(), itemToCompareAgainst:T, comptime opts:struct{
MakeSpaceForNewIfNotFound:bool = false,
AssumeCapacity:bool = false,
LinearInsertionSearch:bool = false,
}) !?SpotInfo {
if(!opts.MakeSpaceForNewIfNotFound and opts.AssumeCapacity)
@compileError("Can't assume capacity if findSpotInternal can not insert");
var left: usize = 0;
var right: usize = self.items.len;
// in any of the cases where we find it, we can ignore opts.MakeSpaceForNewIfNotFound (obviously)
if(opts.LinearInsertionSearch){
while(comparatorFn(itemToCompareAgainst, self.items[left]) == Order.gt and left < right){
left += 1;
}
if(comparatorFn(itemToCompareAgainst, self.items[left]) == Order.eq) {
return .{.item_ptr = &self.items[left], .found_existing = true};
}
// otherwise left points to the first element that is greater than the item to insert -> insert before that
}else{
// binary search, but we can't use the std.sort one, because we need to insert if not found
// so just copy that one and change it :
while (left < right) {
// Avoid overflowing in the midpoint calculation
const mid = left + (right - left) / 2;
// Compare the key with the midpoint element
switch(comparatorFn(itemToCompareAgainst, self.items[mid])){
Order.lt => right = mid,
Order.gt => left = mid + 1,
Order.eq => return .{.item_ptr = &self.items[mid], .found_existing = true},
}
}
assert(left == right, "after binary search to insert, we should be left with a definitive insertion point", .{});
// left again points to first element that is greater than the item to insert -> insert before that
}
// didn't find, return the insertion point (and possibly expand the array, and move the items)
const firstGreater = left;
// assert sensible insertion point
assert(firstGreater <= self.items.len, "Find reached too far outside the array", .{});
if(opts.MakeSpaceForNewIfNotFound){
try self.insertBeforeInternal(firstGreater, opts.AssumeCapacity);
}else {
if(firstGreater == self.items.len)
// in this case, we don't want to return an invalid pointer, so we return null (as the whole spot info, because found existing is obviously implicitly false in this case), as the pointer would not make sense, if the array has not been expanded
return null;
}
return .{.item_ptr = @ptrCast(self.items.ptr + firstGreater), .found_existing = false};
}
// do not use this function to simply insert an element, this can only be used if you have found the proper insertion point already
fn insertBeforeInternal(self:*@This(), index:usize, assumeCapacity:bool) Allocator.Error!void {
if(!assumeCapacity)
try self.ensureUnusedCapacity(1);
// let the `items` slice know that it has grown
self.items.len += 1;
// shift everything to the right
std.mem.copyBackwards(T, self.internalSlice[index+1..], self.internalSlice[index..(self.items.len - 1)]); // -1: old item length
}
// clones the set, uses the same allocator. Does not make any guarantees about the capacity of the new set, just that the actual elements are the same
pub fn clone(self:@This()) !@This() {
var theClone = try @This().initCapacity(self.internalAllocator, self.items.len);
theClone.items.len = self.items.len;
@memcpy(theClone.items, self.items);
return theClone;
}
pub fn debugPrint(self:@This()) void {
for (self.items) |item| {
std.debug.print("{}, ", .{item});
}
std.debug.print("\n", .{});
}
};
}
fn oldIntCast(x:anytype, comptime ResultType:type) ResultType {
const result:ResultType = @intCast(x);
return result;
}
// TODO there has to be a better way to 'save' the Key Type locally somehow, to avoid code dupe
fn keyCompare(comptime T:type, comptime compare:fn(structFieldType(T, 0), structFieldType(T, 0)) Order) fn(T, T) Order {
return struct {
pub fn f(a:T, b:T) Order {
return compare(a[0], b[0]);
}
}.f;
}
test "array set" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const T = ArraySet(u32, makeOrder(u32));
var set = try T.init(arena.allocator());
try set.insert(5, .{});
try expect(std.mem.eql(u32, set.items, &[1]u32{5}));
try set.insert(2, .{});
try expect(std.mem.eql(u32, set.items, &[2]u32{2,5}));
try set.insert(7, .{});
try expect(std.mem.eql(u32, set.items, &[3]u32{2,5,7}));
try set.insert(0, .{});
try expect(std.mem.eql(u32, set.items, &[4]u32{0,2,5,7}));
var set2 = try ArraySet(u32, makeOrder(u32)).init(arena.allocator());
const insertionOpts2:T.InsertOpts = .{.DontSort = true};
try set2.insert(5, insertionOpts2);
try expect(std.mem.eql(u32, set2.items, &[1]u32{5}));
try set2.insert(2, insertionOpts2);
try expect(std.mem.eql(u32, set2.items, &[2]u32{5,2}));
try set2.insert(7, insertionOpts2);
try expect(std.mem.eql(u32, set2.items, &[3]u32{5,2,7}));
try set2.insert(0, insertionOpts2);
try expect(std.mem.eql(u32, set2.items, &[4]u32{5,2,7,0}));
set2.sort();
try expect(std.mem.eql(u32, set2.items, &[4]u32{0,2,5,7}));
try expect(set2.remove(2, .{}) == true);
try expect(std.mem.eql(u32, set2.items, &[3]u32{0,5,7}));
try expect(set2.remove(3, .{}) == false);
try expect(std.mem.eql(u32, set2.items, &[3]u32{0,5,7}));
try expect(set2.remove(4, .{}) == false);
try expect(std.mem.eql(u32, set2.items, &[3]u32{0,5,7}));
try expect(set2.remove(5, .{}) == true);
try expect(std.mem.eql(u32, set2.items, &[2]u32{0,7}));
}
test "array set addAll" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const insertionOpts = .{.LinearInsertionSearch = false, .AssumeCapacity = false, .ReplaceExisting = false, .DontSort = false};
var set1 = try ArraySet(u32, makeOrder(u32)).init(arena.allocator());
try set1.insert(5, insertionOpts);
try set1.insert(2, insertionOpts);
try set1.insert(7, insertionOpts);
try set1.insert(0, insertionOpts);
var set2 = try ArraySet(u32, makeOrder(u32)).init(arena.allocator());
try set2.insert(4, insertionOpts);
try set2.insert(1, insertionOpts);
try set2.insert(6, insertionOpts);
try set2.insert(3, insertionOpts);
try set1.addAll(set2);
try expect(std.mem.eql(u32, set1.items, &[8]u32{0,1,2,3,4,5,6,7}));
// add random stuff to the two sets, compare against a single set
const numStuffToInsert = 10000;
set1 = try ArraySet(u32, makeOrder(u32)).initCapacity(arena.allocator(), numStuffToInsert * 2);
set2 = try ArraySet(u32, makeOrder(u32)).initCapacity(arena.allocator(), numStuffToInsert);
var correctSet = try ArraySet(u32, makeOrder(u32)).initCapacity(arena.allocator(), numStuffToInsert * 2 );
var rnd = std.rand.DefaultPrng.init(0);
for(0..numStuffToInsert) |_| {
const rand1 = rnd.random().intRangeLessThan(u32, 0, 1000);
const rand2 = rnd.random().intRangeLessThan(u32, 0, 1000);
try set1.insert(rand1, insertionOpts);
try set2.insert(rand2, insertionOpts);
try correctSet.insert(rand1, insertionOpts);
try correctSet.insert(rand2, insertionOpts);
try set1.addAll(set2);
if(!std.mem.eql(u32, set1.items, correctSet.items)){
set1.debugPrint();
correctSet.debugPrint();
try expect(false);
}
}
}
test "use array set as map" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const T = Tuple(&[2]type{u32, u32});
const S = struct{
fn order_u32(a:u32, b:u32) Order {
return std.math.order(a, b);
}
};
const comp = keyCompare(T, S.order_u32);
const MapT = ArraySet(T, comp);
var set = try MapT.init(arena.allocator());
const insertionOpts:MapT.InsertOpts = .{};
// do x^2 for testing
var rnd = std.rand.DefaultPrng.init(0);
for (0..10000) |i| {
_ = i;
const x = rnd.random().intRangeLessThan(u32, 0, 1 << 15);
try set.insert(.{x, x*x}, insertionOpts);
}
var lastItem = set.items[0];
for (set.items) |item| {
// keys ([0]) should be sorted
try expect(item[0] >= lastItem[0]);
lastItem = item;
// and values ([1]) should be correctd
try expect(item[1] == item[0]*item[0]);
}
}
pub fn UnionFind(comptime T:type, comptime comparatorFn:(fn (T, T) Order)) type {
return struct{
parent:ArraySet(Tuple(&[2]type{T, T}), keyCompare(Tuple(&[2]type{T, T}), comparatorFn)),
pub fn init(allocator:Allocator) !@This() {
return @This(){
.parent = try ArraySet(Tuple(&[2]type{T, T}), keyCompare(Tuple(&[2]type{T, T}), comparatorFn)).init(allocator),
};
}
pub fn deinit(self:@This()) void {
self.parent.deinit();
}
pub fn find(self:*@This(), item:T) !*T {
const parent = try self.parent.findOrMakeSpot(.{item, undefined}, .{});
// smallest sets are simply one-element sets represented by themselves. These get inserted explicitly, so that a union (yunyin) can be done with them
if(!parent.found_existing){
parent.item_ptr.*[0] = item;
parent.item_ptr.*[1] = item;
return &parent.item_ptr.*[1];
}
// parents that point to themselves are also the representative of their set
if(comparatorFn(parent.item_ptr.*[1], item) == Order.eq)
return &parent.item_ptr.*[1];
const rep = try self.find(parent.item_ptr.*[1]);
// path compression
parent.item_ptr.*[1] = rep.*;
return rep;
}
// representative of a is now the representative of all of a \cup b
pub fn yunyin(self:*@This(), a:T, b:T) !void {
const aParent = try self.find(a);
const bParent = try self.find(b);
if(comparatorFn(aParent.*, bParent.*) == Order.eq)
return;
bParent.* = aParent.*;
}
};
}
test "union-find" {
const T = u32;
var uf = try UnionFind(T, makeOrder(T)).init(std.testing.allocator);
defer uf.deinit();
try uf.yunyin(1, 2);
try expect(try uf.find(1) == try uf.find(2));
try expect((try uf.find(1)).* == 1);
try uf.yunyin(3, 4);
try expect(try uf.find(3) == try uf.find(4));
try expect((try uf.find(3)).* == 3);
try uf.yunyin(2, 4);
try expect((try uf.find(1)).* == 1);
for(1..5) |i| {
try expect(try uf.find(@intCast(i)) == try uf.find(1));
}
}
// ranges are inclusive and may not overlap (they are seen as disjoint sets)
pub fn RangeMap(comptime RangeableKey:type, comptime keyOrder:(fn(RangeableKey, RangeableKey) Order), comptime Value:type) type {
return struct{
// maps highest element of range to (lowest, value)
const Item = Pair(RangeableKey, Pair(RangeableKey, Value));
const Map = ArraySet(Item, keyCompare(Item, keyOrder));
map:Map,
pub fn init(allocator:Allocator) !@This() {
return @This(){
.map = try Map.init(allocator),
};
}
pub fn initCapacity(allocator:Allocator, capacity:usize) Allocator.Error!@This() {
return @This(){
.map = try Map.initCapacity(allocator, capacity),
};
}
// clones the set, uses the same allocator. Does not make any guarantees about the capacity of the new set, just that the actual elements are the same
pub fn clone(self:@This()) !@This() {
return @This(){
.map = try self.map.clone(),
};
}
pub fn deinit(self:@This()) void {
self.map.deinit();
}
// inserts a range + value. ranges are inclusive and may not overlap
pub fn insert(self:*@This(), lower:RangeableKey, upper:RangeableKey, value:Value, comptime opts:struct{AssumeNoOverlap:bool = false}) !void {
_ = try self.insertAndGet(lower, upper, value, .{.AssumeNoOverlap = opts.AssumeNoOverlap});
}
// inserts a range + value. ranges are inclusive and may not overlap
pub fn insertAndGet(self:*@This(), lower:RangeableKey, upper:RangeableKey, value:Value, comptime opts:struct{AssumeNoOverlap:bool = false}) !*Item {
assert(keyOrder(lower, upper) != Order.gt, "lower bound of range must be <= than upper bound", .{});
if(opts.AssumeNoOverlap){
assert(self.find(lower) == null, "tried to insert existing range; ranges cannot overlap", .{});
assert(self.find(upper) == null, "tried to insert existing range; ranges cannot overlap", .{});
}else{
if(self.find(lower) != null or self.find(upper) != null)
return error.OverlappingRanges;
}
return (try self.map.insertAndGet(.{upper, .{lower, value}}, .{})).item_ptr;
}
pub fn insertSingle(self:*@This(), key:RangeableKey, value:Value, comptime opts:struct{AssumeNoOverlap:bool = false}) !void {
try self.insert(key, key, value, .{.AssumeNoOverlap = opts.AssumeNoOverlap});
}
pub fn find(self:*const @This(), key:RangeableKey) ?Value {
return (self.findByPtr(key) orelse return null).*;
}
pub fn findByPtr(self:*const @This(), key:RangeableKey) ?*Value {
return &(self.findItem(key) orelse return null).*[1][1];
}
pub fn findItem(self:*const @This(), key:RangeableKey) ?*Item {
// the inner self.map method finds the first greater than or equal to key -> will be the highest element of the range that could contain key, if key >= lowest
const spotInfo = self.map.findSpot(.{key, undefined}, .{})
// passed key is higher than any highest element of a range
orelse return null;
if(keyOrder(key, spotInfo.item_ptr.*[1][0]) != Order.lt)
// lies within the range
return spotInfo.item_ptr;
return null;
}
const SpotInfo = struct{item_ptr:*Item, found_existing:bool,
fn setRange(self:*@This(), newLower:RangeableKey, newUpper:RangeableKey) void { self.item_ptr.*[0] = newUpper; self.item_ptr.*[1][0] = newLower; }
fn getRange(self:*const @This()) Pair(RangeableKey, RangeableKey) { return .{self.item_ptr.*[0], self.item_ptr.*[1][0]}; }
fn value(self:*@This()) *Value { return &self.item_ptr.*[1][1]; }
fn lower(self:*@This()) *RangeableKey { return &self.item_ptr.*[1][0]; }
fn upper(self:*@This()) *RangeableKey { return &self.item_ptr.*[0]; }
};
pub fn findOrMakeSpot(self:*@This(), key:RangeableKey, opts:struct{AssumeCapacity:bool = false}) !SpotInfo {
// TODO unfortunately duplicates code from findSpotInternal, because to avoid searching twice, we need to make nuanced modifications to the search
var left: usize = 0;
var right: usize = self.map.items.len;
// binary search, but we can't use the std.sort one, because we need to insert if not found
// so just copy that one and change it :
while (left < right) {
// Avoid overflowing in the midpoint calculation
const mid = left + (right - left) / 2;
// Compare the key with the midpoint element
switch(keyOrder(key, self.map.items[mid][0])){
Order.lt => right = mid,
Order.gt => left = mid + 1,
Order.eq => return .{.item_ptr = &self.map.items[mid], .found_existing = true},
}
}
assert(left == right, "after binary search to insert, we should be left with a definitive insertion point", .{});
// left again points to first element that is greater than the item to insert -> insert before that
const firstGreater = left;
// assert sensible insertion point
assert(firstGreater <= self.map.items.len, "Find reached too far outside the array", .{});
// DIFFERENCE: check if the key lies in the found range, just return it
if(firstGreater < self.map.items.len and keyOrder(key, self.map.items[firstGreater][1][0]) != Order.lt)
return .{.item_ptr = @ptrCast(self.map.items.ptr + firstGreater), .found_existing = true};
// otherwise insert:
if(!opts.AssumeCapacity)
try self.map.ensureUnusedCapacity(1);
// let the `items` slice know that it has grown
self.map.items.len += 1;
// shift everything to the right
std.mem.copyBackwards(Item, self.map.internalSlice[firstGreater+1..], self.map.internalSlice[firstGreater..(self.map.items.len - 1)]); // -1: old item length
return .{.item_ptr = @ptrCast(self.map.items.ptr + firstGreater), .found_existing = false};
}
// simply accesses the internal slice by index (assumes the index exists). Only use if you understand the maps inner workings
pub fn valueByIndex(self:*const @This(), index:usize) Value {
return self.map.items[index][1][1];
}
};
}
test "range map"{
var rm = try RangeMap(u32, makeOrder(u32), u32).init(std.testing.allocator);
defer rm.deinit();
try rm.insert(0, 10, 1, .{});
for(0..11) |i| {
const ii = oldIntCast(i, u32);
try expect(rm.find(@intCast(ii)).? == 1);
try expectError(error.OverlappingRanges, rm.insert(ii, ii, 1, .{}));
}
try expectError(error.OverlappingRanges, rm.insert(0, 10, 1, .{}));
try expectError(error.OverlappingRanges, rm.insert(3, 6, 1, .{}));
}
test "range map transitions" {
// adapted from NFA
const UniqueStateSet = ArraySet(u32, makeOrder(u32));
const EntireTransitionMapOfAState = RangeMap(u8, makeOrder(u8), UniqueStateSet);
var map = try EntireTransitionMapOfAState.init(std.testing.allocator);
defer map.deinit();
try map.insert('a', 'z', try UniqueStateSet.init(std.testing.allocator), .{});
var res = try expectNotNull(map.findByPtr('a'));
defer res.deinit();
try res.insert(1, .{});
res = try expectNotNull(map.findByPtr('a'));
try expect(res.contains(1));
res = try expectNotNull(map.findByPtr('a'));
try res.insert(3, .{});
res = try expectNotNull(map.findByPtr('a'));
try expect(res.contains(3));
res = try expectNotNull(map.findByPtr('a'));
try res.insert(2, .{});
res = try expectNotNull(map.findByPtr('a'));
try expect(res.contains(2));
for('a'..('z'+1)) |c|{
var res2 = try expectNotNull(map.findByPtr(@intCast(c)));
for(1..4) |i| {
try expect(res2.contains(@intCast(i)));
}
}
}
pub fn formatTransitionChar(char:u8, writer: anytype) !void {
// handle some special chars
switch(char){
0 => _ = try writer.write("ε"),
' ' => _ = try writer.write("\\s"),
'\n' => _ = try writer.write("\\n"),
'\t' => _ = try writer.write("\\t"),
'\r' => _ = try writer.write("\\r"),
else => {
if(char < 0x20 or char >= 0xff){
try writer.print("0x{x:0>2}", .{char});
}else{
try writer.writeByte(char);
}
}
}
}
pub fn formatTransitionChars(chars:Pair(u8, u8), writer: anytype) !void {
// TODO for correct DOT output, need to html string escape the chars at some point
// single char transition
if(chars[0] == chars[1]){
try formatTransitionChar(chars[0], writer);
} // anychar transition
else if(chars[0] == 1 and chars[1] == 255){
try writer.print("any", .{});
} // range transition
else{
try formatTransitionChar(chars[0], writer);
try writer.writeByte('-');
try formatTransitionChar(chars[1], writer);
}
}
const Token = struct {
char:u8,
kind:Kind,
pub const Kind = enum {
Char,
AnyChar,
Concat,
Union,
Kleen,
LParen,
RParen,
// syntactic sugar
Plus,
Question,
RangeMinus,
RangeInvert,
LSquareBrack,
RSquareBrack,
// hope that the compiler knows that this is often used at comptime
pub fn precedenceAndChar(self:@This()) struct{prec:u8, char:u8} {
return switch(self){
Kind.AnyChar => .{.prec = 0, .char = '.'},
Kind.Union => .{.prec = 1, .char = '|'},
Kind.Concat => .{.prec = 2, .char = ' '},
Kind.Kleen => .{.prec = 3, .char = '*'},
Kind.Plus => .{.prec = 3, .char = '+'},
Kind.Question => .{.prec = 3, .char = '?'},
Kind.LParen => .{.prec = 0, .char = '('},
Kind.RParen => .{.prec = 0, .char = ')'},
Kind.LSquareBrack => .{.prec = 0, .char = '['},
// e.g. char, RangeInvert, RangeMinus
else => .{.prec = 0, .char = 'x'},
};
}
pub fn fromChar(theChar:u8) @This() {
// this seems to get compiled into smth proper
return switch(theChar){
Kind.AnyChar.precedenceAndChar().char => Kind.AnyChar,
Kind.Union.precedenceAndChar().char => Kind.Union,
Kind.Kleen.precedenceAndChar().char => Kind.Kleen,
Kind.Plus.precedenceAndChar().char => Kind.Plus,
Kind.Question.precedenceAndChar().char => Kind.Question,
Kind.LParen.precedenceAndChar().char => Kind.LParen,
Kind.RParen.precedenceAndChar().char => Kind.RParen,
Kind.LSquareBrack.precedenceAndChar().char => Kind.LSquareBrack,
else => Kind.Char
};
}
pub fn fromCharInsideCharRangeGroup(theChar:u8) @This() {
// this seems to get compiled into smth proper
return switch(theChar){
'^' => Kind.RangeInvert,
'-' => Kind.RangeMinus,
// rsquarebrack is only a special char inside a char range group
']' => Kind.RSquareBrack,
// inside a char range group, a period and all other special chars are just normal chars
else => Kind.Char,
};
}
pub fn canConcatToRight(self:@This()) bool {
return switch(self){
Kind.Char => true,
Kind.AnyChar => true,
Kind.Kleen => true,
Kind.Plus => true,
Kind.Question => true,
Kind.RParen => true,
Kind.RSquareBrack => true,
else => false
};
}
pub fn canConcatToLeft(self:@This()) bool {
return switch(self){
Kind.Char => true,
Kind.AnyChar => true,
Kind.LParen => true,
Kind.LSquareBrack => true,
else => false
};
}
};
pub fn initChar(char:u8) @This() {
return Token{
.kind = Token.Kind.fromChar(char),
.char = char
};
}
pub fn initCharInsideCharRangeGroup(char:u8) @This() {
return Token{
.kind = Token.Kind.fromCharInsideCharRangeGroup(char),
.char = char
};
}
pub fn initKind(kind:Kind) @This() {
return Token{
.kind = kind,
.char = kind.precedenceAndChar().char
};
}
};
const SeeDiagError = error{SeeDiag, OutOfMemory};
const SyntaxError = error{InvalidToken, PrematureEnd, UnmatchedCharGroupBracket};
const ParseError = error{OutOfMemory, ExpressionInvalid, SemanticallyInvalidRange} || SyntaxError;
const CompileError = ParseError;
const Diag = struct{
msgs:std.ArrayList(Msg),
const Msg = struct{
const Kind = union(enum) {
Error:CompileError,
Warning:void,
};
kind:Kind,
// inclusive-start exclusive-end index into token array, not source string (!)
location:Pair(u32, u32),
str:[]const u8,
};
pub fn init(allocator:Allocator) @This() {
return @This(){
.msgs = std.ArrayList(Msg).init(allocator),