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
//! # `FileAttr` Function
//!
//! Returns a `Long` representing the file mode for files opened using the `Open` statement,
//! or the file attribute information for files, directories, or folders.
//!
//! ## Syntax
//!
//! ```vb
//! FileAttr(filenumber, returntype)
//! ```
//!
//! ## Parameters
//!
//! - **filenumber**: Required. An `Integer` containing a valid file number of an open file.
//! - **returntype**: Required. A `Long` indicating the type of information to return.
//!   - **1**: Returns a value indicating the file mode (`Input`, `Output`, `Append`, `Binary`, `Random`)
//!   - **2**: Returns the file handle used by the operating system
//!
//! ## Return Value
//!
//! Returns a `Long` value. The meaning depends on the returntype parameter:
//!
//! ### When returntype = 1 (File Mode):
//! - **1**: `Input` mode
//! - **2**: `Output` mode
//! - **4**: `Random` access mode
//! - **8**: `Append` mode
//! - **32**: `Binary` mode
//!
//! ### When returntype = 2 (File Handle):
//! Returns the operating system file handle (an integer value used by the OS to identify the file).
//!
//! ## Remarks
//!
//! The `FileAttr` function returns information about files that have been opened using
//! the `Open` statement. It provides two types of information: the file access mode
//! or the operating system file handle.
//!
//! **Important Characteristics:**
//!
//! - File must be open before calling `FileAttr`
//! - Error if file number is invalid or file is closed
//! - returntype must be 1 or 2
//! - File mode values are mutually exclusive
//! - File handle is OS-specific (Windows, Unix, etc.)
//! - File handle can be used with API calls
//! - Not applicable to files opened by other applications
//! - Only works with files opened via VB6 Open statement
//!
//! ## File Mode Values (returntype = 1)
//!
//! | Mode | Value | Description |
//! |------|-------|-------------|
//! | Input | 1 | File opened for reading |
//! | Output | 2 | File opened for writing (new file or overwrite) |
//! | Random | 4 | File opened for random access |
//! | Append | 8 | File opened for appending |
//! | Binary | 32 | File opened in binary mode |
//!
//! ## Examples
//!
//! ### Basic Usage - Check File Mode
//!
//! ```vb
//! Sub CheckFileMode()
//!     Dim fileNum As Integer
//!     Dim fileMode As Long
//!     
//!     fileNum = FreeFile
//!     Open "C:\data.txt" For Input As #fileNum
//!     
//!     ' Get file mode
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     Select Case fileMode
//!         Case 1
//!             Debug.Print "File opened for Input"
//!         Case 2
//!             Debug.Print "File opened for Output"
//!         Case 4
//!             Debug.Print "File opened for Random access"
//!         Case 8
//!             Debug.Print "File opened for Append"
//!         Case 32
//!             Debug.Print "File opened for Binary"
//!     End Select
//!     
//!     Close #fileNum
//! End Sub
//! ```
//!
//! ### Get File Handle
//!
//! ```vb
//! Sub GetFileHandle()
//!     Dim fileNum As Integer
//!     Dim fileHandle As Long
//!     
//!     fileNum = FreeFile
//!     Open "C:\temp.dat" For Binary As #fileNum
//!     
//!     ' Get operating system file handle
//!     fileHandle = FileAttr(fileNum, 2)
//!     Debug.Print "OS File Handle: " & fileHandle
//!     
//!     ' File handle can be used with Windows API calls
//!     ' Example: SetFilePointer, ReadFile, WriteFile, etc.
//!     
//!     Close #fileNum
//! End Sub
//! ```
//!
//! ### Verify File Is Open for Writing
//!
//! ```vb
//! Function CanWriteToFile(fileNum As Integer) As Boolean
//!     On Error GoTo ErrorHandler
//!     
//!     Dim fileMode As Long
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     ' Check if file is open for Output, Append, Random, or Binary
//!     CanWriteToFile = (fileMode = 2 Or fileMode = 8 Or fileMode = 4 Or fileMode = 32)
//!     Exit Function
//!     
//! ErrorHandler:
//!     CanWriteToFile = False
//! End Function
//! ```
//!
//! ## Common Patterns
//!
//! ### File Mode Lookup Function
//!
//! ```vb
//! Function GetFileModeDescription(fileNum As Integer) As String
//!     On Error GoTo ErrorHandler
//!     
//!     Dim fileMode As Long
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     Select Case fileMode
//!         Case 1
//!             GetFileModeDescription = "Input"
//!         Case 2
//!             GetFileModeDescription = "Output"
//!         Case 4
//!             GetFileModeDescription = "Random"
//!         Case 8
//!             GetFileModeDescription = "Append"
//!         Case 32
//!             GetFileModeDescription = "Binary"
//!         Case Else
//!             GetFileModeDescription = "Unknown"
//!     End Select
//!     Exit Function
//!     
//! ErrorHandler:
//!     GetFileModeDescription = "Error: " & Err.Description
//! End Function
//! ```
//!
//! ### List All Open Files
//!
//! ```vb
//! Sub ListOpenFiles()
//!     Dim i As Integer
//!     Dim fileMode As Long
//!     Dim modeDesc As String
//!     
//!     Debug.Print "Open Files:"
//!     Debug.Print String(60, "-")
//!     Debug.Print "File#", "Mode", "Handle"
//!     Debug.Print String(60, "-")
//!     
//!     For i = 1 To 255
//!         On Error Resume Next
//!         fileMode = FileAttr(i, 1)
//!         
//!         If Err.Number = 0 Then
//!             ' File is open
//!             modeDesc = GetFileModeDescription(i)
//!             Debug.Print i, modeDesc, FileAttr(i, 2)
//!         End If
//!         
//!         Err.Clear
//!     Next i
//! End Sub
//! ```
//!
//! ### Safe File Operation Wrapper
//!
//! ```vb
//! Function WriteToFile(fileNum As Integer, data As String) As Boolean
//!     On Error GoTo ErrorHandler
//!     
//!     Dim fileMode As Long
//!     
//!     ' Verify file is open
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     ' Check if writable
//!     If fileMode <> 2 And fileMode <> 8 And fileMode <> 4 And fileMode <> 32 Then
//!         MsgBox "File is not open for writing", vbExclamation
//!         WriteToFile = False
//!         Exit Function
//!     End If
//!     
//!     ' Write data based on mode
//!     Select Case fileMode
//!         Case 2, 8  ' Output or Append
//!             Print #fileNum, data
//!         Case 4     ' Random
//!             Put #fileNum, , data
//!         Case 32    ' Binary
//!             Put #fileNum, , data
//!     End Select
//!     
//!     WriteToFile = True
//!     Exit Function
//!     
//! ErrorHandler:
//!     WriteToFile = False
//! End Function
//! ```
//!
//! ### Log File Access Information
//!
//! ```vb
//! Sub LogFileAccess(fileNum As Integer, logPath As String)
//!     Dim logNum As Integer
//!     Dim fileMode As Long
//!     Dim fileHandle As Long
//!     
//!     On Error Resume Next
//!     
//!     fileMode = FileAttr(fileNum, 1)
//!     fileHandle = FileAttr(fileNum, 2)
//!     
//!     If Err.Number = 0 Then
//!         logNum = FreeFile
//!         Open logPath For Append As #logNum
//!         Print #logNum, Format(Now, "yyyy-mm-dd hh:nn:ss") & " | " & _
//!                        "File#" & fileNum & " | " & _
//!                        "Mode: " & GetFileModeDescription(fileNum) & " | " & _
//!                        "Handle: " & fileHandle
//!         Close #logNum
//!     End If
//! End Sub
//! ```
//!
//! ### Check If File Number Is Valid
//!
//! ```vb
//! Function IsFileOpen(fileNum As Integer) As Boolean
//!     On Error Resume Next
//!     Dim fileMode As Long
//!     
//!     fileMode = FileAttr(fileNum, 1)
//!     IsFileOpen = (Err.Number = 0)
//! End Function
//! ```
//!
//! ### Get All File Handles
//!
//! ```vb
//! Function GetOpenFileHandles() As Collection
//!     Dim handles As New Collection
//!     Dim i As Integer
//!     Dim fileHandle As Long
//!     
//!     For i = 1 To 255
//!         On Error Resume Next
//!         fileHandle = FileAttr(i, 2)
//!         
//!         If Err.Number = 0 Then
//!             handles.Add fileHandle, CStr(i)
//!         End If
//!         
//!         Err.Clear
//!     Next i
//!     
//!     Set GetOpenFileHandles = handles
//! End Function
//! ```
//!
//! ### Validate File Before Operation
//!
//! ```vb
//! Function ValidateFileForReading(fileNum As Integer) As Boolean
//!     On Error GoTo ErrorHandler
//!     
//!     Dim fileMode As Long
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     ' Check if file is open for Input, Random, or Binary
//!     ValidateFileForReading = (fileMode = 1 Or fileMode = 4 Or fileMode = 32)
//!     Exit Function
//!     
//! ErrorHandler:
//!     ValidateFileForReading = False
//! End Function
//! ```
//!
//! ### Compare File Modes
//!
//! ```vb
//! Sub CompareFileModes(file1 As Integer, file2 As Integer)
//!     Dim mode1 As Long, mode2 As Long
//!     
//!     On Error Resume Next
//!     mode1 = FileAttr(file1, 1)
//!     mode2 = FileAttr(file2, 1)
//!     
//!     If Err.Number = 0 Then
//!         If mode1 = mode2 Then
//!             Debug.Print "Files have the same mode: " & GetFileModeDescription(file1)
//!         Else
//!             Debug.Print "File1 mode: " & GetFileModeDescription(file1)
//!             Debug.Print "File2 mode: " & GetFileModeDescription(file2)
//!         End If
//!     End If
//! End Sub
//! ```
//!
//! ### Track File Usage Statistics
//!
//! ```vb
//! Type FileStats
//!     FileNumber As Integer
//!     Mode As Long
//!     Handle As Long
//!     OpenTime As Date
//!     OperationCount As Long
//! End Type
//!
//! Private fileStatistics() As FileStats
//! Private statCount As Long
//!
//! Sub RecordFileOpen(fileNum As Integer)
//!     On Error Resume Next
//!     
//!     Dim fileMode As Long
//!     Dim fileHandle As Long
//!     
//!     fileMode = FileAttr(fileNum, 1)
//!     fileHandle = FileAttr(fileNum, 2)
//!     
//!     If Err.Number = 0 Then
//!         ReDim Preserve fileStatistics(0 To statCount)
//!         
//!         With fileStatistics(statCount)
//!             .FileNumber = fileNum
//!             .Mode = fileMode
//!             .Handle = fileHandle
//!             .OpenTime = Now
//!             .OperationCount = 0
//!         End With
//!         
//!         statCount = statCount + 1
//!     End If
//! End Sub
//! ```
//!
//! ### Platform-Specific File Handle Usage
//!
//! ```vb
//! ' Windows API declarations (for demonstration)
//! Private Declare Function GetFileSize Lib "kernel32" _
//!     (ByVal hFile As Long, lpFileSizeHigh As Long) As Long
//!
//! Function GetFileSizeViaHandle(fileNum As Integer) As Long
//!     Dim fileHandle As Long
//!     Dim fileSizeHigh As Long
//!     
//!     On Error GoTo ErrorHandler
//!     
//!     ' Get file handle from VB6 file number
//!     fileHandle = FileAttr(fileNum, 2)
//!     
//!     ' Use Windows API to get file size
//!     GetFileSizeViaHandle = GetFileSize(fileHandle, fileSizeHigh)
//!     Exit Function
//!     
//! ErrorHandler:
//!     GetFileSizeViaHandle = -1
//! End Function
//! ```
//!
//! ## Advanced Usage
//!
//! ### File Access Monitor
//!
//! ```vb
//! Type FileAccessInfo
//!     FileNumber As Integer
//!     Mode As String
//!     Handle As Long
//!     CanRead As Boolean
//!     CanWrite As Boolean
//!     LastChecked As Date
//! End Type
//!
//! Function GetFileAccessInfo(fileNum As Integer) As FileAccessInfo
//!     Dim info As FileAccessInfo
//!     Dim fileMode As Long
//!     
//!     On Error GoTo ErrorHandler
//!     
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     With info
//!         .FileNumber = fileNum
//!         .Handle = FileAttr(fileNum, 2)
//!         .LastChecked = Now
//!         
//!         Select Case fileMode
//!             Case 1  ' Input
//!                 .Mode = "Input"
//!                 .CanRead = True
//!                 .CanWrite = False
//!             Case 2  ' Output
//!                 .Mode = "Output"
//!                 .CanRead = False
//!                 .CanWrite = True
//!             Case 4  ' Random
//!                 .Mode = "Random"
//!                 .CanRead = True
//!                 .CanWrite = True
//!             Case 8  ' Append
//!                 .Mode = "Append"
//!                 .CanRead = False
//!                 .CanWrite = True
//!             Case 32  ' Binary
//!                 .Mode = "Binary"
//!                 .CanRead = True
//!                 .CanWrite = True
//!         End Select
//!     End With
//!     
//!     GetFileAccessInfo = info
//!     Exit Function
//!     
//! ErrorHandler:
//!     info.Mode = "Error"
//!     GetFileAccessInfo = info
//! End Function
//! ```
//!
//! ### Automatic File Mode Detection for Operations
//!
//! ```vb
//! Function ReadFromFile(fileNum As Integer, ByRef data As Variant) As Boolean
//!     On Error GoTo ErrorHandler
//!     
//!     Dim fileMode As Long
//!     fileMode = FileAttr(fileNum, 1)
//!     
//!     ' Read based on detected mode
//!     Select Case fileMode
//!         Case 1  ' Input mode
//!             If Not EOF(fileNum) Then
//!                 Line Input #fileNum, data
//!                 ReadFromFile = True
//!             End If
//!         
//!         Case 4  ' Random mode
//!             Get #fileNum, , data
//!             ReadFromFile = True
//!         
//!         Case 32  ' Binary mode
//!             Get #fileNum, , data
//!             ReadFromFile = True
//!         
//!         Case Else
//!             MsgBox "File not open for reading", vbExclamation
//!             ReadFromFile = False
//!     End Select
//!     
//!     Exit Function
//!     
//! ErrorHandler:
//!     ReadFromFile = False
//! End Function
//! ```
//!
//! ### File Handle Cache
//!
//! ```vb
//! Private Type HandleCacheEntry
//!     FileNumber As Integer
//!     Handle As Long
//!     CachedTime As Date
//! End Type
//!
//! Private handleCache() As HandleCacheEntry
//! Private cacheSize As Long
//!
//! Function GetCachedHandle(fileNum As Integer) As Long
//!     Dim i As Long
//!     Dim currentTime As Date
//!     
//!     currentTime = Now
//!     
//!     ' Check cache first
//!     For i = 0 To cacheSize - 1
//!         If handleCache(i).FileNumber = fileNum Then
//!             ' Verify cache is still valid (within 1 second)
//!             If DateDiff("s", handleCache(i).CachedTime, currentTime) < 1 Then
//!                 GetCachedHandle = handleCache(i).Handle
//!                 Exit Function
//!             End If
//!         End If
//!     Next i
//!     
//!     ' Not in cache or expired, get fresh value
//!     On Error Resume Next
//!     GetCachedHandle = FileAttr(fileNum, 2)
//!     
//!     If Err.Number = 0 Then
//!         ' Add to cache
//!         ReDim Preserve handleCache(0 To cacheSize)
//!         handleCache(cacheSize).FileNumber = fileNum
//!         handleCache(cacheSize).Handle = GetCachedHandle
//!         handleCache(cacheSize).CachedTime = currentTime
//!         cacheSize = cacheSize + 1
//!     End If
//! End Function
//! ```
//!
//! ### Cross-Platform File Handle Wrapper
//!
//! ```vb
//! Function GetPlatformFileInfo(fileNum As Integer) As String
//!     Dim fileHandle As Long
//!     Dim info As String
//!     
//!     On Error Resume Next
//!     
//!     fileHandle = FileAttr(fileNum, 2)
//!     
//!     If Err.Number = 0 Then
//!         info = "File Number: " & fileNum & vbCrLf
//!         info = info & "Mode: " & GetFileModeDescription(fileNum) & vbCrLf
//!         info = info & "OS Handle: " & fileHandle & vbCrLf
//!         
//!         ' Platform-specific information
//!         #If Win32 Then
//!             info = info & "Platform: Windows 32-bit" & vbCrLf
//!         #ElseIf Win64 Then
//!             info = info & "Platform: Windows 64-bit" & vbCrLf
//!         #Else
//!             info = info & "Platform: Unknown" & vbCrLf
//!         #End If
//!     Else
//!         info = "File not open"
//!     End If
//!     
//!     GetPlatformFileInfo = info
//! End Function
//! ```
//!
//! ### File Descriptor Manager
//!
//! ```vb
//! Private Type FileDescriptor
//!     VBFileNumber As Integer
//!     OSHandle As Long
//!     Mode As Long
//!     ModeDescription As String
//!     FilePath As String
//!     OpenedAt As Date
//!     IsOpen As Boolean
//! End Type
//!
//! Private descriptors As Collection
//!
//! Sub InitializeDescriptorManager()
//!     Set descriptors = New Collection
//! End Sub
//!
//! Sub RegisterOpenFile(fileNum As Integer, filePath As String)
//!     Dim desc As FileDescriptor
//!     
//!     On Error Resume Next
//!     
//!     desc.VBFileNumber = fileNum
//!     desc.OSHandle = FileAttr(fileNum, 2)
//!     desc.Mode = FileAttr(fileNum, 1)
//!     desc.ModeDescription = GetFileModeDescription(fileNum)
//!     desc.FilePath = filePath
//!     desc.OpenedAt = Now
//!     desc.IsOpen = (Err.Number = 0)
//!     
//!     If desc.IsOpen Then
//!         descriptors.Add desc, "FD" & fileNum
//!     End If
//! End Sub
//!
//! Function GetDescriptor(fileNum As Integer) As FileDescriptor
//!     On Error Resume Next
//!     GetDescriptor = descriptors("FD" & fileNum)
//! End Function
//! ```
//!
//! ### Comprehensive File State Checker
//!
//! ```vb
//! Function GetCompleteFileState(fileNum As Integer) As String
//!     Dim state As String
//!     Dim fileMode As Long
//!     Dim fileHandle As Long
//!     
//!     On Error Resume Next
//!     
//!     state = "=== File State for #" & fileNum & " ===" & vbCrLf
//!     
//!     fileMode = FileAttr(fileNum, 1)
//!     If Err.Number <> 0 Then
//!         state = state & "File is CLOSED or invalid file number" & vbCrLf
//!         GetCompleteFileState = state
//!         Exit Function
//!     End If
//!     
//!     state = state & "File is OPEN" & vbCrLf
//!     state = state & "Mode: " & GetFileModeDescription(fileNum) & " (" & fileMode & ")" & vbCrLf
//!     
//!     fileHandle = FileAttr(fileNum, 2)
//!     state = state & "OS Handle: " & fileHandle & vbCrLf
//!     
//!     ' Add capabilities
//!     state = state & "Capabilities:" & vbCrLf
//!     Select Case fileMode
//!         Case 1
//!             state = state & "  - Read: Yes" & vbCrLf
//!             state = state & "  - Write: No" & vbCrLf
//!             state = state & "  - EOF applicable: Yes" & vbCrLf
//!         Case 2
//!             state = state & "  - Read: No" & vbCrLf
//!             state = state & "  - Write: Yes" & vbCrLf
//!             state = state & "  - EOF applicable: No" & vbCrLf
//!         Case 4
//!             state = state & "  - Read: Yes" & vbCrLf
//!             state = state & "  - Write: Yes" & vbCrLf
//!             state = state & "  - EOF applicable: Yes" & vbCrLf
//!         Case 8
//!             state = state & "  - Read: No" & vbCrLf
//!             state = state & "  - Write: Yes (append only)" & vbCrLf
//!             state = state & "  - EOF applicable: No" & vbCrLf
//!         Case 32
//!             state = state & "  - Read: Yes" & vbCrLf
//!             state = state & "  - Write: Yes" & vbCrLf
//!             state = state & "  - EOF applicable: Use LOF/Seek" & vbCrLf
//!     End Select
//!     
//!     GetCompleteFileState = state
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! Function SafeFileAttr(fileNum As Integer, returnType As Long) As Variant
//!     On Error GoTo ErrorHandler
//!     
//!     ' Validate returnType
//!     If returnType <> 1 And returnType <> 2 Then
//!         Err.Raise 5, , "Invalid returnType. Must be 1 or 2."
//!     End If
//!     
//!     SafeFileAttr = FileAttr(fileNum, returnType)
//!     Exit Function
//!     
//! ErrorHandler:
//!     Select Case Err.Number
//!         Case 52  ' Bad file name or number
//!             MsgBox "File #" & fileNum & " is not open", vbExclamation
//!             SafeFileAttr = Null
//!         Case 5   ' Invalid procedure call
//!             MsgBox "Invalid returnType parameter", vbExclamation
//!             SafeFileAttr = Null
//!         Case Else
//!             MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical
//!             SafeFileAttr = Null
//!     End Select
//! End Function
//! ```
//!
//! ### Common Errors
//!
//! - **Error 52** (Bad file name or number): File number is invalid or file is closed
//! - **Error 5** (Invalid procedure call): returntype is not 1 or 2
//!
//! ## Performance Considerations
//!
//! - `FileAttr` is very fast (simple state query)
//! - Minimal overhead for checking file state
//! - More efficient than maintaining separate state variables
//! - File handle retrieval (returntype=2) is as fast as mode retrieval
//! - Consider caching results if calling frequently in tight loops
//!
//! ## Best Practices
//!
//! ### Always Validate File Is Open
//!
//! ```vb
//! ' Good - Check before operations
//! On Error Resume Next
//! fileMode = FileAttr(fileNum, 1)
//! If Err.Number <> 0 Then
//!     MsgBox "File is not open"
//!     Exit Sub
//! End If
//! On Error GoTo 0
//!
//! ' Or use IsFileOpen helper
//! If Not IsFileOpen(fileNum) Then
//!     Exit Sub
//! End If
//! ```
//!
//! ### Use Constants for Return Types
//!
//! ```vb
//! ' Good - Define constants for clarity
//! Const FILE_ATTR_MODE = 1
//! Const FILE_ATTR_HANDLE = 2
//!
//! fileMode = FileAttr(fileNum, FILE_ATTR_MODE)
//! fileHandle = FileAttr(fileNum, FILE_ATTR_HANDLE)
//! ```
//!
//! ## Comparison with Other Functions
//!
//! ### `FileAttr` vs `GetAttr`
//!
//! ```vb
//! ' FileAttr - For open files, returns mode or handle
//! fileMode = FileAttr(fileNum, 1)  ' File must be open
//!
//! ' GetAttr - For any file, returns attributes (readonly, hidden, etc.)
//! attrs = GetAttr("C:\file.txt")   ' File can be closed
//! ```
//!
//! ### `FileAttr` vs `LOF`
//!
//! ```vb
//! ' FileAttr - Returns mode or handle
//! fileMode = FileAttr(fileNum, 1)
//!
//! ' LOF - Returns file length in bytes
//! fileSize = LOF(fileNum)
//! ```
//!
//! ## Limitations
//!
//! - Only works with files opened via VB6 Open statement
//! - Cannot get attributes of closed files
//! - returntype must be exactly 1 or 2
//! - File handle is platform-specific
//! - No information about file path or name
//! - Cannot determine if file is at EOF
//! - Does not indicate file position
//!
//! ## Related Functions
//!
//! - `FreeFile`: Returns next available file number
//! - `Open`: Opens a file for reading or writing
//! - `Close`: Closes an open file
//! - `LOF`: Returns length of open file
//! - `Seek`: Returns or sets current position in file
//! - `EOF`: Returns whether end of file reached
//! - `GetAttr`: Returns attributes of any file (readonly, hidden, etc.)

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

    #[test]
    fn fileattr_mode() {
        let source = r"
fileMode = FileAttr(fileNum, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_handle() {
        let source = r"
fileHandle = FileAttr(fileNum, 2)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_literal_file_number() {
        let source = r"
mode = FileAttr(1, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_select_case() {
        let source = r#"
Select Case FileAttr(fileNum, 1)
    Case 1
        Debug.Print "Input"
    Case 2
        Debug.Print "Output"
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_in_if() {
        let source = r#"
If FileAttr(fileNum, 1) = 1 Then
    Debug.Print "Input mode"
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_in_function() {
        let source = r"
Function GetFileMode(fnum As Integer) As Long
    GetFileMode = FileAttr(fnum, 1)
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_debug_print() {
        let source = r"
Debug.Print FileAttr(fileNum, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_comparison() {
        let source = r"
canWrite = (FileAttr(fileNum, 1) = 2)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_or_condition() {
        let source = r"
isWritable = (FileAttr(fileNum, 1) = 2 Or FileAttr(fileNum, 1) = 8)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_error_handling() {
        let source = r#"
On Error Resume Next
mode = FileAttr(fileNum, 1)
If Err.Number <> 0 Then
    MsgBox "File not open"
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_in_loop() {
        let source = r"
For i = 1 To 255
    mode = FileAttr(i, 1)
    If Err.Number = 0 Then
        Debug.Print i, mode
    End If
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_with_concatenation() {
        let source = r#"
msg = "Mode: " & FileAttr(fileNum, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_udt_assignment() {
        let source = r"
info.Mode = FileAttr(fileNum, 1)
info.Handle = FileAttr(fileNum, 2)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_validation() {
        let source = r"
valid = (FileAttr(fileNum, 1) >= 1 And FileAttr(fileNum, 1) <= 32)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_nested_if() {
        let source = r"
If FileAttr(fileNum, 1) = 1 Or FileAttr(fileNum, 1) = 4 Then
    canRead = True
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_collection_add() {
        let source = r"
handles.Add FileAttr(i, 2), CStr(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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_msgbox() {
        let source = r#"
MsgBox "File mode: " & FileAttr(fileNum, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_multiline() {
        let source = r#"
info = "File #" & fileNum & vbCrLf & _
       "Mode: " & FileAttr(fileNum, 1) & vbCrLf & _
       "Handle: " & FileAttr(fileNum, 2)
"#;
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_format() {
        let source = r#"
formatted = Format(FileAttr(fileNum, 1), "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/file/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_file_logging() {
        let source = r#"
Print #logNum, "Mode: " & FileAttr(fileNum, 1) & " | Handle: " & FileAttr(fileNum, 2)
"#;
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_boolean_expression() {
        let source = r"
isOpen = (Err.Number = 0) And (FileAttr(fileNum, 1) > 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/file/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_with_constants() {
        let source = r"
Const FILE_ATTR_MODE = 1
mode = FileAttr(fileNum, FILE_ATTR_MODE)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_array_assignment() {
        let source = r"
modes(i) = FileAttr(i, 1)
handles(i) = FileAttr(i, 2)
";
        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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_in_with_block() {
        let source = r"
With descriptor
    .Mode = FileAttr(fileNum, 1)
    .Handle = FileAttr(fileNum, 2)
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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn fileattr_immediate_window() {
        let source = r"
? FileAttr(1, 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/fileattr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }
}