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
//! # `Atn` Function
//!
//! Returns a `Double` specifying the arctangent of a number.
//!
//! ## Syntax
//!
//! ```vb
//! Atn(number)
//! ```
//!
//! ## Parameters
//!
//! - `number` - Required. A `Double` or any valid numeric expression. The tangent value for which you want the angle.
//!
//! ## Return Value
//!
//! Returns a `Double` representing the arctangent of the number in radians.
//!
//! - The result is in the range -π/2 to π/2 radians (-90° to 90°)
//! - To convert from radians to degrees, multiply by 180/π (approximately 57.2957795130823)
//! - To convert from degrees to radians, multiply by π/180 (approximately 0.0174532925199433)
//!
//! ## Remarks
//!
//! The `Atn` function takes the ratio of two sides of a right triangle (opposite/adjacent) and
//! returns the corresponding angle in radians. This is the inverse of the tangent function.
//!
//! ### Important Notes
//!
//! 1. **Return Type**: Always returns `Double` regardless of input type
//! 2. **Radians**: Result is always in radians, not degrees
//! 3. **Range**: Return value is between -π/2 and π/2 (-1.5708 to 1.5708 radians)
//! 4. **Ratio Input**: The argument represents the tangent (opposite/adjacent) of the angle
//! 5. **Inverse Function**: `Atn` is the inverse of `Tan` (`Atn(Tan(x)) = x` for x in valid range)
//!
//! ### Mathematical Relationship
//!
//! ```vb
//! ' For a right triangle:
//! angle = Atn(opposite / adjacent)
//!
//! ' Converting between functions:
//! Tan(Atn(x)) = x    ' Always true
//! Atn(Tan(x)) = x    ' True when -π/2 < x < π/2
//! ```
//!
//! ### Special Values
//!
//! - `Atn(0)` returns 0 (angle is 0 radians or 0°)
//! - `Atn(1)` returns π/4 (approximately 0.785398, which is 45°)
//! - `Atn(-1)` returns -π/4 (approximately -0.785398, which is -45°)
//! - Large positive values approach π/2 (90°)
//! - Large negative values approach -π/2 (-90°)
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```vb
//! Dim angle As Double
//! angle = Atn(1)              ' Returns π/4 (approx 0.785398) = 45°
//! angle = Atn(0)              ' Returns 0 = 0°
//! angle = Atn(-1)             ' Returns -π/4 (approx -0.785398) = -45°
//! angle = Atn(1.732050808)    ' Returns π/3 (approx 1.047198) = 60°
//! ```
//!
//! ### Converting to Degrees
//!
//! ```vb
//! Function AtnDegrees(tangent As Double) As Double
//!     Const PI As Double = 3.14159265358979
//!     AtnDegrees = Atn(tangent) * 180 / PI
//! End Function
//!
//! ' Usage:
//! angle = AtnDegrees(1)       ' Returns 45 degrees
//! ```
//!
//! ### Calculating Angle from Triangle Sides
//!
//! ```vb
//! Function AngleFromSides(opposite As Double, adjacent As Double) As Double
//!     ' Returns angle in radians
//!     AngleFromSides = Atn(opposite / adjacent)
//! End Function
//!
//! ' For a right triangle with opposite=3, adjacent=4:
//! angle = AngleFromSides(3, 4)    ' Returns angle in radians
//! ```
//!
//! ### Calculating π
//!
//! ```vb
//! Function CalculatePi() As Double
//!     ' Since Atn(1) = π/4, then 4 * Atn(1) = π
//!     CalculatePi = 4 * Atn(1)
//! End Function
//! ```
//!
//! ### Full Circle Angle Calculation (Atn2 Emulation)
//!
//! ```vb
//! Function Atn2(y As Double, x As Double) As Double
//!     ' Emulates atan2 function for full circle (-π to π)
//!     Const PI As Double = 3.14159265358979
//!     
//!     If x > 0 Then
//!         Atn2 = Atn(y / x)
//!     ElseIf x < 0 Then
//!         If y >= 0 Then
//!             Atn2 = Atn(y / x) + PI
//!         Else
//!             Atn2 = Atn(y / x) - PI
//!         End If
//!     ElseIf y > 0 Then
//!         Atn2 = PI / 2
//!     ElseIf y < 0 Then
//!         Atn2 = -PI / 2
//!     Else
//!         Atn2 = 0  ' Undefined, but return 0
//!     End If
//! End Function
//! ```
//!
//! ## Common Patterns
//!
//! ### 1. Slope to Angle Conversion
//!
//! ```vb
//! Dim slope As Double
//! Dim angleRadians As Double
//! Dim angleDegrees As Double
//!
//! slope = 0.5  ' Rise over run
//! angleRadians = Atn(slope)
//! angleDegrees = angleRadians * 180 / (4 * Atn(1))
//! ```
//!
//! ### 2. Direction Calculation
//!
//! ```vb
//! Function GetDirection(deltaX As Double, deltaY As Double) As Double
//!     ' Returns angle in degrees (0-360)
//!     Const PI As Double = 3.14159265358979
//!     Dim angle As Double
//!     
//!     If deltaX = 0 Then
//!         If deltaY > 0 Then
//!             angle = 90
//!         ElseIf deltaY < 0 Then
//!             angle = 270
//!         Else
//!             angle = 0
//!         End If
//!     Else
//!         angle = Atn(deltaY / deltaX) * 180 / PI
//!         If deltaX < 0 Then angle = angle + 180
//!         If angle < 0 Then angle = angle + 360
//!     End If
//!     
//!     GetDirection = angle
//! End Function
//! ```
//!
//! ### 3. Distance and Angle from Origin
//!
//! ```vb
//! Sub GetPolarCoordinates(x As Double, y As Double, _
//!                         distance As Double, angle As Double)
//!     distance = Sqr(x * x + y * y)
//!     
//!     If x = 0 Then
//!         If y > 0 Then
//!             angle = 90
//!         Else
//!             angle = 270
//!         End If
//!     Else
//!         angle = Atn(y / x) * 180 / (4 * Atn(1))
//!         If x < 0 Then angle = angle + 180
//!     End If
//! End Sub
//! ```
//!
//! ### 4. Graphics Rotation
//!
//! ```vb
//! Function RotatePoint(x As Double, y As Double, _
//!                     centerX As Double, centerY As Double, _
//!                     angleDegrees As Double)
//!     Const PI As Double = 3.14159265358979
//!     Dim angleRadians As Double
//!     Dim currentAngle As Double
//!     Dim distance As Double
//!     Dim newAngle As Double
//!     
//!     ' Get current angle and distance from center
//!     distance = Sqr((x - centerX) ^ 2 + (y - centerY) ^ 2)
//!     currentAngle = Atn((y - centerY) / (x - centerX))
//!     
//!     ' Calculate new angle
//!     angleRadians = angleDegrees * PI / 180
//!     newAngle = currentAngle + angleRadians
//!     
//!     ' Calculate new position
//!     x = centerX + distance * Cos(newAngle)
//!     y = centerY + distance * Sin(newAngle)
//! End Function
//! ```
//!
//! ### 5. Navigation Bearing
//!
//! ```vb
//! Function CalculateBearing(lat1 As Double, lon1 As Double, _
//!                          lat2 As Double, lon2 As Double) As Double
//!     Const PI As Double = 3.14159265358979
//!     Dim dLon As Double
//!     Dim y As Double
//!     Dim x As Double
//!     Dim bearing As Double
//!     
//!     dLon = lon2 - lon1
//!     y = Sin(dLon) * Cos(lat2)
//!     x = Cos(lat1) * Sin(lat2) - Sin(lat1) * Cos(lat2) * Cos(dLon)
//!     bearing = Atn(y / x) * 180 / PI
//!     
//!     ' Normalize to 0-360
//!     CalculateBearing = (bearing + 360) Mod 360
//! End Function
//! ```
//!
//! ### 6. Inverse Trigonometry Relationships
//!
//! ```vb
//! ' Calculate arcsine using Atn
//! Function Asin(x As Double) As Double
//!     Asin = Atn(x / Sqr(1 - x * x))
//! End Function
//!
//! ' Calculate arccosine using Atn
//! Function Acos(x As Double) As Double
//!     Const PI As Double = 3.14159265358979
//!     Acos = PI / 2 - Atn(x / Sqr(1 - x * x))
//! End Function
//! ```
//!
//! ### 7. Tangent Line Slope
//!
//! ```vb
//! Function GetTangentAngle(x1 As Double, y1 As Double, _
//!                         x2 As Double, y2 As Double) As Double
//!     Dim slope As Double
//!     Const PI As Double = 3.14159265358979
//!     
//!     If x2 = x1 Then
//!         GetTangentAngle = 90  ' Vertical line
//!     Else
//!         slope = (y2 - y1) / (x2 - x1)
//!         GetTangentAngle = Atn(slope) * 180 / PI
//!     End If
//! End Function
//! ```
//!
//! ### 8. Game Development - Projectile Angle
//!
//! ```vb
//! Function AimAngle(shooterX As Double, shooterY As Double, _
//!                   targetX As Double, targetY As Double) As Double
//!     Const PI As Double = 3.14159265358979
//!     Dim deltaX As Double
//!     Dim deltaY As Double
//!     
//!     deltaX = targetX - shooterX
//!     deltaY = targetY - shooterY
//!     
//!     If deltaX = 0 Then
//!         If deltaY > 0 Then
//!             AimAngle = 90
//!         Else
//!             AimAngle = 270
//!         End If
//!     Else
//!         AimAngle = Atn(deltaY / deltaX) * 180 / PI
//!         If deltaX < 0 Then AimAngle = AimAngle + 180
//!         If AimAngle < 0 Then AimAngle = AimAngle + 360
//!     End If
//! End Function
//! ```
//!
//! ## Common Trigonometric Values
//!
//! | Angle (Degrees) | Angle (Radians) | Tangent | Atn(Tangent) |
//! |-----------------|-----------------|---------|--------------|
//! | 0°              | 0               | 0       | 0            |
//! | 30°             | π/6 ≈ 0.524     | 0.577   | π/6          |
//! | 45°             | π/4 ≈ 0.785     | 1       | π/4          |
//! | 60°             | π/3 ≈ 1.047     | 1.732   | π/3          |
//! | 90°             | π/2 ≈ 1.571     | ∞       | π/2 (limit)  |
//!
//! ## Type Conversion
//!
//! | Input Type | Converted To | Example |
//! |------------|--------------|---------|
//! | `Integer`  | `Double`     | Atn(1) → Atn(1.0) |
//! | `Long`     | `Double`     | Atn(10&) → Atn(10.0) |
//! | `Single`   | `Double`     | Atn(1.5!) → Atn(1.5) |
//! | `Double`   | `Double`     | Atn(1.5#) → 1.5 |
//! | `Currency` | `Double`     | Atn(100@) → Atn(100.0) |
//! | `Variant`  | `Double`     | Depends on content |
//!
//! ## Error Conditions
//!
//! - **Type Mismatch**: If the argument cannot be converted to a numeric value
//! - **No overflow**: Unlike some functions, `Atn` cannot overflow as it's bounded to ±π/2
//!
//! ## Related Functions
//!
//! - `Tan`: Returns the tangent of an angle (inverse of `Atn`)
//! - `Sin`: Returns the sine of an angle
//! - `Cos`: Returns the cosine of an angle
//! - `Sqr`: Returns the square root (used with `Atn` to calculate other inverse trig functions)
//! - `Abs`: Returns absolute value (useful in angle calculations)
//!
//! ## Performance Notes
//!
//! - `Atn` is a fast intrinsic function
//! - Implemented using CPU floating-point instructions
//! - No significant performance difference between `Integer`, `Long`, or `Double` arguments
//! - For repeated π calculations, cache the value of 4 * `Atn`(1) rather than recalculating

use crate::{
    error::VBResult,
    value::{VBDouble, VBVariant},
};

/// Implementation of the arctangent (Atn) function.
///
/// VB6 behavior:
/// - `Atn(Null)` returns `Null`
/// - other values are coerced with numeric conversion rules and return `Double`
pub fn atn(value: &VBDouble) -> VBResult<VBVariant> {
    let numeric = value.as_f64();
    Ok(VBVariant::from_double(numeric.atan()))
}

#[cfg(test)]
mod tests {
    use super::atn;
    use crate::{
        error::err_number,
        value::{VBDouble, VBVariant},
    };

    fn assert_approx_eq(actual: f64, expected: f64) {
        if (actual == f64::INFINITY && expected == f64::INFINITY)
            || (actual == f64::NEG_INFINITY && expected == f64::NEG_INFINITY)
        {
            return;
        }

        let diff = (actual - expected).abs();
        assert!(
            diff < 1e-12,
            "expected {expected}, got {actual}, diff {diff}"
        );
    }

    #[test]
    fn computes_expected_doubles() {
        let result = atn(&VBDouble::from(5.0)).unwrap();
        assert_eq!(result, VBVariant::from_double((5.0_f64).atan()));

        let result = atn(&VBDouble::from(-12.5)).unwrap();
        assert_eq!(result, VBVariant::from_double((-12.5_f64).atan()));
    }

    #[test]
    fn returns_expected_special_angles() {
        let VBVariant::Double(v) = atn(&VBDouble::from(0.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, 0.0);

        let VBVariant::Double(v) = atn(&VBDouble::from(1.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, std::f64::consts::FRAC_PI_4);

        let VBVariant::Double(v) = atn(&VBDouble::from(-1.0)).unwrap() else {
            panic!("expected Double")
        };
        assert_approx_eq(v, -std::f64::consts::FRAC_PI_4);
    }

    #[test]
    fn conversion_rejects_non_numeric_values() {
        let err = VBDouble::try_from(&VBVariant::from_string("not-a-number")).unwrap_err();
        assert_eq!(err.number, err_number::TYPE_MISMATCH);
    }

    #[test]
    fn conversion_accepts_numeric_strings() {
        assert_eq!(
            VBDouble::try_from(&VBVariant::from_string("1.5")).unwrap(),
            VBDouble::from(1.5)
        );
    }
}