vb6runtime 0.2.0

VB6 runtime library - value system, type conversions, and standard library implementations
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
//! # `Dir` Function
//!
//! Returns a `String` representing the name of a file, directory, or folder that matches a
//! specified pattern or file attribute, or the volume label of a drive.
//!
//! ## Syntax
//!
//! ```vb
//! Dir[(pathname[, attributes])]
//! ```
//!
//! ## Parameters
//!
//! - **pathname**: Optional. `String` expression that specifies a file name, directory name,
//!   or folder name. May include wildcards (* and ?). If not specified, uses the pattern
//!   from the previous `Dir` call.
//! - **attributes**: Optional. Constant or numeric expression whose sum specifies file
//!   attributes. If omitted, returns files that match pathname but have no attributes.
//!
//! ## Attributes
//!
//! - **vbNormal** (0): Normal files (default)
//! - **vbReadOnly** (1): Read-only files
//! - **vbHidden** (2): Hidden files
//! - **vbSystem** (4): System files
//! - **vbVolume** (8): Volume label (pathname ignored)
//! - **vbDirectory** (16): Directories or folders
//! - **vbArchive** (32): Files that have changed since last backup
//!
//! ## Return Value
//!
//! Returns a `String` containing the name of a file, directory, or folder that matches the
//! specified pattern and attributes. Returns a zero-length string ("") when no more files
//! are found.
//!
//! ## Remarks
//!
//! The `Dir` function is used to retrieve file and directory names that match a pattern.
//! It's commonly used to iterate through files in a directory or to check if a file exists.
//!
//! **Important Characteristics:**
//!
//! - First call with pathname initializes search and returns first match
//! - Subsequent calls without arguments return next matching file
//! - Returns empty string ("") when no more matches found
//! - Case-insensitive pattern matching
//! - Supports wildcards: * (multiple chars) and ? (single char)
//! - Does not return "." and ".." directory entries
//! - Order of returned files is not guaranteed (typically file system order)
//! - Maintains internal state between calls
//! - Multiple Dir loops cannot be nested without complications
//! - Changing directory during Dir enumeration can cause issues
//!
//! ## Wildcards
//!
//! - `*` - Matches zero or more characters
//! - `?` - Matches exactly one character
//! - `*.*` - All files with extensions
//! - `*.txt` - All .txt files
//! - `test?.dat` - Files like test1.dat, testA.dat
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```vb
//! ' Get first .txt file in current directory
//! Dim fileName As String
//! fileName = Dir("*.txt")
//! MsgBox fileName
//!
//! ' Check if specific file exists
//! If Len(Dir("C:\data\report.txt")) > 0 Then
//!     MsgBox "File exists"
//! End If
//!
//! ' Get volume label
//! Dim volumeLabel As String
//! volumeLabel = Dir("C:\", vbVolume)
//! ```
//!
//! ### Iterate Through Files
//!
//! ```vb
//! Sub ListAllTextFiles()
//!     Dim fileName As String
//!     
//!     ' First call with pattern
//!     fileName = Dir("C:\Documents\*.txt")
//!     
//!     ' Loop through all matches
//!     Do While fileName <> ""
//!         Debug.Print fileName
//!         fileName = Dir  ' Subsequent calls without arguments
//!     Loop
//! End Sub
//! ```
//!
//! ### Count Files
//!
//! ```vb
//! Function CountFiles(path As String, pattern As String) As Long
//!     Dim fileName As String
//!     Dim count As Long
//!     
//!     count = 0
//!     fileName = Dir(path & "\" & pattern)
//!     
//!     Do While fileName <> ""
//!         count = count + 1
//!         fileName = Dir
//!     Loop
//!     
//!     CountFiles = count
//! End Function
//! ```
//!
//! ## Common Patterns
//!
//! ### File Existence Check
//!
//! ```vb
//! Function FileExists(filePath As String) As Boolean
//!     FileExists = (Len(Dir(filePath)) > 0)
//! End Function
//!
//! ' Usage
//! If FileExists("C:\data\file.txt") Then
//!     ' File exists
//! End If
//! ```
//!
//! ### Get All Files in Directory
//!
//! ```vb
//! Function GetFileList(folderPath As String, pattern As String) As Variant
//!     Dim files() As String
//!     Dim fileName As String
//!     Dim count As Long
//!     
//!     count = 0
//!     ReDim files(0 To 100)
//!     
//!     fileName = Dir(folderPath & "\" & pattern)
//!     Do While fileName <> ""
//!         files(count) = fileName
//!         count = count + 1
//!         
//!         If count > UBound(files) Then
//!             ReDim Preserve files(0 To UBound(files) + 100)
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//!     
//!     If count > 0 Then
//!         ReDim Preserve files(0 To count - 1)
//!         GetFileList = files
//!     Else
//!         GetFileList = Array()
//!     End If
//! End Function
//! ```
//!
//! ### Find Files by Attribute
//!
//! ```vb
//! Sub ListHiddenFiles(folderPath As String)
//!     Dim fileName As String
//!     
//!     fileName = Dir(folderPath & "\*.*", vbHidden)
//!     Do While fileName <> ""
//!         Debug.Print "Hidden: " & fileName
//!         fileName = Dir
//!     Loop
//! End Sub
//!
//! Sub ListDirectories(folderPath As String)
//!     Dim dirName As String
//!     
//!     dirName = Dir(folderPath & "\*.*", vbDirectory)
//!     Do While dirName <> ""
//!         ' Filter out "." and ".." if they appear
//!         If dirName <> "." And dirName <> ".." Then
//!             ' Check if it's actually a directory
//!             If GetAttr(folderPath & "\" & dirName) And vbDirectory Then
//!                 Debug.Print "Directory: " & dirName
//!             End If
//!         End If
//!         dirName = Dir
//!     Loop
//! End Sub
//! ```
//!
//! ### Search Multiple File Types
//!
//! ```vb
//! Function FindDocuments(folderPath As String) As Variant
//!     Dim files() As String
//!     Dim fileName As String
//!     Dim count As Long
//!     Dim extensions As Variant
//!     Dim i As Integer
//!     
//!     extensions = Array("*.txt", "*.doc", "*.docx", "*.pdf")
//!     ReDim files(0 To 100)
//!     count = 0
//!     
//!     For i = LBound(extensions) To UBound(extensions)
//!         fileName = Dir(folderPath & "\" & extensions(i))
//!         Do While fileName <> ""
//!             files(count) = fileName
//!             count = count + 1
//!             
//!             If count > UBound(files) Then
//!                 ReDim Preserve files(0 To UBound(files) + 100)
//!             End If
//!             
//!             fileName = Dir
//!         Loop
//!     Next i
//!     
//!     If count > 0 Then
//!         ReDim Preserve files(0 To count - 1)
//!         FindDocuments = files
//!     Else
//!         FindDocuments = Array()
//!     End If
//! End Function
//! ```
//!
//! ### Get Full File Paths
//!
//! ```vb
//! Function GetFullPaths(folderPath As String, pattern As String) As Variant
//!     Dim paths() As String
//!     Dim fileName As String
//!     Dim count As Long
//!     
//!     count = 0
//!     ReDim paths(0 To 100)
//!     
//!     fileName = Dir(folderPath & "\" & pattern)
//!     Do While fileName <> ""
//!         paths(count) = folderPath & "\" & fileName
//!         count = count + 1
//!         
//!         If count > UBound(paths) Then
//!             ReDim Preserve paths(0 To UBound(paths) + 100)
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//!     
//!     If count > 0 Then
//!         ReDim Preserve paths(0 To count - 1)
//!         GetFullPaths = paths
//!     Else
//!         GetFullPaths = Array()
//!     End If
//! End Function
//! ```
//!
//! ### Delete All Files Matching Pattern
//!
//! ```vb
//! Sub DeleteMatchingFiles(folderPath As String, pattern As String)
//!     Dim fileName As String
//!     Dim fullPath As String
//!     
//!     fileName = Dir(folderPath & "\" & pattern)
//!     Do While fileName <> ""
//!         fullPath = folderPath & "\" & fileName
//!         
//!         ' Get next file BEFORE deleting (Dir state would be lost)
//!         fileName = Dir
//!         
//!         ' Delete the file
//!         Kill fullPath
//!     Loop
//! End Sub
//! ```
//!
//! ### Find Newest File
//!
//! ```vb
//! Function GetNewestFile(folderPath As String, pattern As String) As String
//!     Dim fileName As String
//!     Dim newestFile As String
//!     Dim newestDate As Date
//!     Dim currentDate As Date
//!     Dim fullPath As String
//!     
//!     newestDate = 0
//!     fileName = Dir(folderPath & "\" & pattern)
//!     
//!     Do While fileName <> ""
//!         fullPath = folderPath & "\" & fileName
//!         currentDate = FileDateTime(fullPath)
//!         
//!         If currentDate > newestDate Then
//!             newestDate = currentDate
//!             newestFile = fileName
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//!     
//!     GetNewestFile = newestFile
//! End Function
//! ```
//!
//! ### Calculate Total Size
//!
//! ```vb
//! Function GetTotalFileSize(folderPath As String, pattern As String) As Double
//!     Dim fileName As String
//!     Dim totalSize As Double
//!     Dim fullPath As String
//!     
//!     totalSize = 0
//!     fileName = Dir(folderPath & "\" & pattern)
//!     
//!     Do While fileName <> ""
//!         fullPath = folderPath & "\" & fileName
//!         totalSize = totalSize + FileLen(fullPath)
//!         fileName = Dir
//!     Loop
//!     
//!     GetTotalFileSize = totalSize
//! End Function
//! ```
//!
//! ### Recursive Directory Search
//!
//! ```vb
//! Sub SearchRecursive(folderPath As String, pattern As String)
//!     Dim fileName As String
//!     Dim dirName As String
//!     Dim fullPath As String
//!     
//!     ' Search files in current directory
//!     fileName = Dir(folderPath & "\" & pattern)
//!     Do While fileName <> ""
//!         Debug.Print folderPath & "\" & fileName
//!         fileName = Dir
//!     Loop
//!     
//!     ' Search subdirectories
//!     dirName = Dir(folderPath & "\*.*", vbDirectory)
//!     Do While dirName <> ""
//!         If dirName <> "." And dirName <> ".." Then
//!             fullPath = folderPath & "\" & dirName
//!             If GetAttr(fullPath) And vbDirectory Then
//!                 SearchRecursive fullPath, pattern
//!             End If
//!         End If
//!         dirName = Dir
//!     Loop
//! End Sub
//! ```
//!
//! ## Advanced Usage
//!
//! ### File Filter with Multiple Criteria
//!
//! ```vb
//! Function FindFilesAdvanced(folderPath As String, _
//!                           minSize As Long, maxSize As Long, _
//!                           afterDate As Date) As Variant
//!     Dim files() As String
//!     Dim fileName As String
//!     Dim fullPath As String
//!     Dim fileSize As Long
//!     Dim fileDate As Date
//!     Dim count As Long
//!     
//!     count = 0
//!     ReDim files(0 To 100)
//!     
//!     fileName = Dir(folderPath & "\*.*")
//!     Do While fileName <> ""
//!         fullPath = folderPath & "\" & fileName
//!         fileSize = FileLen(fullPath)
//!         fileDate = FileDateTime(fullPath)
//!         
//!         If fileSize >= minSize And fileSize <= maxSize And fileDate > afterDate Then
//!             files(count) = fileName
//!             count = count + 1
//!             
//!             If count > UBound(files) Then
//!                 ReDim Preserve files(0 To UBound(files) + 100)
//!             End If
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//!     
//!     If count > 0 Then
//!         ReDim Preserve files(0 To count - 1)
//!         FindFilesAdvanced = files
//!     Else
//!         FindFilesAdvanced = Array()
//!     End If
//! End Function
//! ```
//!
//! ### Safe Dir Loop Helper
//!
//! ```vb
//! ' Helper to avoid nested Dir issues
//! Type FileInfo
//!     Name As String
//!     FullPath As String
//!     Size As Long
//!     Modified As Date
//! End Type
//!
//! Function GetFileInfoList(folderPath As String, pattern As String) As Variant
//!     Dim files() As FileInfo
//!     Dim fileName As String
//!     Dim count As Long
//!     
//!     count = 0
//!     ReDim files(0 To 100)
//!     
//!     fileName = Dir(folderPath & "\" & pattern)
//!     Do While fileName <> ""
//!         files(count).Name = fileName
//!         files(count).FullPath = folderPath & "\" & fileName
//!         files(count).Size = FileLen(files(count).FullPath)
//!         files(count).Modified = FileDateTime(files(count).FullPath)
//!         
//!         count = count + 1
//!         If count > UBound(files) Then
//!             ReDim Preserve files(0 To UBound(files) + 100)
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//!     
//!     If count > 0 Then
//!         ReDim Preserve files(0 To count - 1)
//!         GetFileInfoList = files
//!     Else
//!         GetFileInfoList = Array()
//!     End If
//! End Function
//! ```
//!
//! ### Backup Old Files
//!
//! ```vb
//! Sub BackupOldFiles(sourcePath As String, backupPath As String, daysOld As Integer)
//!     Dim fileName As String
//!     Dim fullPath As String
//!     Dim cutoffDate As Date
//!     
//!     cutoffDate = Date - daysOld
//!     fileName = Dir(sourcePath & "\*.*")
//!     
//!     Do While fileName <> ""
//!         fullPath = sourcePath & "\" & fileName
//!         
//!         If FileDateTime(fullPath) < cutoffDate Then
//!             FileCopy fullPath, backupPath & "\" & fileName
//!         End If
//!         
//!         fileName = Dir
//!     Loop
//! End Sub
//! ```
//!
//! ### Build File Index
//!
//! ```vb
//! Function BuildFileIndex(rootPath As String) As Collection
//!     Dim index As New Collection
//!     Dim fileName As String
//!     
//!     ' Add all files to collection with full path as key
//!     fileName = Dir(rootPath & "\*.*")
//!     Do While fileName <> ""
//!         On Error Resume Next
//!         index.Add fileName, UCase(fileName)
//!         On Error GoTo 0
//!         fileName = Dir
//!     Loop
//!     
//!     Set BuildFileIndex = index
//! End Function
//! ```
//!
//! ### File Synchronization Check
//!
//! ```vb
//! Function CompareDirectories(path1 As String, path2 As String) As String
//!     Dim files1 As Collection
//!     Dim files2 As Collection
//!     Dim fileName As String
//!     Dim report As String
//!     
//!     Set files1 = New Collection
//!     Set files2 = New Collection
//!     
//!     ' Get files from first directory
//!     fileName = Dir(path1 & "\*.*")
//!     Do While fileName <> ""
//!         files1.Add fileName
//!         fileName = Dir
//!     Loop
//!     
//!     ' Get files from second directory
//!     fileName = Dir(path2 & "\*.*")
//!     Do While fileName <> ""
//!         files2.Add fileName
//!         fileName = Dir
//!     Loop
//!     
//!     ' Compare (simplified - full version would check both ways)
//!     report = "Files only in " & path1 & ":" & vbCrLf
//!     ' ... comparison logic ...
//!     
//!     CompareDirectories = report
//! End Function
//! ```
//!
//! ### Generate Directory Listing Report
//!
//! ```vb
//! Sub ExportDirectoryListing(folderPath As String, outputFile As String)
//!     Dim fileName As String
//!     Dim fullPath As String
//!     Dim fileNum As Integer
//!     
//!     fileNum = FreeFile
//!     Open outputFile For Output As #fileNum
//!     
//!     Print #fileNum, "Directory Listing for: " & folderPath
//!     Print #fileNum, "Generated: " & Now
//!     Print #fileNum, String(80, "-")
//!     Print #fileNum, "Filename" & vbTab & "Size" & vbTab & "Modified"
//!     Print #fileNum, String(80, "-")
//!     
//!     fileName = Dir(folderPath & "\*.*")
//!     Do While fileName <> ""
//!         fullPath = folderPath & "\" & fileName
//!         Print #fileNum, fileName & vbTab & _
//!                        FileLen(fullPath) & vbTab & _
//!                        FileDateTime(fullPath)
//!         fileName = Dir
//!     Loop
//!     
//!     Close #fileNum
//! End Sub
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! Function SafeDir(pathname As String, Optional attributes As Integer = 0) As String
//!     On Error Resume Next
//!     SafeDir = Dir(pathname, attributes)
//!     If Err.Number <> 0 Then
//!         SafeDir = ""
//!     End If
//! End Function
//!
//! Function SafeFileExists(filePath As String) As Boolean
//!     On Error Resume Next
//!     SafeFileExists = (Len(Dir(filePath)) > 0)
//!     If Err.Number <> 0 Then
//!         SafeFileExists = False
//!     End If
//! End Function
//! ```
//!
//! ### Common Errors
//!
//! - **Error 52** (Bad file name or number): Invalid pathname or pattern
//! - **Error 76** (Path not found): Directory does not exist
//! - **Error 68** (Device unavailable): Drive not ready or network path unavailable
//!
//! ## Performance Considerations
//!
//! - `Dir` is relatively fast for simple file enumeration
//! - For large directories, consider showing progress
//! - Network paths can be slow; consider timeout handling
//! - Avoid nested `Dir` loops (collect to array first)
//! - `FileSystemObject` may be faster for complex operations
//! - Cache results if scanning same directory repeatedly
//!
//! ## Best Practices
//!
//! ### Always Check for Empty String
//!
//! ```vb
//! ' Good - Check for no more files
//! fileName = Dir("*.txt")
//! Do While fileName <> ""
//!     ' Process file
//!     fileName = Dir
//! Loop
//!
//! ' Avoid - May cause infinite loop
//! fileName = Dir("*.txt")
//! Do While Len(fileName) > 0  ' Less reliable
//!     fileName = Dir
//! Loop
//! ```
//!
//! ### Store Files Before Processing
//!
//! ```vb
//! ' Good - Collect files first
//! Dim files() As String, i As Integer
//! ReDim files(0 To 100)
//! count = 0
//!
//! fileName = Dir("*.txt")
//! Do While fileName <> ""
//!     files(count) = fileName
//!     count = count + 1
//!     fileName = Dir
//! Loop
//!
//! ' Now process without Dir active
//! For i = 0 To count - 1
//!     ProcessFile files(i)
//! Next i
//! ```
//!
//! ### Use Absolute Paths
//!
//! ```vb
//! ' Good - Explicit path
//! fileName = Dir("C:\Data\*.txt")
//!
//! ' Risky - Depends on current directory
//! fileName = Dir("*.txt")
//! ```
//!
//! ### Handle No Matches Gracefully
//!
//! ```vb
//! fileName = Dir("*.xyz")
//! If fileName = "" Then
//!     MsgBox "No matching files found"
//!     Exit Sub
//! End If
//! ```
//!
//! ## Comparison with Other Methods
//!
//! ### `Dir` vs `FileSystemObject`
//!
//! ```vb
//! ' Dir - Built-in, faster for simple cases
//! fileName = Dir("C:\Data\*.txt")
//!
//! ' FileSystemObject - More features, but requires reference
//! Dim fso As New FileSystemObject
//! Dim folder As Folder
//! Set folder = fso.GetFolder("C:\Data")
//! ' ... more complex but more powerful
//! ```
//!
//! ### `Dir` vs `File Dialog`
//!
//! ```vb
//! ' Dir - Programmatic file discovery
//! fileName = Dir("*.txt")
//!
//! ' File Dialog - User selection
//! fileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
//! ```
//!
//! ## Limitations
//!
//! - Cannot nest Dir loops reliably (single internal state)
//! - Does not return files in sorted order
//! - Returns only file names, not full paths
//! - No built-in recursion into subdirectories
//! - Cannot filter by date, size, or other attributes directly
//! - Changing current directory during enumeration causes issues
//! - Limited attribute filtering compared to `FileSystemObject`
//!
//! ## Related Functions
//!
//! - `GetAttr`: Gets file attributes
//! - `SetAttr`: Sets file attributes
//! - `FileLen`: Returns file size
//! - `FileDateTime`: Returns file modification date/time
//! - `CurDir`: Returns current directory
//! - `ChDir`: Changes current directory
//! - `MkDir`: Creates directory
//! - `RmDir`: Removes directory
//! - `Kill`: Deletes file
//! - `FileCopy`: Copies file
//! - `Name`: Renames/moves file

use crate::error::{VBError, VBResult};
use crate::state::file;
use crate::value::VBVariant;
use std::path::Path;

/// Retrieves the name of a file, directory, or folder that matches the specified pattern and attributes.
///
/// # Parameters
///
/// - `pathname`: Optional. `String` expression that specifies a file name, directory name,
///   or folder name. May include wildcards (* and ?). If not specified, uses the pattern
///   from the previous `Dir` call.
/// - `attributes`: Optional. Constant or numeric expression whose sum specifies file
///   attributes. If omitted, returns files that match pathname but have no attributes.
///
/// # Return Value
///
/// Returns a `String` containing the name of a file, directory, or folder that matches the
/// specified pattern and attributes. Returns a zero-length string ("") when no more files
/// are found.
///
/// # Remarks
///
/// The `Dir` function is used to retrieve file and directory names that match a pattern.
/// It's commonly used to iterate through files in a directory or to check if a file exists.
pub fn dir(pathname: Option<&VBVariant>, attributes: Option<&VBVariant>) -> VBResult<VBVariant> {
    // An omitted path acts as `Empty`, and an omitted or unconvertible
    // attribute mask falls back to 0 (no filtering) — the historical
    // adapter behavior, now owned by the body.
    let attributes = attributes
        .and_then(|value| value.as_i32().ok())
        .map(|number| number as i16)
        .unwrap_or(0);
    let empty = VBVariant::Empty;
    let pathname_str = match pathname.unwrap_or(&empty) {
        VBVariant::String(s) => s.as_str().to_string(),
        _ => {
            return Err(VBError::with_description(
                13, // Type mismatch
                "Type mismatch in Dir",
            ));
        }
    };

    let path = Path::new(&pathname_str);

    // Split into the directory to enumerate and the entry-name pattern:
    // `Dir("report.txt")` checks one file in the current directory, while
    // `Dir("C:\data\*.txt")` enumerates `C:\data`. Passing the full path
    // as the enumeration directory would fail `read_dir` on a file.
    let (search_dir, pattern) = match path.file_name() {
        Some(name) => (
            path.parent().unwrap_or_else(|| Path::new(".")),
            name.to_string_lossy().into_owned(),
        ),
        // A path without a file name (e.g. `C:\`) enumerates itself.
        None => (path, pathname_str.clone()),
    };

    // Resolved against the file-state root by the backend layer, so any
    // backend (native, memory, ...) sees the same relative-path semantics.
    let file_list = file::file_dir(search_dir, &pattern, attributes).unwrap_or_else(|_| Vec::new());

    if file_list.is_empty() {
        Ok(VBVariant::String(String::new()))
    } else {
        Ok(VBVariant::String(file_list[0].clone()))
    }
}