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
//! # Loc Function
//!
//! Returns a Long specifying the current read/write position within an open file.
//!
//! ## Syntax
//!
//! ```vb
//! Loc(filenumber)
//! ```
//!
//! ## Parameters
//!
//! - `filenumber` (Required): Integer file number used in the Open statement
//!   - Must be a valid file number from a currently open file
//!   - File numbers typically obtained from `FreeFile` function
//!
//! ## Return Value
//!
//! Returns a Long:
//! - For Random mode: Record number of last record read or written
//! - For Sequential mode: Current byte position divided by 128
//! - For Binary mode: Position of last byte read or written
//! - Returns 0 if no read/write operations have occurred yet
//! - Returns value based on last I/O operation
//!
//! ## Remarks
//!
//! The Loc function returns the current position in an open file:
//!
//! - Behavior varies based on file access mode
//! - For Random access: Returns record number (1-based)
//! - For Sequential access: Returns byte position / 128 (approximation)
//! - For Binary access: Returns byte position (0-based)
//! - Does not move the file pointer
//! - Read-only operation (non-destructive)
//! - Useful for tracking progress in file operations
//! - Returns position of last operation, not next operation
//! - For Random files, increments after Get/Put
//! - For Binary files, tracks exact byte position
//! - For Sequential files, provides approximate position
//! - Essential for file I/O progress tracking
//! - Used with Seek to navigate files
//! - Different from Seek function (which also sets position)
//! - LOF function returns file length, Loc returns position
//! - Error 52 if file number not open
//! - Error 68 if device unavailable
//! - Common in loops reading/writing files
//! - Helps detect end-of-file conditions
//! - Used for progress bars during file operations
//!
//! ## Typical Uses
//!
//! 1. **Track Random File Position**
//!    ```vb
//!    currentRecord = Loc(1)
//!    ```
//!
//! 2. **Track Binary File Position**
//!    ```vb
//!    bytesProcessed = Loc(fileNum)
//!    ```
//!
//! 3. **Progress Calculation**
//!    ```vb
//!    percentComplete = (Loc(1) / LOF(1)) * 100
//!    ```
//!
//! 4. **Check if Data Written**
//!    ```vb
//!    If Loc(fileNum) > 0 Then
//!        ' File has been written to
//!    End If
//!    ```
//!
//! 5. **Loop Until End**
//!    ```vb
//!    Do While Loc(1) < LOF(1)
//!        Get #1, , record
//!    Loop
//!    ```
//!
//! 6. **Record Number Display**
//!    ```vb
//!    lblRecordNum.Caption = "Record: " & Loc(1)
//!    ```
//!
//! 7. **Byte Position Check**
//!    ```vb
//!    Debug.Print "Position: " & Loc(fileNum)
//!    ```
//!
//! 8. **Progress Bar Update**
//!    ```vb
//!    ProgressBar1.Value = (Loc(1) / totalRecords) * 100
//!    ```
//!
//! ## Basic Examples
//!
//! ### Example 1: Random File Position
//! ```vb
//! Type CustomerRecord
//!     ID As Long
//!     Name As String * 50
//! End Type
//!
//! Dim customer As CustomerRecord
//! Dim fileNum As Integer
//!
//! fileNum = FreeFile
//! Open "customers.dat" For Random As #fileNum Len = Len(customer)
//!
//! ' Read records
//! Do While Not EOF(fileNum)
//!     Get #fileNum, , customer
//!     Debug.Print "Record: " & Loc(fileNum)
//! Loop
//!
//! Close #fileNum
//! ```
//!
//! ### Example 2: Binary File Progress
//! ```vb
//! Dim fileNum As Integer
//! Dim data As Byte
//! Dim fileSize As Long
//!
//! fileNum = FreeFile
//! Open "data.bin" For Binary As #fileNum
//! fileSize = LOF(fileNum)
//!
//! Do While Loc(fileNum) < fileSize
//!     Get #fileNum, , data
//!     
//!     ' Update progress
//!     If Loc(fileNum) Mod 1024 = 0 Then
//!         Debug.Print "Progress: " & (Loc(fileNum) / fileSize) * 100 & "%"
//!     End If
//! Loop
//!
//! Close #fileNum
//! ```
//!
//! ### Example 3: Sequential File Position
//! ```vb
//! Dim fileNum As Integer
//! Dim line As String
//!
//! fileNum = FreeFile
//! Open "log.txt" For Input As #fileNum
//!
//! Do While Not EOF(fileNum)
//!     Line Input #fileNum, line
//!     
//!     ' Approximate position (bytes / 128)
//!     Debug.Print "Position: " & Loc(fileNum)
//! Loop
//!
//! Close #fileNum
//! ```
//!
//! ### Example 4: Track Write Position
//! ```vb
//! Dim fileNum As Integer
//! Dim i As Integer
//!
//! fileNum = FreeFile
//! Open "output.bin" For Binary As #fileNum
//!
//! For i = 1 To 100
//!     Put #fileNum, , i
//!     Debug.Print "Wrote to position: " & Loc(fileNum)
//! Next i
//!
//! Close #fileNum
//! ```
//!
//! ## Common Patterns
//!
//! ### Pattern 1: `CalculateProgress`
//! ```vb
//! Function CalculateProgress(ByVal fileNum As Integer) As Single
//!     Dim currentPos As Long
//!     Dim totalSize As Long
//!     
//!     currentPos = Loc(fileNum)
//!     totalSize = LOF(fileNum)
//!     
//!     If totalSize > 0 Then
//!         CalculateProgress = (currentPos / totalSize) * 100
//!     Else
//!         CalculateProgress = 0
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 2: `IsFilePositionChanged`
//! ```vb
//! Function IsFilePositionChanged(ByVal fileNum As Integer, _
//!                                 ByVal lastPosition As Long) As Boolean
//!     IsFilePositionChanged = (Loc(fileNum) <> lastPosition)
//! End Function
//! ```
//!
//! ### Pattern 3: `GetCurrentRecord`
//! ```vb
//! Function GetCurrentRecord(ByVal fileNum As Integer) As Long
//!     ' For Random access files
//!     GetCurrentRecord = Loc(fileNum)
//! End Function
//! ```
//!
//! ### Pattern 4: `GetBytesProcessed`
//! ```vb
//! Function GetBytesProcessed(ByVal fileNum As Integer) As Long
//!     ' For Binary access files
//!     GetBytesProcessed = Loc(fileNum)
//! End Function
//! ```
//!
//! ### Pattern 5: `UpdateProgressBar`
//! ```vb
//! Sub UpdateProgressBar(ByVal fileNum As Integer, _
//!                       ByVal progressBar As ProgressBar)
//!     Dim percent As Single
//!     percent = (Loc(fileNum) / LOF(fileNum)) * 100
//!     
//!     If percent <= 100 Then
//!         progressBar.Value = percent
//!     End If
//!     DoEvents
//! End Sub
//! ```
//!
//! ### Pattern 6: `ReadFileWithProgress`
//! ```vb
//! Sub ReadFileWithProgress(ByVal filename As String)
//!     Dim fileNum As Integer
//!     Dim data As Byte
//!     Dim lastPercent As Integer
//!     Dim currentPercent As Integer
//!     
//!     fileNum = FreeFile
//!     Open filename For Binary As #fileNum
//!     
//!     Do While Loc(fileNum) < LOF(fileNum)
//!         Get #fileNum, , data
//!         ProcessByte data
//!         
//!         currentPercent = Int((Loc(fileNum) / LOF(fileNum)) * 100)
//!         If currentPercent <> lastPercent Then
//!             Debug.Print "Progress: " & currentPercent & "%"
//!             lastPercent = currentPercent
//!         End If
//!     Loop
//!     
//!     Close #fileNum
//! End Sub
//! ```
//!
//! ### Pattern 7: `GetRecordPosition`
//! ```vb
//! Function GetRecordPosition(ByVal fileNum As Integer) As String
//!     Dim current As Long
//!     Dim total As Long
//!     
//!     current = Loc(fileNum)
//!     total = LOF(fileNum) / Len(recordVariable)
//!     
//!     GetRecordPosition = current & " of " & total
//! End Function
//! ```
//!
//! ### Pattern 8: `SafeLoc`
//! ```vb
//! Function SafeLoc(ByVal fileNum As Integer) As Long
//!     On Error Resume Next
//!     SafeLoc = Loc(fileNum)
//!     If Err.Number <> 0 Then
//!         SafeLoc = -1
//!         Err.Clear
//!     End If
//! End Function
//! ```
//!
//! ### Pattern 9: `IsAtEndOfFile`
//! ```vb
//! Function IsAtEndOfFile(ByVal fileNum As Integer) As Boolean
//!     ' For Binary mode
//!     IsAtEndOfFile = (Loc(fileNum) >= LOF(fileNum))
//! End Function
//! ```
//!
//! ### Pattern 10: `LogFilePosition`
//! ```vb
//! Sub LogFilePosition(ByVal fileNum As Integer, _
//!                     ByVal operation As String)
//!     Debug.Print operation & " - Position: " & Loc(fileNum) & _
//!                 " of " & LOF(fileNum)
//! End Sub
//! ```
//!
//! ## Advanced Examples
//!
//! ### Example 1: File Reader with Progress
//! ```vb
//! ' Class: BinaryFileReader
//! Private m_fileNum As Integer
//! Private m_filename As String
//! Private m_fileSize As Long
//!
//! Public Sub OpenFile(ByVal filename As String)
//!     m_filename = filename
//!     m_fileNum = FreeFile
//!     Open filename For Binary As #m_fileNum
//!     m_fileSize = LOF(m_fileNum)
//! End Sub
//!
//! Public Function ReadByte() As Byte
//!     If Not IsEOF Then
//!         Get #m_fileNum, , ReadByte
//!     End If
//! End Function
//!
//! Public Property Get Position() As Long
//!     Position = Loc(m_fileNum)
//! End Property
//!
//! Public Property Get Size() As Long
//!     Size = m_fileSize
//! End Property
//!
//! Public Property Get Progress() As Single
//!     If m_fileSize > 0 Then
//!         Progress = (Loc(m_fileNum) / m_fileSize) * 100
//!     Else
//!         Progress = 0
//!     End If
//! End Property
//!
//! Public Property Get IsEOF() As Boolean
//!     IsEOF = (Loc(m_fileNum) >= m_fileSize)
//! End Property
//!
//! Public Sub CloseFile()
//!     If m_fileNum > 0 Then
//!         Close #m_fileNum
//!         m_fileNum = 0
//!     End If
//! End Sub
//!
//! Private Sub Class_Terminate()
//!     CloseFile
//! End Sub
//! ```
//!
//! ### Example 2: Random File Navigator
//! ```vb
//! ' Class: RandomFileNavigator
//! Private m_fileNum As Integer
//! Private m_recordLength As Integer
//! Private m_totalRecords As Long
//!
//! Public Sub OpenFile(ByVal filename As String, _
//!                     ByVal recordLength As Integer)
//!     m_recordLength = recordLength
//!     m_fileNum = FreeFile
//!     Open filename For Random As #m_fileNum Len = recordLength
//!     m_totalRecords = LOF(m_fileNum) / recordLength
//! End Sub
//!
//! Public Property Get CurrentRecord() As Long
//!     CurrentRecord = Loc(m_fileNum)
//! End Property
//!
//! Public Property Get TotalRecords() As Long
//!     TotalRecords = m_totalRecords
//! End Property
//!
//! Public Property Get ProgressPercent() As Single
//!     If m_totalRecords > 0 Then
//!         ProgressPercent = (Loc(m_fileNum) / m_totalRecords) * 100
//!     Else
//!         ProgressPercent = 0
//!     End If
//! End Property
//!
//! Public Function IsFirstRecord() As Boolean
//!     IsFirstRecord = (Loc(m_fileNum) = 1)
//! End Function
//!
//! Public Function IsLastRecord() As Boolean
//!     IsLastRecord = (Loc(m_fileNum) = m_totalRecords)
//! End Function
//!
//! Public Sub CloseFile()
//!     If m_fileNum > 0 Then
//!         Close #m_fileNum
//!         m_fileNum = 0
//!     End If
//! End Sub
//!
//! Private Sub Class_Terminate()
//!     CloseFile
//! End Sub
//! ```
//!
//! ### Example 3: File Copy with Progress
//! ```vb
//! Sub CopyFileWithProgress(ByVal sourceFile As String, _
//!                          ByVal destFile As String, _
//!                          Optional progressBar As ProgressBar = Nothing)
//!     Dim sourceNum As Integer, destNum As Integer
//!     Dim buffer As Byte
//!     Dim totalSize As Long
//!     Dim lastPercent As Integer
//!     Dim currentPercent As Integer
//!     
//!     sourceNum = FreeFile
//!     Open sourceFile For Binary As #sourceNum
//!     totalSize = LOF(sourceNum)
//!     
//!     destNum = FreeFile
//!     Open destFile For Binary As #destNum
//!     
//!     Do While Loc(sourceNum) < totalSize
//!         Get #sourceNum, , buffer
//!         Put #destNum, , buffer
//!         
//!         If Not progressBar Is Nothing Then
//!             currentPercent = Int((Loc(sourceNum) / totalSize) * 100)
//!             If currentPercent <> lastPercent Then
//!                 progressBar.Value = currentPercent
//!                 lastPercent = currentPercent
//!                 DoEvents
//!             End If
//!         End If
//!     Loop
//!     
//!     Close #sourceNum
//!     Close #destNum
//! End Sub
//! ```
//!
//! ### Example 4: File Processing Monitor
//! ```vb
//! ' Form with lblStatus, lblProgress, ProgressBar1
//! Private m_fileNum As Integer
//! Private m_totalSize As Long
//!
//! Private Sub ProcessLargeFile(ByVal filename As String)
//!     Dim data As Byte
//!     Dim startTime As Single
//!     
//!     m_fileNum = FreeFile
//!     Open filename For Binary As #m_fileNum
//!     m_totalSize = LOF(m_fileNum)
//!     
//!     startTime = Timer
//!     Timer1.Enabled = True
//!     
//!     Do While Loc(m_fileNum) < m_totalSize
//!         Get #m_fileNum, , data
//!         ProcessData data
//!     Loop
//!     
//!     Timer1.Enabled = False
//!     Close #m_fileNum
//!     
//!     lblStatus.Caption = "Complete!"
//! End Sub
//!
//! Private Sub Timer1_Timer()
//!     UpdateProgress
//! End Sub
//!
//! Private Sub UpdateProgress()
//!     Dim percent As Single
//!     Dim bytesProcessed As Long
//!     
//!     On Error Resume Next
//!     bytesProcessed = Loc(m_fileNum)
//!     
//!     If m_totalSize > 0 Then
//!         percent = (bytesProcessed / m_totalSize) * 100
//!         ProgressBar1.Value = percent
//!         lblProgress.Caption = Format(percent, "0.0") & "% - " & _
//!                              FormatBytes(bytesProcessed) & " of " & _
//!                              FormatBytes(m_totalSize)
//!     End If
//! End Sub
//!
//! Private Function FormatBytes(ByVal bytes As Long) As String
//!     If bytes < 1024 Then
//!         FormatBytes = bytes & " bytes"
//!     ElseIf bytes < 1048576 Then
//!         FormatBytes = Format(bytes / 1024, "0.0") & " KB"
//!     Else
//!         FormatBytes = Format(bytes / 1048576, "0.0") & " MB"
//!     End If
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! ' Error 52: Bad file name or number
//! On Error Resume Next
//! pos = Loc(999)
//! If Err.Number = 52 Then
//!     MsgBox "File not open!"
//! End If
//!
//! ' Error 68: Device unavailable
//! pos = Loc(fileNum)
//! If Err.Number = 68 Then
//!     MsgBox "Device unavailable!"
//! End If
//!
//! ' Safe position retrieval
//! Function GetSafePosition(ByVal fileNum As Integer) As Long
//!     On Error Resume Next
//!     GetSafePosition = Loc(fileNum)
//!     If Err.Number <> 0 Then
//!         GetSafePosition = -1
//!         Err.Clear
//!     End If
//! End Function
//! ```
//!
//! ## Performance Considerations
//!
//! - **Very Fast**: Loc is a simple file pointer query
//! - **No I/O**: Does not perform actual file operations
//! - **Frequent Calls**: Safe to call in tight loops
//! - **Progress Updates**: Use modulo to update UI less frequently
//! - **`DoEvents`**: Call `DoEvents` when updating UI to maintain responsiveness
//!
//! ## Best Practices
//!
//! 1. **Use with LOF** for calculating percentage complete
//! 2. **Check file is open** before calling Loc
//! 3. **Update progress periodically** not on every byte
//! 4. **Cache in variable** if using multiple times
//! 5. **Use for Binary/Random** files (Sequential returns approximation)
//! 6. **Combine with EOF** for robust loop conditions
//! 7. **Handle errors** for unopened files
//! 8. **Use `DoEvents`** when updating UI in loops
//! 9. **Consider mode** when interpreting return value
//! 10. **Document units** (bytes, records, or approximation)
//!
//! ## Comparison with Related Functions
//!
//! | Function | Purpose | Read/Write | Return Value |
//! |----------|---------|------------|--------------|
//! | **Loc** | Get position | Read-only | Position |
//! | **Seek** (function) | Get position | Read-only | Position + 1 |
//! | **Seek** (statement) | Set position | Write | N/A |
//! | **LOF** | Get file length | Read-only | Total bytes |
//! | **EOF** | Check end | Read-only | Boolean |
//!
//! ## Loc vs Seek Function
//!
//! ```vb
//! ' Loc - returns position of last operation
//! currentPos = Loc(fileNum)
//!
//! ' Seek - returns next read/write position (Loc + 1)
//! nextPos = Seek(fileNum)
//!
//! ' For Binary mode:
//! ' After reading byte at position 100:
//! ' Loc returns 100
//! ' Seek returns 101
//! ```
//!
//! ## Mode-Specific Behavior
//!
//! ```vb
//! ' Random mode - record number
//! Open "data.dat" For Random As #1 Len = 128
//! Get #1, 5, record
//! Debug.Print Loc(1)  ' Returns 5 (record number)
//!
//! ' Binary mode - byte position
//! Open "data.bin" For Binary As #1
//! Get #1, , buffer
//! Debug.Print Loc(1)  ' Returns bytes read
//!
//! ' Sequential mode - approximate (bytes / 128)
//! Open "text.txt" For Input As #1
//! Line Input #1, line
//! Debug.Print Loc(1)  ' Returns approximate position
//! ```
//!
//! ## Platform Notes
//!
//! - Available in all VB6 versions
//! - Part of VBA core library
//! - Returns Long (max 2GB file support)
//! - For files > 2GB, result may overflow
//! - Windows-specific file I/O
//! - Behavior identical across Windows versions
//! - Sequential mode approximation may vary
//! - Random mode most reliable
//! - Binary mode exact for files < 2GB
//!
//! ## Limitations
//!
//! - **2GB Limit**: Long type limits file size to ~2GB
//! - **Sequential Approximation**: Not exact for Input/Output/Append modes
//! - **Division by 128**: Sequential mode uses this approximation
//! - **No String Files**: Works with file numbers only
//! - **Requires Open File**: Error if file not open
//! - **Mode Dependent**: Return value meaning varies by mode
//! - **No Directory**: Only for files, not directories
//! - **Last Operation**: Returns position of last I/O, not current
//!
//! ## Related Functions
//!
//! - `Seek`: Get/set file position (next position, not last)
//! - `LOF`: Get length of file
//! - `EOF`: Check if at end of file
//! - `Open`: Open file for I/O
//! - `Close`: Close file
//! - `Get`: Read from file (updates Loc)
//! - `Put`: Write to file (updates Loc)
//! - `FreeFile`: Get available file number

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

    #[test]
    fn loc_basic() {
        let source = r"
            Dim pos As Long
            pos = Loc(1)
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_file_variable() {
        let source = r"
            currentPos = Loc(fileNum)
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_if_statement() {
        let source = r#"
            If Loc(fileNum) > 0 Then
                MsgBox "Data written"
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_progress_calculation() {
        let source = r"
            percentComplete = (Loc(1) / LOF(1)) * 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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_do_while() {
        let source = r"
            Do While Loc(1) < LOF(1)
                Get #1, , data
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_function_return() {
        let source = r"
            Function GetPosition() As Long
                GetPosition = Loc(fileNum)
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_debug_print() {
        let source = r#"
            Debug.Print "Position: " & Loc(fileNum)
        "#;
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_error_handling() {
        let source = r#"
            On Error Resume Next
            pos = Loc(fileNum)
            If Err.Number <> 0 Then
                MsgBox "Error reading position"
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_comparison() {
        let source = r#"
            If Loc(fileNum) >= LOF(fileNum) Then
                MsgBox "At end of file"
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_label_assignment() {
        let source = r#"
            lblPosition.Caption = "Record: " & Loc(1)
        "#;
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_with_statement() {
        let source = r"
            With fileInfo
                .Position = Loc(fileNum)
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_select_case() {
        let source = r#"
            Select Case Loc(fileNum)
                Case 0
                    MsgBox "No data"
                Case Else
                    MsgBox "Processing"
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_elseif() {
        let source = r#"
            If Loc(fileNum) = 0 Then
                status = "Start"
            ElseIf Loc(fileNum) < 100 Then
                status = "Progress"
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_parentheses() {
        let source = r"
            pos = (Loc(fileNum))
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_iif() {
        let source = r#"
            msg = IIf(Loc(fileNum) > 0, "Data exists", "Empty")
        "#;
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_in_class() {
        let source = r"
            Private Sub Class_Method()
                m_position = Loc(m_fileNum)
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_function_argument() {
        let source = r"
            Call UpdateProgress(Loc(fileNum))
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_property_assignment() {
        let source = r"
            MyObject.Position = Loc(fileNum)
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_array_assignment() {
        let source = r"
            positions(i) = Loc(fileNum)
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_while_wend() {
        let source = r"
            While Loc(fileNum) < totalRecords
                Get #fileNum, , record
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_do_until() {
        let source = r"
            Do Until Loc(fileNum) >= targetPosition
                Get #fileNum, , buffer
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_for_loop() {
        let source = r"
            For i = 1 To Loc(fileNum)
                ProcessRecord 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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_modulo() {
        let source = r"
            If Loc(fileNum) Mod 1024 = 0 Then
                UpdateProgress
            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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_progressbar() {
        let source = r"
            ProgressBar1.Value = (Loc(1) / LOF(1)) * 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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_msgbox() {
        let source = r#"
            MsgBox "Current position: " & Loc(fileNum)
        "#;
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_format() {
        let source = r#"
            lblStatus.Caption = Format(Loc(fileNum), "0,000")
        "#;
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn loc_arithmetic() {
        let source = r"
            bytesRemaining = LOF(fileNum) - Loc(fileNum)
        ";
        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/file/loc");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }
}