vb6parse 1.0.1

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! # Partition Function
//!
//! Returns a String indicating where a number occurs within a calculated series of ranges.
//!
//! ## Syntax
//!
//! ```vb
//! Partition(number, start, stop, interval)
//! ```
//!
//! ## Parameters
//!
//! - `number` - Required. Whole number that you want to locate within one of the ranges.
//! - `start` - Required. Whole number that is the start of the overall range of numbers. Cannot be less than 0.
//! - `stop` - Required. Whole number that is the end of the overall range of numbers. Cannot be equal to or less than `start`.
//! - `interval` - Required. Whole number that indicates the size of each range from `start` to `stop`. Cannot be less than 1.
//!
//! ## Return Value
//!
//! Returns a `String` describing the range in which `number` falls. The format is:
//! - `"lowerbound:upperbound"` for ranges within the series
//! - `" :lowerbound-1"` for values less than `start`
//! - `"upperbound+1: "` for values greater than `stop`
//!
//! ## Remarks
//!
//! The `Partition` function divides a range of numbers into smaller intervals and returns a string
//! describing which interval contains a given number. This is particularly useful for creating
//! frequency distributions, histograms, and grouping data into bins.
//!
//! The function creates ranges starting at `start` and ending at `stop`, with each range having
//! a width of `interval`. The returned string always has the same width for both the lower and
//! upper boundaries, padded with leading spaces as needed. This ensures consistent formatting
//! when building reports or tables.
//!
//! For example, if `start` is 0, `stop` is 100, and `interval` is 10, the function creates
//! ranges: 0:9, 10:19, 20:29, etc., plus special ranges for values below 0 (":–1") and
//! above 100 ("101:").
//!
//! The width of each number in the returned string is calculated based on the number of digits
//! in `stop` plus 1. This ensures all ranges align properly in columnar displays.
//!
//! ## Typical Uses
//!
//! 1. **Frequency Distribution**: Creating frequency tables for statistical analysis
//! 2. **Histogram Generation**: Grouping data into bins for histogram charts
//! 3. **Age Group Analysis**: Categorizing people into age brackets (0-9, 10-19, etc.)
//! 4. **Sales Range Reports**: Grouping sales figures into ranges for analysis
//! 5. **Performance Banding**: Categorizing test scores or metrics into performance bands
//! 6. **Data Binning**: Organizing continuous data into discrete categories
//! 7. **Time Period Grouping**: Grouping timestamps into hour, day, or week ranges
//! 8. **Price Range Analysis**: Categorizing products by price ranges
//!
//! ## Basic Examples
//!
//! ### Example 1: Simple Partition
//! ```vb
//! Dim range As String
//! range = Partition(15, 0, 100, 10)    ' Returns " 10: 19"
//! range = Partition(5, 0, 100, 10)     ' Returns "  0:  9"
//! range = Partition(95, 0, 100, 10)    ' Returns " 90: 99"
//! ```
//!
//! ### Example 2: Frequency Distribution
//! ```vb
//! ' Count how many values fall in each range
//! Dim values(100) As Integer
//! Dim frequency As Collection
//! Dim i As Integer
//! Dim range As String
//!
//! Set frequency = New Collection
//!
//! ' Populate with sample data
//! For i = 0 To 100
//!     values(i) = Int(Rnd * 100)
//! Next i
//!
//! ' Count frequencies
//! For i = 0 To 100
//!     range = Partition(values(i), 0, 99, 10)
//!     ' Increment count for this range
//! Next i
//! ```
//!
//! ### Example 3: Age Grouping
//! ```vb
//! Function GetAgeGroup(age As Integer) As String
//!     ' Group ages into decades
//!     GetAgeGroup = Partition(age, 0, 100, 10)
//! End Function
//!
//! ' Usage
//! Debug.Print GetAgeGroup(25)    ' Returns " 20: 29"
//! Debug.Print GetAgeGroup(5)     ' Returns "  0:  9"
//! ```
//!
//! ### Example 4: Out of Range Values
//! ```vb
//! Dim range As String
//! range = Partition(-5, 0, 100, 10)    ' Returns "   : -1" (below start)
//! range = Partition(150, 0, 100, 10)   ' Returns "101:   " (above stop)
//! ```
//!
//! ## Common Patterns
//!
//! ### Pattern 1: `BuildFrequencyTable`
//! ```vb
//! Function BuildFrequencyTable(values() As Integer, start As Long, _
//!                              stop As Long, interval As Long) As Collection
//!     Dim i As Integer
//!     Dim range As String
//!     Dim count As Long
//!     Dim freq As Collection
//!     
//!     Set freq = New Collection
//!     
//!     ' Initialize all ranges to 0
//!     For i = start To stop Step interval
//!         range = Partition(i, start, stop, interval)
//!         On Error Resume Next
//!         freq.Add 0, range
//!         On Error GoTo 0
//!     Next i
//!     
//!     ' Count occurrences
//!     For i = LBound(values) To UBound(values)
//!         range = Partition(values(i), start, stop, interval)
//!         On Error Resume Next
//!         count = freq(range)
//!         freq.Remove range
//!         freq.Add count + 1, range
//!         On Error GoTo 0
//!     Next i
//!     
//!     Set BuildFrequencyTable = freq
//! End Function
//! ```
//!
//! ### Pattern 2: `GenerateHistogram`
//! ```vb
//! Sub GenerateHistogram(values() As Integer, start As Long, _
//!                       stop As Long, interval As Long)
//!     Dim i As Integer
//!     Dim range As String
//!     Dim counts As Object
//!     Dim currentRange As String
//!     
//!     Set counts = CreateObject("Scripting.Dictionary")
//!     
//!     ' Count frequencies
//!     For i = LBound(values) To UBound(values)
//!         range = Partition(values(i), start, stop, interval)
//!         If Not counts.Exists(range) Then
//!             counts.Add range, 0
//!         End If
//!         counts(range) = counts(range) + 1
//!     Next i
//!     
//!     ' Display histogram
//!     Debug.Print "Range", "Count", "Chart"
//!     Debug.Print String(50, "-")
//!     For Each currentRange In counts.Keys
//!         Debug.Print currentRange, counts(currentRange), _
//!                     String(counts(currentRange), "*")
//!     Next currentRange
//! End Sub
//! ```
//!
//! ### Pattern 3: `ClassifyValue`
//! ```vb
//! Function ClassifyValue(value As Long, start As Long, _
//!                        stop As Long, interval As Long) As String
//!     Dim range As String
//!     range = Partition(value, start, stop, interval)
//!     
//!     If InStr(range, ":") = 1 Then
//!         ClassifyValue = "Below Range"
//!     ElseIf Right(range, 1) = ":" Then
//!         ClassifyValue = "Above Range"
//!     Else
//!         ClassifyValue = "In Range: " & Trim(range)
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 4: `GetRangeBoundaries`
//! ```vb
//! Sub GetRangeBoundaries(partitionStr As String, _
//!                        ByRef lower As Long, ByRef upper As Long)
//!     Dim parts() As String
//!     parts = Split(partitionStr, ":")
//!     
//!     If UBound(parts) = 1 Then
//!         On Error Resume Next
//!         lower = CLng(Trim(parts(0)))
//!         upper = CLng(Trim(parts(1)))
//!         On Error GoTo 0
//!     End If
//! End Sub
//! ' Usage: GetRangeBoundaries(" 20: 29", lower, upper)  ' lower=20, upper=29
//! ```
//!
//! ### Pattern 5: `AnalyzeDataDistribution`
//! ```vb
//! Function AnalyzeDataDistribution(data() As Variant) As String
//!     Dim minVal As Long, maxVal As Long
//!     Dim i As Long
//!     Dim report As String
//!     Dim range As String
//!     Dim counts As Object
//!     
//!     ' Find min and max
//!     minVal = data(LBound(data))
//!     maxVal = data(LBound(data))
//!     For i = LBound(data) + 1 To UBound(data)
//!         If data(i) < minVal Then minVal = data(i)
//!         If data(i) > maxVal Then maxVal = data(i)
//!     Next i
//!     
//!     ' Build frequency table
//!     Set counts = CreateObject("Scripting.Dictionary")
//!     For i = LBound(data) To UBound(data)
//!         range = Partition(data(i), minVal, maxVal, (maxVal - minVal) \ 10)
//!         If Not counts.Exists(range) Then counts.Add range, 0
//!         counts(range) = counts(range) + 1
//!     Next i
//!     
//!     ' Build report
//!     report = "Data Distribution:" & vbCrLf
//!     For Each range In counts.Keys
//!         report = report & range & ": " & counts(range) & vbCrLf
//!     Next range
//!     
//!     AnalyzeDataDistribution = report
//! End Function
//! ```
//!
//! ### Pattern 6: `ValidatePartitionParameters`
//! ```vb
//! Function ValidatePartitionParameters(start As Long, stop As Long, _
//!                                      interval As Long) As Boolean
//!     ValidatePartitionParameters = False
//!     
//!     If start < 0 Then
//!         MsgBox "Start must be >= 0"
//!         Exit Function
//!     End If
//!     
//!     If stop <= start Then
//!         MsgBox "Stop must be > start"
//!         Exit Function
//!     End If
//!     
//!     If interval < 1 Then
//!         MsgBox "Interval must be >= 1"
//!         Exit Function
//!     End If
//!     
//!     ValidatePartitionParameters = True
//! End Function
//! ```
//!
//! ### Pattern 7: `CreateRangeLabels`
//! ```vb
//! Function CreateRangeLabels(start As Long, stop As Long, _
//!                            interval As Long) As String()
//!     Dim labels() As String
//!     Dim count As Long
//!     Dim i As Long
//!     Dim index As Long
//!     
//!     count = (stop - start) \ interval + 3  ' +3 for below, above, and safety
//!     ReDim labels(0 To count)
//!     
//!     index = 0
//!     For i = start To stop Step interval
//!         labels(index) = Partition(i, start, stop, interval)
//!         index = index + 1
//!     Next i
//!     
//!     ReDim Preserve labels(0 To index - 1)
//!     CreateRangeLabels = labels
//! End Function
//! ```
//!
//! ### Pattern 8: `CountInRange`
//! ```vb
//! Function CountInRange(values() As Variant, targetRange As String, _
//!                       start As Long, stop As Long, interval As Long) As Long
//!     Dim i As Long
//!     Dim count As Long
//!     
//!     count = 0
//!     For i = LBound(values) To UBound(values)
//!         If Partition(values(i), start, stop, interval) = targetRange Then
//!             count = count + 1
//!         End If
//!     Next i
//!     
//!     CountInRange = count
//! End Function
//! ```
//!
//! ### Pattern 9: `GetRangeMidpoint`
//! ```vb
//! Function GetRangeMidpoint(partitionStr As String) As Double
//!     Dim lower As Long, upper As Long
//!     Dim parts() As String
//!     
//!     parts = Split(partitionStr, ":")
//!     If UBound(parts) = 1 Then
//!         On Error Resume Next
//!         lower = CLng(Trim(parts(0)))
//!         upper = CLng(Trim(parts(1)))
//!         If Err.Number = 0 Then
//!             GetRangeMidpoint = (lower + upper) / 2
//!         End If
//!         On Error GoTo 0
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 10: `GroupByRange`
//! ```vb
//! Function GroupByRange(values() As Variant, start As Long, _
//!                       stop As Long, interval As Long) As Object
//!     Dim groups As Object
//!     Dim i As Long
//!     Dim range As String
//!     Dim groupItems As Collection
//!     
//!     Set groups = CreateObject("Scripting.Dictionary")
//!     
//!     For i = LBound(values) To UBound(values)
//!         range = Partition(values(i), start, stop, interval)
//!         
//!         If Not groups.Exists(range) Then
//!             Set groupItems = New Collection
//!             groups.Add range, groupItems
//!         End If
//!         
//!         groups(range).Add values(i)
//!     Next i
//!     
//!     Set GroupByRange = groups
//! End Function
//! ```
//!
//! ## Advanced Usage
//!
//! ### Example 1: Statistical Analysis Tool
//! ```vb
//! ' Comprehensive statistical analysis using Partition
//! Class StatisticalAnalyzer
//!     Private m_data() As Double
//!     Private m_binCount As Long
//!     Private m_minValue As Double
//!     Private m_maxValue As Double
//!     
//!     Public Sub LoadData(data() As Double)
//!         Dim i As Long
//!         ReDim m_data(LBound(data) To UBound(data))
//!         
//!         m_minValue = data(LBound(data))
//!         m_maxValue = data(LBound(data))
//!         
//!         For i = LBound(data) To UBound(data)
//!             m_data(i) = data(i)
//!             If data(i) < m_minValue Then m_minValue = data(i)
//!             If data(i) > m_maxValue Then m_maxValue = data(i)
//!         Next i
//!     End Sub
//!     
//!     Public Property Let BinCount(value As Long)
//!         If value > 0 Then m_binCount = value
//!     End Property
//!     
//!     Public Function GetFrequencyDistribution() As Object
//!         Dim freq As Object
//!         Dim i As Long
//!         Dim interval As Long
//!         Dim range As String
//!         Dim start As Long, stop As Long
//!         
//!         Set freq = CreateObject("Scripting.Dictionary")
//!         
//!         start = Int(m_minValue)
//!         stop = Int(m_maxValue)
//!         interval = (stop - start) \ m_binCount
//!         If interval < 1 Then interval = 1
//!         
//!         For i = LBound(m_data) To UBound(m_data)
//!             range = Partition(Int(m_data(i)), start, stop, interval)
//!             If Not freq.Exists(range) Then
//!                 freq.Add range, 0
//!             End If
//!             freq(range) = freq(range) + 1
//!         Next i
//!         
//!         Set GetFrequencyDistribution = freq
//!     End Function
//!     
//!     Public Function GetHistogramData() As Object
//!         Dim histogram As Object
//!         Dim freq As Object
//!         Dim range As Variant
//!         Dim item As Object
//!         
//!         Set freq = GetFrequencyDistribution()
//!         Set histogram = CreateObject("Scripting.Dictionary")
//!         
//!         For Each range In freq.Keys
//!             Set item = CreateObject("Scripting.Dictionary")
//!             item.Add "Range", range
//!             item.Add "Count", freq(range)
//!             item.Add "Percentage", (freq(range) / UBound(m_data)) * 100
//!             histogram.Add range, item
//!         Next range
//!         
//!         Set GetHistogramData = histogram
//!     End Function
//!     
//!     Public Function GenerateReport() As String
//!         Dim report As String
//!         Dim histogram As Object
//!         Dim range As Variant
//!         Dim maxCount As Long
//!         Dim barWidth As Long
//!         
//!         Set histogram = GetHistogramData()
//!         
//!         ' Find max count for scaling
//!         maxCount = 0
//!         For Each range In histogram.Keys
//!             If histogram(range)("Count") > maxCount Then
//!                 maxCount = histogram(range)("Count")
//!             End If
//!         Next range
//!         
//!         report = "Frequency Distribution Report" & vbCrLf
//!         report = report & String(60, "=") & vbCrLf
//!         report = report & "Data Points: " & UBound(m_data) + 1 & vbCrLf
//!         report = report & "Min Value: " & m_minValue & vbCrLf
//!         report = report & "Max Value: " & m_maxValue & vbCrLf
//!         report = report & String(60, "-") & vbCrLf
//!         report = report & "Range          Count    Pct    Chart" & vbCrLf
//!         report = report & String(60, "-") & vbCrLf
//!         
//!         For Each range In histogram.Keys
//!             barWidth = Int((histogram(range)("Count") / maxCount) * 30)
//!             report = report & range & "  " & _
//!                      Format(histogram(range)("Count"), "0000") & "  " & _
//!                      Format(histogram(range)("Percentage"), "00.0") & "%  " & _
//!                      String(barWidth, "#") & vbCrLf
//!         Next range
//!         
//!         GenerateReport = report
//!     End Function
//!     
//!     Public Function GetModeRange() As String
//!         ' Find the range with the highest frequency
//!         Dim freq As Object
//!         Dim range As Variant
//!         Dim maxCount As Long
//!         Dim modeRange As String
//!         
//!         Set freq = GetFrequencyDistribution()
//!         maxCount = 0
//!         
//!         For Each range In freq.Keys
//!             If freq(range) > maxCount Then
//!                 maxCount = freq(range)
//!                 modeRange = range
//!             End If
//!         Next range
//!         
//!         GetModeRange = modeRange
//!     End Function
//! End Class
//! ```
//!
//! ### Example 2: Sales Performance Analyzer
//! ```vb
//! ' Analyze sales performance by grouping into performance bands
//! Module SalesAnalyzer
//!     Private Type SalesRecord
//!         SalesPerson As String
//!         Amount As Currency
//!         Date As Date
//!     End Type
//!     
//!     Public Function AnalyzeSalesPerformance(sales() As SalesRecord) As String
//!         Dim i As Long
//!         Dim minSale As Currency, maxSale As Currency
//!         Dim interval As Currency
//!         Dim performanceBands As Object
//!         Dim range As String
//!         Dim report As String
//!         Dim totalSales As Long
//!         
//!         ' Find range
//!         minSale = sales(LBound(sales)).Amount
//!         maxSale = sales(LBound(sales)).Amount
//!         For i = LBound(sales) To UBound(sales)
//!             If sales(i).Amount < minSale Then minSale = sales(i).Amount
//!             If sales(i).Amount > maxSale Then maxSale = sales(i).Amount
//!         Next i
//!         
//!         ' Create 5 performance bands
//!         interval = Int((maxSale - minSale) / 5)
//!         If interval < 1 Then interval = 1
//!         
//!         Set performanceBands = CreateObject("Scripting.Dictionary")
//!         
//!         ' Categorize sales
//!         totalSales = UBound(sales) - LBound(sales) + 1
//!         For i = LBound(sales) To UBound(sales)
//!             range = Partition(Int(sales(i).Amount), Int(minSale), _
//!                              Int(maxSale), interval)
//!             If Not performanceBands.Exists(range) Then
//!                 performanceBands.Add range, 0
//!             End If
//!             performanceBands(range) = performanceBands(range) + 1
//!         Next i
//!         
//!         ' Generate report
//!         report = "Sales Performance Analysis" & vbCrLf
//!         report = report & String(50, "=") & vbCrLf
//!         report = report & "Total Sales: " & totalSales & vbCrLf
//!         report = report & "Range: $" & Format(minSale, "#,##0") & _
//!                  " - $" & Format(maxSale, "#,##0") & vbCrLf
//!         report = report & String(50, "-") & vbCrLf
//!         
//!         For Each range In performanceBands.Keys
//!             report = report & "Range " & range & ": " & _
//!                      performanceBands(range) & " sales (" & _
//!                      Format((performanceBands(range) / totalSales) * 100, "0.0") & _
//!                      "%)" & vbCrLf
//!         Next range
//!         
//!         AnalyzeSalesPerformance = report
//!     End Function
//!     
//!     Public Function GetPerformanceLevel(amount As Currency, _
//!                                         minAmount As Currency, _
//!                                         maxAmount As Currency) As String
//!         Dim range As String
//!         Dim interval As Currency
//!         
//!         interval = (maxAmount - minAmount) / 5
//!         range = Partition(Int(amount), Int(minAmount), Int(maxAmount), Int(interval))
//!         
//!         ' Convert to performance labels
//!         Dim parts() As String
//!         Dim lowerBound As Long
//!         parts = Split(range, ":")
//!         
//!         On Error Resume Next
//!         lowerBound = CLng(Trim(parts(0)))
//!         On Error GoTo 0
//!         
//!         If lowerBound <= minAmount + interval Then
//!             GetPerformanceLevel = "Needs Improvement"
//!         ElseIf lowerBound <= minAmount + interval * 2 Then
//!             GetPerformanceLevel = "Below Average"
//!         ElseIf lowerBound <= minAmount + interval * 3 Then
//!             GetPerformanceLevel = "Average"
//!         ElseIf lowerBound <= minAmount + interval * 4 Then
//!             GetPerformanceLevel = "Above Average"
//!         Else
//!             GetPerformanceLevel = "Excellent"
//!         End If
//!     End Function
//! End Module
//! ```
//!
//! ### Example 3: Age Demographics Tool
//! ```vb
//! ' Tool for analyzing age demographics with Partition
//! Class AgeDemographicsAnalyzer
//!     Private m_ages() As Integer
//!     Private m_ageGroupSize As Integer
//!     
//!     Public Sub Initialize(ages() As Integer, groupSize As Integer)
//!         Dim i As Long
//!         ReDim m_ages(LBound(ages) To UBound(ages))
//!         For i = LBound(ages) To UBound(ages)
//!             m_ages(i) = ages(i)
//!         Next i
//!         m_ageGroupSize = groupSize
//!     End Sub
//!     
//!     Public Function GetAgeDistribution() As Object
//!         Dim dist As Object
//!         Dim i As Long
//!         Dim range As String
//!         
//!         Set dist = CreateObject("Scripting.Dictionary")
//!         
//!         For i = LBound(m_ages) To UBound(m_ages)
//!             range = Partition(m_ages(i), 0, 120, m_ageGroupSize)
//!             If Not dist.Exists(range) Then
//!                 dist.Add range, 0
//!             End If
//!             dist(range) = dist(range) + 1
//!         Next i
//!         
//!         Set GetAgeDistribution = dist
//!     End Function
//!     
//!     Public Function GetAgeGroupName(age As Integer) As String
//!         Dim range As String
//!         range = Partition(age, 0, 120, m_ageGroupSize)
//!         
//!         Select Case m_ageGroupSize
//!             Case 10
//!                 ' Decades
//!                 If InStr(range, " 0:") > 0 Then
//!                     GetAgeGroupName = "Children (0-9)"
//!                 ElseIf InStr(range, "10:") > 0 Then
//!                     GetAgeGroupName = "Teens (10-19)"
//!                 ElseIf InStr(range, "20:") > 0 Then
//!                     GetAgeGroupName = "Twenties (20-29)"
//!                 ElseIf InStr(range, "30:") > 0 Then
//!                     GetAgeGroupName = "Thirties (30-39)"
//!                 ElseIf InStr(range, "40:") > 0 Then
//!                     GetAgeGroupName = "Forties (40-49)"
//!                 ElseIf InStr(range, "50:") > 0 Then
//!                     GetAgeGroupName = "Fifties (50-59)"
//!                 ElseIf InStr(range, "60:") > 0 Then
//!                     GetAgeGroupName = "Sixties (60-69)"
//!                 Else
//!                     GetAgeGroupName = "70+"
//!                 End If
//!             Case Else
//!                 GetAgeGroupName = Trim(range)
//!         End Select
//!     End Function
//!     
//!     Public Function GenerateDemographicsReport() As String
//!         Dim report As String
//!         Dim dist As Object
//!         Dim range As Variant
//!         Dim total As Long
//!         
//!         Set dist = GetAgeDistribution()
//!         total = UBound(m_ages) - LBound(m_ages) + 1
//!         
//!         report = "Age Demographics Report" & vbCrLf
//!         report = report & String(50, "=") & vbCrLf
//!         report = report & "Total Population: " & total & vbCrLf
//!         report = report & "Age Group Size: " & m_ageGroupSize & " years" & vbCrLf
//!         report = report & String(50, "-") & vbCrLf
//!         report = report & "Age Range      Count    Percentage" & vbCrLf
//!         report = report & String(50, "-") & vbCrLf
//!         
//!         For Each range In dist.Keys
//!             report = report & range & "  " & _
//!                      Format(dist(range), "0000") & "    " & _
//!                      Format((dist(range) / total) * 100, "00.0") & "%" & vbCrLf
//!         Next range
//!         
//!         GenerateDemographicsReport = report
//!     End Function
//!     
//!     Public Function GetMedianAgeRange() As String
//!         ' Find the range containing the median age
//!         Dim sortedAges() As Integer
//!         Dim i As Long
//!         Dim medianAge As Integer
//!         
//!         ' Copy and sort ages
//!         ReDim sortedAges(LBound(m_ages) To UBound(m_ages))
//!         For i = LBound(m_ages) To UBound(m_ages)
//!             sortedAges(i) = m_ages(i)
//!         Next i
//!         
//!         ' Simple bubble sort (for demonstration)
//!         Dim temp As Integer, j As Long
//!         For i = LBound(sortedAges) To UBound(sortedAges) - 1
//!             For j = i + 1 To UBound(sortedAges)
//!                 If sortedAges(i) > sortedAges(j) Then
//!                     temp = sortedAges(i)
//!                     sortedAges(i) = sortedAges(j)
//!                     sortedAges(j) = temp
//!                 End If
//!             Next j
//!         Next i
//!         
//!         ' Get median
//!         medianAge = sortedAges((LBound(sortedAges) + UBound(sortedAges)) \ 2)
//!         
//!         GetMedianAgeRange = Partition(medianAge, 0, 120, m_ageGroupSize)
//!     End Function
//! End Class
//! ```
//!
//! ### Example 4: Test Score Grading System
//! ```vb
//! ' Automatic grading system using Partition
//! Module GradingSystem
//!     Public Function GetLetterGrade(score As Integer) As String
//!         Dim range As String
//!         
//!         ' Use Partition to determine grade range (0-100, intervals of 10)
//!         range = Partition(score, 0, 100, 10)
//!         
//!         ' Convert range to letter grade
//!         If score >= 90 Then
//!             GetLetterGrade = "A"
//!         ElseIf score >= 80 Then
//!             GetLetterGrade = "B"
//!         ElseIf score >= 70 Then
//!             GetLetterGrade = "C"
//!         ElseIf score >= 60 Then
//!             GetLetterGrade = "D"
//!         Else
//!             GetLetterGrade = "F"
//!         End If
//!     End Function
//!     
//!     Public Function AnalyzeClassScores(scores() As Integer) As String
//!         Dim gradeDistribution As Object
//!         Dim i As Long
//!         Dim range As String
//!         Dim report As String
//!         Dim total As Long
//!         
//!         Set gradeDistribution = CreateObject("Scripting.Dictionary")
//!         total = UBound(scores) - LBound(scores) + 1
//!         
//!         ' Count scores in each range
//!         For i = LBound(scores) To UBound(scores)
//!             range = Partition(scores(i), 0, 100, 10)
//!             If Not gradeDistribution.Exists(range) Then
//!                 gradeDistribution.Add range, 0
//!             End If
//!             gradeDistribution(range) = gradeDistribution(range) + 1
//!         Next i
//!         
//!         ' Build report
//!         report = "Class Score Distribution" & vbCrLf
//!         report = report & String(40, "=") & vbCrLf
//!         report = report & "Total Students: " & total & vbCrLf
//!         report = report & String(40, "-") & vbCrLf
//!         
//!         For Each range In gradeDistribution.Keys
//!             report = report & range & ": " & gradeDistribution(range) & _
//!                      " (" & Format((gradeDistribution(range) / total) * 100, "0.0") & _
//!                      "%)" & vbCrLf
//!         Next range
//!         
//!         AnalyzeClassScores = report
//!     End Function
//!     
//!     Public Function GetClassStatistics(scores() As Integer) As Object
//!         Dim stats As Object
//!         Dim dist As Object
//!         Dim i As Long
//!         Dim range As String
//!         Dim sum As Long
//!         Dim passingCount As Long
//!         
//!         Set stats = CreateObject("Scripting.Dictionary")
//!         Set dist = CreateObject("Scripting.Dictionary")
//!         
//!         sum = 0
//!         passingCount = 0
//!         
//!         For i = LBound(scores) To UBound(scores)
//!             sum = sum + scores(i)
//!             If scores(i) >= 60 Then passingCount = passingCount + 1
//!             
//!             range = Partition(scores(i), 0, 100, 10)
//!             If Not dist.Exists(range) Then dist.Add range, 0
//!             dist(range) = dist(range) + 1
//!         Next i
//!         
//!         stats.Add "Average", sum / (UBound(scores) - LBound(scores) + 1)
//!         stats.Add "PassingRate", (passingCount / (UBound(scores) - LBound(scores) + 1)) * 100
//!         stats.Add "Distribution", dist
//!         
//!         Set GetClassStatistics = stats
//!     End Function
//! End Module
//! ```
//!
//! ## Error Handling
//!
//! The `Partition` function can raise errors in the following situations:
//!
//! - **Invalid Procedure Call (Error 5)**: When:
//!   - `start` is less than 0
//!   - `stop` is less than or equal to `start`
//!   - `interval` is less than 1
//! - **Type Mismatch (Error 13)**: When arguments cannot be converted to whole numbers
//! - **Overflow (Error 6)**: When calculated values exceed data type limits
//!
//! Always validate parameters before calling `Partition`:
//!
//! ```vb
//! If start >= 0 And stop > start And interval >= 1 Then
//!     range = Partition(value, start, stop, interval)
//! Else
//!     MsgBox "Invalid partition parameters"
//! End If
//! ```
//!
//! ## Performance Considerations
//!
//! - The `Partition` function is very fast for individual calls
//! - String formatting overhead is minimal but can add up with millions of calls
//! - For large datasets, consider caching partition ranges if the same parameters are used
//! - Dictionary/Collection operations for frequency counting are generally efficient
//! - Sorting large arrays for statistical analysis can be slow; consider alternative algorithms
//!
//! ## Best Practices
//!
//! 1. **Validate Parameters**: Always check that start >= 0, stop > start, and interval >= 1
//! 2. **Choose Appropriate Intervals**: Select interval sizes that create meaningful groups
//! 3. **Handle Edge Cases**: Account for values below start and above stop
//! 4. **Use Consistent Formatting**: Leverage the automatic padding for aligned displays
//! 5. **Parse Results Carefully**: Remember the format includes spaces and colons
//! 6. **Consider Alternatives**: For simple range checks, If statements may be clearer
//! 7. **Document Ranges**: Clearly document the meaning of each partition range
//! 8. **Test Boundaries**: Verify behavior at start, stop, and interval boundaries
//! 9. **Cache When Possible**: If using same parameters repeatedly, cache the range labels
//! 10. **Combine with Collections**: Use Dictionary or Collection for frequency counting
//!
//! ## Comparison with Related Functions
//!
//! | Function | Purpose | Returns | Use Case |
//! |----------|---------|---------|----------|
//! | **Partition** | Create range labels | String (range description) | Frequency distributions, histograms |
//! | **Switch** | Choose from value pairs | Variant (matched value) | Simple value mapping |
//! | **Choose** | Pick from list by index | Variant (indexed item) | Select from fixed options |
//! | **`IIf`** | Conditional expression | Variant (true/false result) | Simple binary choices |
//! | **Select Case** | Multi-way branching | N/A (statement) | Complex conditional logic |
//!
//! ## Platform and Version Notes
//!
//! - Available in VBA and VB6
//! - Behavior is consistent across Windows platforms
//! - The returned string format is fixed and cannot be customized
//! - All parameters must be whole numbers (fractional parts are truncated)
//! - Maximum values limited by Long data type (approximately ±2 billion)
//!
//! ## Limitations
//!
//! - Only works with whole numbers; fractional values are truncated
//! - Cannot customize the output format (padding, separators, etc.)
//! - Parameters must fit in Long data type range
//! - No built-in frequency counting; must implement separately
//! - String result requires parsing to extract numeric boundaries
//! - Cannot specify custom labels for ranges
//! - All ranges must have equal intervals (except first/last special cases)
//!
//! ## Related Functions
//!
//! - `Switch`: Evaluates a list of expressions and returns associated value
//! - `Choose`: Returns a value from a list based on position
//! - `IIf`: Returns one of two values based on a condition
//! - `Format`: Formats values as strings with custom patterns
//! - `InStr`: Searches for substring within a string (useful for parsing Partition results)

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn partition_basic() {
        let source = r"
Dim range As String
range = Partition(15, 0, 100, 10)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_with_variables() {
        let source = r"
Dim value As Integer
Dim rangeStr As String
value = 42
rangeStr = Partition(value, 0, 100, 10)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_if_statement() {
        let source = r#"
If Partition(score, 0, 100, 10) = " 90: 99" Then
    MsgBox "Grade A"
End If
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_function_return() {
        let source = r"
Function GetAgeRange(age As Integer) As String
    GetAgeRange = Partition(age, 0, 100, 10)
End Function
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_variable_assignment() {
        let source = r"
Dim bucket As String
bucket = Partition(salesAmount, 0, 1000, 100)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_msgbox() {
        let source = r#"
MsgBox "Value falls in range: " & Partition(num, 0, 50, 5)
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_debug_print() {
        let source = r#"
Debug.Print "Range: " & Partition(value, min, max, interval)
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_select_case() {
        let source = r#"
Select Case Partition(score, 0, 100, 20)
    Case "  0: 19"
        grade = "F"
    Case " 80: 99"
        grade = "A"
    Case Else
        grade = "Other"
End Select
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_class_usage() {
        let source = r"
Private m_range As String

Public Sub CategorizeValue(num As Long)
    m_range = Partition(num, 0, 1000, 100)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_with_statement() {
        let source = r"
With analyzer
    .RangeLabel = Partition(.Value, .MinVal, .MaxVal, .Interval)
End With
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_elseif() {
        let source = r#"
If x < 0 Then
    y = 1
ElseIf Partition(x, 0, 100, 10) = " 50: 59" Then
    y = 2
End If
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_for_loop() {
        let source = r"
For i = 0 To 100
    rangeStr = Partition(i, 0, 100, 10)
    Debug.Print i, rangeStr
Next i
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_do_while() {
        let source = r#"
Do While Partition(counter, 0, 100, 10) <> "100:   "
    counter = counter + 1
Loop
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_do_until() {
        let source = r#"
Do Until Partition(val, 1, 50, 5) = " 46: 50"
    val = val + 1
Loop
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_while_wend() {
        let source = r#"
While InStr(Partition(num, 0, 1000, 100), "500") = 0
    num = num + 10
Wend
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_parentheses() {
        let source = r"
Dim result As String
result = (Partition(value, 0, 100, 25))
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_iif() {
        let source = r"
Dim label As String
label = IIf(usePartition, Partition(val, 0, 100, 10), CStr(val))
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_comparison() {
        let source = r#"
If Partition(val1, 0, 100, 10) = Partition(val2, 0, 100, 10) Then
    MsgBox "Same range"
End If
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_array_assignment() {
        let source = r"
Dim ranges(100) As String
ranges(i) = Partition(values(i), 0, 1000, 50)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_property_assignment() {
        let source = r"
Set obj = New DataAnalyzer
obj.RangeBucket = Partition(obj.DataValue, 0, 500, 50)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_function_argument() {
        let source = r"
Call ProcessRange(Partition(score, 0, 100, 10), studentName)
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_arithmetic() {
        let source = r"
Dim rangeCount As Integer
rangeCount = Len(Partition(value, 0, 100, 10))
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_concatenation() {
        let source = r#"
Dim msg As String
msg = "Value " & value & " is in range " & Partition(value, 0, 100, 10)
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_instr() {
        let source = r#"
Dim pos As Integer
pos = InStr(Partition(num, 0, 100, 10), ":")
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_trim() {
        let source = r"
Dim cleaned As String
cleaned = Trim(Partition(value, 0, 1000, 100))
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_error_handling() {
        let source = r#"
On Error Resume Next
rangeLabel = Partition(userInput, startVal, stopVal, intervalVal)
If Err.Number <> 0 Then
    MsgBox "Invalid partition parameters"
End If
On Error GoTo 0
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn partition_on_error_goto() {
        let source = r#"
Sub CategorizeData()
    On Error GoTo ErrorHandler
    Dim bucket As String
    bucket = Partition(dataValue, minValue, maxValue, step)
    Exit Sub
ErrorHandler:
    MsgBox "Error in partition calculation"
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(
            "../../../../../snapshots/syntax/library/functions/graphics/partition",
        );
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }
}