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
//! # Replace Function
//!
//! Returns a string in which a specified substring has been replaced with another substring a specified number of times.
//!
//! ## Syntax
//!
//! ```vb
//! Replace(expression, find, replace, [start], [count], [compare])
//! ```
//!
//! ## Parameters
//!
//! - `expression` - Required. String expression containing substring to replace.
//! - `find` - Required. Substring being searched for.
//! - `replace` - Required. Replacement substring.
//! - `start` - Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed. Must be used in conjunction with count.
//! - `count` - Optional. Number of substring substitutions to perform. If omitted, default value is -1, which means make all possible substitutions.
//! - `compare` - Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, 0 is assumed (vbBinaryCompare).
//!
//! ## Compare Values
//!
//! | Constant | Value | Description |
//! |----------|-------|-------------|
//! | vbBinaryCompare | 0 | Perform a binary comparison (case-sensitive) |
//! | vbTextCompare | 1 | Perform a textual comparison (case-insensitive) |
//! | vbDatabaseCompare | 2 | Perform a comparison based on database settings (Microsoft Access only) |
//!
//! ## Return Value
//!
//! Returns a `String` with the replacements made. The return value depends on the parameters:
//!
//! | If | Replace Returns |
//! |-----|----------------|
//! | expression is zero-length | Zero-length string ("") |
//! | expression is Null | An error |
//! | find is zero-length | Copy of expression |
//! | replace is zero-length | Copy of expression with all find occurrences removed |
//! | start > Len(expression) | Zero-length string ("") |
//! | count is 0 | Copy of expression |
//!
//! ## Remarks
//!
//! The `Replace` function returns a string with substitutions made. Unlike the `Replace` method of regular expressions, this function performs simple string substitution without pattern matching.
//!
//! The return value of the `Replace` function is a string that begins at the position specified by `start`, with substitutions made, and concludes at the end of the `expression` string. It is not a copy of the original string from start to finish.
//!
//! **Important Notes**:
//! - If `start` is specified, the return value starts from that position, not from position 1
//! - The original string before `start` position is not included in the result
//! - Use `count` parameter to limit the number of replacements
//! - Binary comparison (default) is case-sensitive; textual comparison is case-insensitive
//! - Empty `find` string returns the original expression unchanged
//! - Empty `replace` string removes all occurrences of `find`
//!
//! ## Typical Uses
//!
//! 1. **Text Sanitization**: Remove or replace unwanted characters from user input
//! 2. **Data Formatting**: Replace delimiters or format characters in data
//! 3. **Template Processing**: Replace placeholders in template strings
//! 4. **Path Manipulation**: Replace path separators or modify file paths
//! 5. **Case Normalization**: Replace mixed-case text with standardized case
//! 6. **String Cleaning**: Remove multiple spaces, tabs, or other whitespace
//! 7. **Data Import/Export**: Convert between different data formats
//! 8. **SQL String Building**: Escape quotes and special characters
//!
//! ## Basic Examples
//!
//! ### Example 1: Simple Replacement
//! ```vb
//! Dim result As String
//! result = Replace("Hello World", "World", "VB6")
//! ' Returns: "Hello VB6"
//! ```
//!
//! ### Example 2: Case-Insensitive Replacement
//! ```vb
//! Dim result As String
//! result = Replace("Hello WORLD", "world", "VB6", 1, -1, vbTextCompare)
//! ' Returns: "Hello VB6"
//! ```
//!
//! ### Example 3: Remove Substring
//! ```vb
//! Dim cleaned As String
//! cleaned = Replace("Remove   extra   spaces", "   ", " ")
//! ' Returns: "Remove extra spaces"
//! ```
//!
//! ### Example 4: Limited Replacements
//! ```vb
//! Dim result As String
//! result = Replace("one, two, three, four", ", ", " | ", 1, 2)
//! ' Returns: "one | two | three, four" (only first 2 commas replaced)
//! ```
//!
//! ## Common Patterns
//!
//! ### Pattern 1: `RemoveAllSpaces`
//! ```vb
//! Function RemoveAllSpaces(text As String) As String
//!     RemoveAllSpaces = Replace(text, " ", "")
//! End Function
//! ```
//!
//! ### Pattern 2: `NormalizeWhitespace`
//! ```vb
//! Function NormalizeWhitespace(text As String) As String
//!     Dim result As String
//!     result = text
//!     
//!     ' Replace tabs with spaces
//!     result = Replace(result, vbTab, " ")
//!     
//!     ' Replace multiple spaces with single space
//!     Do While InStr(result, "  ") > 0
//!         result = Replace(result, "  ", " ")
//!     Loop
//!     
//!     NormalizeWhitespace = Trim(result)
//! End Function
//! ```
//!
//! ### Pattern 3: `EscapeSQLString`
//! ```vb
//! Function EscapeSQLString(text As String) As String
//!     ' Escape single quotes for SQL
//!     EscapeSQLString = Replace(text, "'", "''")
//! End Function
//! ```
//!
//! ### Pattern 4: `ReplaceMultiple`
//! ```vb
//! Function ReplaceMultiple(text As String, findList() As String, _
//!                          replaceList() As String) As String
//!     Dim i As Integer
//!     Dim result As String
//!     
//!     result = text
//!     
//!     For i = LBound(findList) To UBound(findList)
//!         result = Replace(result, findList(i), replaceList(i))
//!     Next i
//!     
//!     ReplaceMultiple = result
//! End Function
//! ```
//!
//! ### Pattern 5: `ReplaceCaseInsensitive`
//! ```vb
//! Function ReplaceCaseInsensitive(text As String, find As String, _
//!                                replaceWith As String) As String
//!     ReplaceCaseInsensitive = Replace(text, find, replaceWith, 1, -1, vbTextCompare)
//! End Function
//! ```
//!
//! ### Pattern 6: `ReplaceSpecialChars`
//! ```vb
//! Function ReplaceSpecialChars(text As String, replacement As String) As String
//!     Dim result As String
//!     Dim specialChars As String
//!     Dim i As Integer
//!     
//!     result = text
//!     specialChars = "!@#$%^&*()[]{}|;:,.<>?/"
//!     
//!     For i = 1 To Len(specialChars)
//!         result = Replace(result, Mid(specialChars, i, 1), replacement)
//!     Next i
//!     
//!     ReplaceSpecialChars = result
//! End Function
//! ```
//!
//! ### Pattern 7: `SanitizeFilename`
//! ```vb
//! Function SanitizeFilename(filename As String) As String
//!     Dim result As String
//!     Dim invalidChars As String
//!     Dim i As Integer
//!     
//!     result = filename
//!     invalidChars = "\/:*?""<>|"
//!     
//!     For i = 1 To Len(invalidChars)
//!         result = Replace(result, Mid(invalidChars, i, 1), "_")
//!     Next i
//!     
//!     SanitizeFilename = result
//! End Function
//! ```
//!
//! ### Pattern 8: `ConvertLineEndings`
//! ```vb
//! Function ConvertLineEndings(text As String, newEnding As String) As String
//!     Dim result As String
//!     
//!     result = text
//!     
//!     ' Normalize to LF first
//!     result = Replace(result, vbCrLf, vbLf)
//!     result = Replace(result, vbCr, vbLf)
//!     
//!     ' Convert to desired ending
//!     If newEnding <> vbLf Then
//!         result = Replace(result, vbLf, newEnding)
//!     End If
//!     
//!     ConvertLineEndings = result
//! End Function
//! ```
//!
//! ### Pattern 9: `ReplaceWithCounter`
//! ```vb
//! Function CountReplacements(text As String, find As String) As Long
//!     ' Count how many times find appears in text
//!     Dim original As String
//!     Dim replaced As String
//!     
//!     If Len(find) = 0 Then
//!         CountReplacements = 0
//!         Exit Function
//!     End If
//!     
//!     original = text
//!     replaced = Replace(original, find, "")
//!     
//!     CountReplacements = (Len(original) - Len(replaced)) / Len(find)
//! End Function
//! ```
//!
//! ### Pattern 10: `TemplateReplace`
//! ```vb
//! Function ProcessTemplate(template As String, replacements As Collection) As String
//!     ' Replace {key} placeholders with values from collection
//!     Dim result As String
//!     Dim key As Variant
//!     Dim placeholder As String
//!     
//!     result = template
//!     
//!     For Each key In replacements
//!         placeholder = "{" & key & "}"
//!         result = Replace(result, placeholder, CStr(replacements(key)))
//!     Next key
//!     
//!     ProcessTemplate = result
//! End Function
//! ```
//!
//! ## Advanced Usage
//!
//! ### Example 1: Text Sanitizer with Multiple Rules
//! ```vb
//! ' Advanced text sanitization with configurable rules
//! Class TextSanitizer
//!     Private Type ReplacementRule
//!         Find As String
//!         ReplaceWith As String
//!         CaseSensitive As Boolean
//!         MaxReplacements As Long
//!     End Type
//!     
//!     Private m_rules() As ReplacementRule
//!     Private m_ruleCount As Integer
//!     
//!     Public Sub Initialize()
//!         m_ruleCount = 0
//!         ReDim m_rules(0 To 9)
//!     End Sub
//!     
//!     Public Sub AddRule(find As String, replaceWith As String, _
//!                       Optional caseSensitive As Boolean = True, _
//!                       Optional maxReplacements As Long = -1)
//!         If m_ruleCount > UBound(m_rules) Then
//!             ReDim Preserve m_rules(0 To UBound(m_rules) + 10)
//!         End If
//!         
//!         With m_rules(m_ruleCount)
//!             .Find = find
//!             .ReplaceWith = replaceWith
//!             .CaseSensitive = caseSensitive
//!             .MaxReplacements = maxReplacements
//!         End With
//!         
//!         m_ruleCount = m_ruleCount + 1
//!     End Sub
//!     
//!     Public Function Sanitize(text As String) As String
//!         Dim result As String
//!         Dim i As Integer
//!         Dim compareMode As Integer
//!         
//!         result = text
//!         
//!         For i = 0 To m_ruleCount - 1
//!             With m_rules(i)
//!                 If .CaseSensitive Then
//!                     compareMode = vbBinaryCompare
//!                 Else
//!                     compareMode = vbTextCompare
//!                 End If
//!                 
//!                 result = Replace(result, .Find, .ReplaceWith, 1, .MaxReplacements, compareMode)
//!             End With
//!         Next i
//!         
//!         Sanitize = result
//!     End Function
//!     
//!     Public Sub ClearRules()
//!         m_ruleCount = 0
//!     End Sub
//!     
//!     Public Function GetRuleCount() As Integer
//!         GetRuleCount = m_ruleCount
//!     End Function
//! End Class
//! ```
//!
//! ### Example 2: String Template Engine
//! ```vb
//! ' Simple template engine with variable replacement
//! Module TemplateEngine
//!     Public Function ProcessTemplate(template As String, _
//!                                    variables As Scripting.Dictionary) As String
//!         Dim result As String
//!         Dim key As Variant
//!         Dim placeholder As String
//!         Dim value As String
//!         
//!         result = template
//!         
//!         ' Replace {variable} placeholders
//!         For Each key In variables.Keys
//!             placeholder = "{" & CStr(key) & "}"
//!             value = CStr(variables(key))
//!             result = Replace(result, placeholder, value)
//!         Next key
//!         
//!         ProcessTemplate = result
//!     End Function
//!     
//!     Public Function ProcessConditional(template As String, condition As Boolean, _
//!                                       trueValue As String, falseValue As String) As String
//!         Dim result As String
//!         
//!         result = template
//!         
//!         If condition Then
//!             result = Replace(result, "{if}", trueValue)
//!             result = Replace(result, "{else}", "")
//!         Else
//!             result = Replace(result, "{if}", "")
//!             result = Replace(result, "{else}", falseValue)
//!         End If
//!         
//!         ProcessConditional = result
//!     End Function
//!     
//!     Public Function ProcessLoop(template As String, items() As String) As String
//!         Dim result As String
//!         Dim itemText As String
//!         Dim i As Integer
//!         
//!         ' Extract the loop template
//!         Dim loopStart As Long
//!         Dim loopEnd As Long
//!         Dim loopTemplate As String
//!         
//!         loopStart = InStr(template, "{loop}")
//!         loopEnd = InStr(template, "{/loop}")
//!         
//!         If loopStart = 0 Or loopEnd = 0 Then
//!             ProcessLoop = template
//!             Exit Function
//!         End If
//!         
//!         loopTemplate = Mid(template, loopStart + 6, loopEnd - loopStart - 6)
//!         
//!         itemText = ""
//!         For i = LBound(items) To UBound(items)
//!             itemText = itemText & Replace(loopTemplate, "{item}", items(i))
//!         Next i
//!         
//!         result = Left(template, loopStart - 1) & itemText & Mid(template, loopEnd + 7)
//!         
//!         ProcessLoop = result
//!     End Function
//! End Module
//! ```
//!
//! ### Example 3: CSV/TSV Converter
//! ```vb
//! ' Convert between CSV and TSV formats
//! Class DelimiterConverter
//!     Private m_sourceDelimiter As String
//!     Private m_targetDelimiter As String
//!     Private m_textQualifier As String
//!     
//!     Public Sub Initialize(sourceDelim As String, targetDelim As String, _
//!                          Optional textQual As String = """")
//!         m_sourceDelimiter = sourceDelim
//!         m_targetDelimiter = targetDelim
//!         m_textQualifier = textQual
//!     End Sub
//!     
//!     Public Function Convert(data As String) As String
//!         Dim result As String
//!         Dim inQuotes As Boolean
//!         Dim i As Long
//!         Dim ch As String
//!         
//!         result = ""
//!         inQuotes = False
//!         
//!         For i = 1 To Len(data)
//!             ch = Mid(data, i, 1)
//!             
//!             If ch = m_textQualifier Then
//!                 inQuotes = Not inQuotes
//!                 result = result & ch
//!             ElseIf ch = m_sourceDelimiter And Not inQuotes Then
//!                 result = result & m_targetDelimiter
//!             Else
//!                 result = result & ch
//!             End If
//!         Next i
//!         
//!         Convert = result
//!     End Function
//!     
//!     Public Function ConvertSimple(data As String) As String
//!         ' Simple conversion without quote handling
//!         ConvertSimple = Replace(data, m_sourceDelimiter, m_targetDelimiter)
//!     End Function
//!     
//!     Public Function EscapeField(field As String) As String
//!         ' Escape field for CSV/TSV
//!         Dim needsQuotes As Boolean
//!         Dim result As String
//!         
//!         result = field
//!         
//!         ' Check if field needs quoting
//!         needsQuotes = (InStr(field, m_sourceDelimiter) > 0) Or _
//!                      (InStr(field, m_textQualifier) > 0) Or _
//!                      (InStr(field, vbCrLf) > 0)
//!         
//!         If needsQuotes Then
//!             ' Escape existing quotes
//!             result = Replace(result, m_textQualifier, m_textQualifier & m_textQualifier)
//!             result = m_textQualifier & result & m_textQualifier
//!         End If
//!         
//!         EscapeField = result
//!     End Function
//! End Class
//! ```
//!
//! ### Example 4: Smart String Replacer
//! ```vb
//! ' Advanced string replacement with history and undo
//! Class SmartReplacer
//!     Private m_originalText As String
//!     Private m_currentText As String
//!     Private m_history() As String
//!     Private m_historyCount As Integer
//!     
//!     Public Sub Initialize(text As String)
//!         m_originalText = text
//!         m_currentText = text
//!         m_historyCount = 0
//!         ReDim m_history(0 To 99)
//!         AddToHistory text
//!     End Sub
//!     
//!     Public Function ReplaceText(find As String, replaceWith As String, _
//!                                Optional caseSensitive As Boolean = True, _
//!                                Optional maxCount As Long = -1) As String
//!         Dim compareMode As Integer
//!         
//!         If caseSensitive Then
//!             compareMode = vbBinaryCompare
//!         Else
//!             compareMode = vbTextCompare
//!         End If
//!         
//!         m_currentText = Replace(m_currentText, find, replaceWith, 1, maxCount, compareMode)
//!         AddToHistory m_currentText
//!         
//!         ReplaceText = m_currentText
//!     End Function
//!     
//!     Public Function ReplaceFromStart(find As String, replaceWith As String, _
//!                                     startPos As Long) As String
//!         ' Replace starting from a specific position
//!         Dim beforeStart As String
//!         Dim afterStart As String
//!         
//!         If startPos < 1 Then startPos = 1
//!         If startPos > Len(m_currentText) Then
//!             ReplaceFromStart = m_currentText
//!             Exit Function
//!         End If
//!         
//!         beforeStart = Left(m_currentText, startPos - 1)
//!         afterStart = Replace(Mid(m_currentText, startPos), find, replaceWith)
//!         
//!         m_currentText = beforeStart & afterStart
//!         AddToHistory m_currentText
//!         
//!         ReplaceFromStart = m_currentText
//!     End Function
//!     
//!     Public Function GetCurrent() As String
//!         GetCurrent = m_currentText
//!     End Function
//!     
//!     Public Function Undo() As String
//!         If m_historyCount > 1 Then
//!             m_historyCount = m_historyCount - 1
//!             m_currentText = m_history(m_historyCount - 1)
//!         End If
//!         
//!         Undo = m_currentText
//!     End Function
//!     
//!     Public Function Reset() As String
//!         m_currentText = m_originalText
//!         m_historyCount = 0
//!         ReDim m_history(0 To 99)
//!         AddToHistory m_currentText
//!         
//!         Reset = m_currentText
//!     End Function
//!     
//!     Public Function GetReplacementCount(find As String) As Long
//!         Dim withFind As Long
//!         Dim withoutFind As Long
//!         
//!         If Len(find) = 0 Then
//!             GetReplacementCount = 0
//!             Exit Function
//!         End If
//!         
//!         withFind = Len(m_currentText)
//!         withoutFind = Len(Replace(m_currentText, find, ""))
//!         
//!         GetReplacementCount = (withFind - withoutFind) / Len(find)
//!     End Function
//!     
//!     Private Sub AddToHistory(text As String)
//!         If m_historyCount > UBound(m_history) Then
//!             ' Shift history
//!             Dim i As Integer
//!             For i = 0 To UBound(m_history) - 1
//!                 m_history(i) = m_history(i + 1)
//!             Next i
//!             m_history(UBound(m_history)) = text
//!         Else
//!             m_history(m_historyCount) = text
//!             m_historyCount = m_historyCount + 1
//!         End If
//!     End Sub
//! End Class
//! ```
//!
//! ## Error Handling
//!
//! The `Replace` function can raise errors in the following situations:
//!
//! - **Invalid Procedure Call (Error 5)**: When:
//!   - `start` parameter is less than 1
//!   - `count` parameter is less than -1
//! - **Type Mismatch (Error 13)**: When parameters cannot be converted to appropriate types
//! - **Invalid Use of Null (Error 94)**: When `expression` is Null
//!
//! Always validate inputs when necessary:
//!
//! ```vb
//! Function SafeReplace(text As String, find As String, replaceWith As String) As String
//!     On Error Resume Next
//!     SafeReplace = Replace(text, find, replaceWith)
//!     If Err.Number <> 0 Then
//!         SafeReplace = text  ' Return original on error
//!         Err.Clear
//!     End If
//!     On Error GoTo 0
//! End Function
//! ```
//!
//! ## Performance Considerations
//!
//! - The `Replace` function is optimized and very fast for most use cases
//! - Multiple sequential Replace calls can be slow for large strings
//! - Consider building a new string if making many replacements
//! - Using `count` parameter can improve performance by limiting replacements
//! - Binary comparison is faster than textual comparison
//! - Replacing with empty string is efficient for removing substrings
//!
//! ## Best Practices
//!
//! 1. **Use Meaningful Names**: Name variables clearly (find, replaceWith, not f, r)
//! 2. **Check Empty Strings**: Validate find parameter is not empty when expected
//! 3. **Consider Case Sensitivity**: Choose appropriate compare parameter
//! 4. **Limit Replacements**: Use count parameter when you know the limit
//! 5. **Chain Carefully**: Be aware that multiple Replace calls compound
//! 6. **Escape Special Characters**: Properly escape quotes and special chars
//! 7. **Validate Start Position**: Ensure start is within string bounds
//! 8. **Test Edge Cases**: Test with empty strings, no matches, all matches
//! 9. **Document Assumptions**: Comment why specific replacements are made
//! 10. **Use Constants**: Define commonly replaced strings as constants
//!
//! ## Comparison with Related Functions
//!
//! | Function | Purpose | Returns | Use Case |
//! |----------|---------|---------|----------|
//! | **Replace** | Replace substring | String (modified) | Simple string substitution |
//! | **`InStr`** | Find substring position | Long (position) | Locate substring, check existence |
//! | **Mid** | Extract substring | String (portion) | Get part of string |
//! | **Left/Right** | Extract from ends | String (portion) | Get start/end of string |
//! | **Trim/LTrim/RTrim** | Remove whitespace | String (trimmed) | Clean string edges |
//! | **UCase/LCase** | Change case | String (case changed) | Normalize case |
//!
//! ## Platform and Version Notes
//!
//! - Available in VB6 and VBA (Office 2000 and later)
//! - Not available in earlier VBA versions (use custom function)
//! - Behavior consistent across Windows platforms
//! - Case-insensitive comparison uses system locale settings
//! - vbDatabaseCompare only works in Microsoft Access
//!
//! ## Limitations
//!
//! - Cannot use regular expressions (use VBScript.RegExp for patterns)
//! - Cannot replace with different string based on match context
//! - Case-insensitive comparison depends on system locale
//! - No built-in way to replace with function result
//! - Cannot perform multiple different replacements in one call
//! - When start > 1, characters before start are not in result
//!
//! ## Related Functions
//!
//! - `InStr`: Returns position of substring within string
//! - `InStrRev`: Returns position of substring searching from end
//! - `Mid`: Returns specified portion of string
//! - `Left`: Returns specified number of characters from left
//! - `Right`: Returns specified number of characters from right
//! - `LCase`: Converts string to lowercase
//! - `UCase`: Converts string to uppercase

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

    #[test]
    fn replace_basic() {
        let source = r#"
Dim result As String
result = Replace("Hello World", "World", "VB6")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_with_all_parameters() {
        let source = r#"
Dim result As String
result = Replace("one, two, three", ", ", " | ", 1, 2, vbBinaryCompare)
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_if_statement() {
        let source = r#"
If InStr(Replace(text, "old", "new"), "new") > 0 Then
    MsgBox "Replacement successful"
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_function_return() {
        let source = r#"
Function RemoveSpaces(text As String) As String
    RemoveSpaces = Replace(text, " ", "")
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_variable_assignment() {
        let source = r"
Dim cleaned As String
cleaned = Replace(dirtyText, badChar, goodChar)
";
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_msgbox() {
        let source = r#"
MsgBox Replace("Error: {code}", "{code}", "404")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_debug_print() {
        let source = r#"
Debug.Print Replace(filePath, "\", "/")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_select_case() {
        let source = r#"
Dim sanitized As String
sanitized = Replace(input, invalidChar, "_")
Select Case Len(sanitized)
    Case 0
        result = "Empty"
    Case Else
        result = sanitized
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

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

Public Sub CleanText()
    m_text = Replace(m_text, vbCrLf, vbLf)
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_with_statement() {
        let source = r"
With document
    .Content = Replace(.Content, oldText, newText)
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_elseif() {
        let source = r#"
If mode = 1 Then
    result = Replace(text, "A", "B")
ElseIf mode = 2 Then
    result = Replace(text, "A", "C")
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_for_loop() {
        let source = r#"
For i = 0 To 9
    text = Replace(text, CStr(i), "*")
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_do_while() {
        let source = r#"
Do While InStr(text, "  ") > 0
    text = Replace(text, "  ", " ")
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_do_until() {
        let source = r#"
Do Until Replace(data, delimiter, "") = data
    data = Replace(data, delimiter, ",")
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_while_wend() {
        let source = r#"
While Len(Replace(str, target, "")) < Len(str)
    str = Replace(str, target, replacement)
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_parentheses() {
        let source = r#"
Dim result As String
result = (Replace(text, "a", "b"))
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_iif() {
        let source = r"
Dim output As String
output = IIf(caseSensitive, Replace(s, f, r), Replace(s, f, r, 1, -1, vbTextCompare))
";
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_nested() {
        let source = r#"
Dim result As String
result = Replace(Replace(text, "A", "B"), "B", "C")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_array_assignment() {
        let source = r#"
Dim lines(10) As String
lines(i) = Replace(lines(i), vbTab, "    ")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_property_assignment() {
        let source = r#"
Set obj = New TextProcessor
obj.ProcessedText = Replace(obj.RawText, Chr(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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_function_argument() {
        let source = r"
Call ProcessData(Replace(rawData, vbCrLf, vbLf), delimiter)
";
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_concatenation() {
        let source = r#"
Dim msg As String
msg = "Result: " & Replace(input, bad, good)
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_case_insensitive() {
        let source = r#"
Dim result As String
result = Replace("Hello WORLD", "world", "VB6", 1, -1, vbTextCompare)
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_remove_substring() {
        let source = r#"
Dim cleaned As String
cleaned = Replace(text, unwanted, "")
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_trim_combination() {
        let source = r#"
Dim result As String
result = Trim(Replace(input, vbTab, " "))
"#;
        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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_error_handling() {
        let source = r"
On Error Resume Next
result = Replace(source, find, replaceWith)
If Err.Number <> 0 Then
    result = source
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn replace_on_error_goto() {
        let source = r#"
Sub ProcessText()
    On Error GoTo ErrorHandler
    Dim output As String
    output = Replace(input, pattern, substitution)
    Exit Sub
ErrorHandler:
    MsgBox "Error in text replacement"
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/string/replace");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }
}