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
//! # Environ Function
//!
//! Returns the String value associated with an operating system environment variable.
//!
//! ## Syntax
//!
//! ```vb
//! Environ(envstring | number)
//! ```
//!
//! ## Parameters
//!
//! - **envstring**: Optional (if number provided). String expression containing the name of an
//! environment variable.
//! - **number**: Optional (if envstring provided). Numeric expression corresponding to the
//! numeric order of an environment string in the environment-string table. The number argument
//! can be any numeric expression, but is rounded to a whole number before it is evaluated.
//!
//! ## Return Value
//!
//! Returns a String containing the value assigned to envstring or the environment variable at
//! position number. Returns a zero-length string ("") if envstring is not found or if there is
//! no environment string at position number.
//!
//! ## Remarks
//!
//! The `Environ` function retrieves values from the operating system's environment variables.
//! Environment variables are system-level or user-level settings that provide information about
//! the operating system environment.
//!
//! **Important Characteristics:**
//!
//! - Reads environment variables from the operating system
//! - Can access by name (string) or position (number)
//! - Case-insensitive on Windows
//! - Returns empty string if variable not found
//! - Position-based access starts at 1 (not 0)
//! - Number of environment variables varies by system
//! - Environment changes during execution are not reflected
//! - Snapshot taken at application start
//! - Cannot modify environment variables (read-only)
//! - Different users may have different environment variables
//!
//! ## Common Environment Variables
//!
//! **Windows:**
//! - `PATH` - Executable search path
//! - `TEMP` or `TMP` - Temporary files directory
//! - `USERNAME` - Current user name
//! - `USERPROFILE` - User's profile directory
//! - `COMPUTERNAME` - Computer name
//! - `SYSTEMROOT` - Windows system directory
//! - `PROGRAMFILES` - Program Files directory
//! - `HOMEDRIVE` - User's home drive (e.g., C:)
//! - `HOMEPATH` - User's home directory path
//! - `APPDATA` - Application data directory
//! - `WINDIR` - Windows directory
//! - `PROCESSOR_ARCHITECTURE` - CPU architecture
//! - `NUMBER_OF_PROCESSORS` - Number of CPU cores
//! - `OS` - Operating system name
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```vb
//! ' Get environment variable by name
//! Dim userName As String
//! userName = Environ("USERNAME")
//! MsgBox "Current user: " & userName
//!
//! ' Get temp directory
//! Dim tempDir As String
//! tempDir = Environ("TEMP")
//!
//! ' Get by position
//! Dim firstEnvVar As String
//! firstEnvVar = Environ(1)
//! ```
//!
//! ### Check if Variable Exists
//!
//! ```vb
//! Function EnvironVarExists(varName As String) As Boolean
//! EnvironVarExists = (Len(Environ(varName)) > 0)
//! End Function
//!
//! ' Usage
//! If EnvironVarExists("JAVA_HOME") Then
//! MsgBox "Java is configured"
//! Else
//! MsgBox "Java not found"
//! End If
//! ```
//!
//! ### Build File Paths
//!
//! ```vb
//! Function GetTempFilePath(fileName As String) As String
//! Dim tempDir As String
//! tempDir = Environ("TEMP")
//!
//! If Right(tempDir, 1) <> "\" Then
//! tempDir = tempDir & "\"
//! End If
//!
//! GetTempFilePath = tempDir & fileName
//! End Function
//! ```
//!
//! ## Common Patterns
//!
//! ### Get User Directories
//!
//! ```vb
//! Function GetUserProfile() As String
//! GetUserProfile = Environ("USERPROFILE")
//! End Function
//!
//! Function GetAppDataPath() As String
//! GetAppDataPath = Environ("APPDATA")
//! End Function
//!
//! Function GetDesktopPath() As String
//! GetDesktopPath = Environ("USERPROFILE") & "\Desktop"
//! End Function
//!
//! Function GetMyDocuments() As String
//! GetMyDocuments = Environ("USERPROFILE") & "\Documents"
//! End Function
//! ```
//!
//! ### System Information
//!
//! ```vb
//! Function GetComputerName() As String
//! GetComputerName = Environ("COMPUTERNAME")
//! End Function
//!
//! Function GetProcessorCount() As Integer
//! Dim procCount As String
//! procCount = Environ("NUMBER_OF_PROCESSORS")
//!
//! If IsNumeric(procCount) Then
//! GetProcessorCount = CInt(procCount)
//! Else
//! GetProcessorCount = 1
//! End If
//! End Function
//!
//! Function GetSystemArchitecture() As String
//! GetSystemArchitecture = Environ("PROCESSOR_ARCHITECTURE")
//! End Function
//! ```
//!
//! ### List All Environment Variables
//!
//! ```vb
//! Sub ListAllEnvironmentVariables()
//! Dim i As Integer
//! Dim envVar As String
//!
//! i = 1
//! Do
//! envVar = Environ(i)
//! If envVar = "" Then Exit Do
//!
//! Debug.Print i & ": " & envVar
//! i = i + 1
//! Loop
//! End Sub
//! ```
//!
//! ### Parse Environment Variable
//!
//! ```vb
//! Function GetEnvironVarName(envString As String) As String
//! Dim equalPos As Integer
//! equalPos = InStr(envString, "=")
//!
//! If equalPos > 0 Then
//! GetEnvironVarName = Left(envString, equalPos - 1)
//! Else
//! GetEnvironVarName = ""
//! End If
//! End Function
//!
//! Function GetEnvironVarValue(envString As String) As String
//! Dim equalPos As Integer
//! equalPos = InStr(envString, "=")
//!
//! If equalPos > 0 Then
//! GetEnvironVarValue = Mid(envString, equalPos + 1)
//! Else
//! GetEnvironVarValue = ""
//! End If
//! End Function
//! ```
//!
//! ### Safe Path Construction
//!
//! ```vb
//! Function BuildSafePath(envVar As String, subPath As String) As String
//! Dim basePath As String
//! basePath = Environ(envVar)
//!
//! If basePath = "" Then
//! BuildSafePath = ""
//! Exit Function
//! End If
//!
//! ' Ensure path ends with backslash
//! If Right(basePath, 1) <> "\" Then
//! basePath = basePath & "\"
//! End If
//!
//! ' Remove leading backslash from subPath if present
//! If Left(subPath, 1) = "\" Then
//! subPath = Mid(subPath, 2)
//! End If
//!
//! BuildSafePath = basePath & subPath
//! End Function
//! ```
//!
//! ### Configuration File Paths
//!
//! ```vb
//! Function GetConfigFilePath(appName As String, fileName As String) As String
//! Dim appDataPath As String
//! Dim configDir As String
//!
//! appDataPath = Environ("APPDATA")
//! configDir = appDataPath & "\" & appName
//!
//! ' Create directory if it doesn't exist
//! If Dir(configDir, vbDirectory) = "" Then
//! MkDir configDir
//! End If
//!
//! GetConfigFilePath = configDir & "\" & fileName
//! End Function
//! ```
//!
//! ### Search PATH Variable
//!
//! ```vb
//! Function FindInPath(executable As String) As String
//! Dim pathVar As String
//! Dim paths() As String
//! Dim i As Integer
//! Dim testPath As String
//!
//! pathVar = Environ("PATH")
//! paths = Split(pathVar, ";")
//!
//! For i = LBound(paths) To UBound(paths)
//! testPath = paths(i) & "\" & executable
//! If Dir(testPath) <> "" Then
//! FindInPath = testPath
//! Exit Function
//! End If
//! Next i
//!
//! FindInPath = ""
//! End Function
//! ```
//!
//! ### Check Operating System
//!
//! ```vb
//! Function IsWindows() As Boolean
//! Dim osVar As String
//! osVar = UCase(Environ("OS"))
//! IsWindows = (InStr(osVar, "WINDOWS") > 0)
//! End Function
//!
//! Function GetWindowsDirectory() As String
//! GetWindowsDirectory = Environ("WINDIR")
//! End Function
//!
//! Function GetSystemRoot() As String
//! GetSystemRoot = Environ("SYSTEMROOT")
//! End Function
//! ```
//!
//! ### Program Files Paths
//!
//! ```vb
//! Function GetProgramFilesPath() As String
//! GetProgramFilesPath = Environ("PROGRAMFILES")
//! End Function
//!
//! Function GetProgramFilesX86Path() As String
//! GetProgramFilesX86Path = Environ("PROGRAMFILES(X86)")
//! End Function
//!
//! Function FindProgramPath(programName As String) As String
//! Dim progFiles As String
//! Dim testPath As String
//!
//! ' Check Program Files
//! progFiles = Environ("PROGRAMFILES")
//! testPath = progFiles & "\" & programName
//! If Dir(testPath, vbDirectory) <> "" Then
//! FindProgramPath = testPath
//! Exit Function
//! End If
//!
//! ' Check Program Files (x86)
//! progFiles = Environ("PROGRAMFILES(X86)")
//! If progFiles <> "" Then
//! testPath = progFiles & "\" & programName
//! If Dir(testPath, vbDirectory) <> "" Then
//! FindProgramPath = testPath
//! Exit Function
//! End If
//! End If
//!
//! FindProgramPath = ""
//! End Function
//! ```
//!
//! ## Advanced Usage
//!
//! ### Environment Variable Dictionary
//!
//! ```vb
//! Function GetEnvironmentDictionary() As Collection
//! Dim dict As New Collection
//! Dim i As Integer
//! Dim envVar As String
//! Dim varName As String
//! Dim varValue As String
//! Dim equalPos As Integer
//!
//! i = 1
//! Do
//! envVar = Environ(i)
//! If envVar = "" Then Exit Do
//!
//! equalPos = InStr(envVar, "=")
//! If equalPos > 0 Then
//! varName = Left(envVar, equalPos - 1)
//! varValue = Mid(envVar, equalPos + 1)
//!
//! On Error Resume Next
//! dict.Add varValue, UCase(varName)
//! On Error GoTo 0
//! End If
//!
//! i = i + 1
//! Loop
//!
//! Set GetEnvironmentDictionary = dict
//! End Function
//! ```
//!
//! ### Expand Environment Variables in String
//!
//! ```vb
//! Function ExpandEnvironmentString(inputString As String) As String
//! Dim result As String
//! Dim startPos As Integer
//! Dim endPos As Integer
//! Dim varName As String
//! Dim varValue As String
//!
//! result = inputString
//!
//! ' Find %VAR% patterns
//! Do
//! startPos = InStr(result, "%")
//! If startPos = 0 Then Exit Do
//!
//! endPos = InStr(startPos + 1, result, "%")
//! If endPos = 0 Then Exit Do
//!
//! varName = Mid(result, startPos + 1, endPos - startPos - 1)
//! varValue = Environ(varName)
//!
//! result = Left(result, startPos - 1) & varValue & Mid(result, endPos + 1)
//! Loop
//!
//! ExpandEnvironmentString = result
//! End Function
//!
//! ' Usage
//! expandedPath = ExpandEnvironmentString("%TEMP%\myfile.txt")
//! ```
//!
//! ### Create Application Log File
//!
//! ```vb
//! Function CreateLogFile(appName As String) As String
//! Dim logDir As String
//! Dim logFile As String
//! Dim dateStamp As String
//!
//! logDir = Environ("TEMP") & "\Logs"
//!
//! ' Create logs directory
//! If Dir(logDir, vbDirectory) = "" Then
//! MkDir logDir
//! End If
//!
//! dateStamp = Format(Date, "yyyy-mm-dd")
//! logFile = logDir & "\" & appName & "_" & dateStamp & ".log"
//!
//! CreateLogFile = logFile
//! End Function
//! ```
//!
//! ### Check Development Environment
//!
//! ```vb
//! Function IsDevelopmentEnvironment() As Boolean
//! ' Check for common development environment variables
//! IsDevelopmentEnvironment = (Len(Environ("VSCODE_PID")) > 0) Or _
//! (Len(Environ("TERM_PROGRAM")) > 0) Or _
//! (Len(Environ("VSAPPIDDIR")) > 0)
//! End Function
//!
//! Function GetJavaHome() As String
//! GetJavaHome = Environ("JAVA_HOME")
//! End Function
//!
//! Function GetPythonPath() As String
//! GetPythonPath = Environ("PYTHONPATH")
//! End Function
//! ```
//!
//! ### Build Connection String
//!
//! ```vb
//! Function BuildConnectionString() As String
//! Dim server As String
//! Dim database As String
//!
//! server = Environ("DB_SERVER")
//! database = Environ("DB_NAME")
//!
//! If server = "" Then server = "localhost"
//! If database = "" Then database = "default"
//!
//! BuildConnectionString = "Server=" & server & ";Database=" & database
//! End Function
//! ```
//!
//! ### Export Environment to File
//!
//! ```vb
//! Sub ExportEnvironmentToFile(filePath As String)
//! Dim fileNum As Integer
//! Dim i As Integer
//! Dim envVar As String
//!
//! fileNum = FreeFile
//! Open filePath For Output As #fileNum
//!
//! Print #fileNum, "Environment Variables"
//! Print #fileNum, "Generated: " & Now
//! Print #fileNum, String(80, "-")
//!
//! i = 1
//! Do
//! envVar = Environ(i)
//! If envVar = "" Then Exit Do
//!
//! Print #fileNum, envVar
//! i = i + 1
//! Loop
//!
//! Close #fileNum
//! End Sub
//! ```
//!
//! ### Portable Path Builder
//!
//! ```vb
//! Function GetPortableAppPath(relativePath As String) As String
//! Dim basePath As String
//!
//! ' Try to get from environment first
//! basePath = Environ("APP_BASE_PATH")
//!
//! ' Fall back to current directory
//! If basePath = "" Then
//! basePath = App.Path
//! End If
//!
//! If Right(basePath, 1) <> "\" Then
//! basePath = basePath & "\"
//! End If
//!
//! GetPortableAppPath = basePath & relativePath
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! Function SafeEnviron(varName As String, Optional defaultValue As String = "") As String
//! On Error Resume Next
//! SafeEnviron = Environ(varName)
//!
//! If Err.Number <> 0 Or SafeEnviron = "" Then
//! SafeEnviron = defaultValue
//! End If
//! End Function
//!
//! Function GetEnvironWithFallback(preferredVar As String, fallbackVar As String) As String
//! GetEnvironWithFallback = Environ(preferredVar)
//!
//! If GetEnvironWithFallback = "" Then
//! GetEnvironWithFallback = Environ(fallbackVar)
//! End If
//! End Function
//! ```
//!
//! ### Common Errors
//!
//! - **Error 5** (Invalid procedure call): Invalid number argument (< 1)
//! - No error for missing variables (returns empty string)
//!
//! ## Performance Considerations
//!
//! - `Environ` is relatively fast (direct OS call)
//! - Environment snapshot taken at application start
//! - Cache frequently used values to avoid repeated calls
//! - Position-based enumeration stops at first empty string
//! - String comparison is case-insensitive on Windows
//!
//! ## Best Practices
//!
//! ### Always Check for Empty String
//!
//! ```vb
//! ' Good - Check before using
//! tempDir = Environ("TEMP")
//! If tempDir = "" Then
//! tempDir = "C:\Temp" ' Fallback
//! End If
//!
//! ' Avoid - Assuming variable exists
//! tempDir = Environ("TEMP") ' May be empty!
//! ```
//!
//! ### Use Constants for Variable Names
//!
//! ```vb
//! ' Good - Constants for maintainability
//! Const ENV_TEMP = "TEMP"
//! Const ENV_USERNAME = "USERNAME"
//!
//! tempDir = Environ(ENV_TEMP)
//! userName = Environ(ENV_USERNAME)
//! ```
//!
//! ### Provide Defaults
//!
//! ```vb
//! Function GetTempDir() As String
//! GetTempDir = Environ("TEMP")
//! If GetTempDir = "" Then GetTempDir = Environ("TMP")
//! If GetTempDir = "" Then GetTempDir = "C:\Temp"
//! End Function
//! ```
//!
//! ### Case Insensitive on Windows
//!
//! ```vb
//! ' All equivalent on Windows
//! userName = Environ("USERNAME")
//! userName = Environ("username")
//! userName = Environ("UserName")
//! ```
//!
//! ## Comparison with Other Methods
//!
//! ### Environ vs Registry
//!
//! ```vb
//! ' Environ - Quick, read-only access to environment
//! tempDir = Environ("TEMP")
//!
//! ' Registry - More control, can read/write, more complex
//! ' (Requires Windows API or Registry object)
//! ```
//!
//! ### Environ vs Command Line
//!
//! ```vb
//! ' Environ - Environment variables
//! userName = Environ("USERNAME")
//!
//! ' Command - Command line arguments
//! args = Command()
//! ```
//!
//! ## Limitations
//!
//! - Read-only access (cannot modify environment variables)
//! - Snapshot at application start (changes not reflected)
//! - Position-based enumeration order not guaranteed
//! - Cannot create or delete environment variables
//! - Limited to process environment (not system-wide)
//! - No wildcard or pattern matching
//! - Case-sensitive on Unix/Linux (VB6 primarily Windows)
//!
//! ## Related Functions
//!
//! - `Command`: Returns command-line arguments
//! - `CurDir`: Returns current directory
//! - `ChDir`: Changes current directory
//! - `App.Path`: Returns application path
//! - `Shell`: Executes external programs (can set environment)
//! - `GetSetting`: Reads application settings from registry
//! - `SaveSetting`: Writes application settings to registry
use crateVBResult;
use crateVBVariant;
use environ_dollar;
/// Returns the value of an environment variable, exactly as [`environ_dollar`]
/// does, except that a `Null` argument propagates as `Null` instead of raising
/// an error.
///
/// `Environ` is the Variant-returning counterpart of `Environ$`; its runtime
/// semantics are otherwise identical (per the VBAL specification, the two
/// functions differ only in the declared type of the return value).