kcl-lib 0.2.168

KittyCAD Language implementation and tools
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
//! Functions related to mathematics.

use anyhow::Result;

use crate::CompilationIssue;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::ExecState;
use crate::execution::KclValue;
use crate::execution::annotations;
use crate::execution::types::ArrayLen;
use crate::execution::types::NumericType;
use crate::execution::types::NumericTypeExt;
use crate::execution::types::RuntimeType;
use crate::std::args::Args;
use crate::std::args::TyF64;
use crate::util::MathExt;

/// Compute the remainder after dividing `num` by `div`.
/// If `num` is negative, the result will be too.
pub async fn rem(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let n: TyF64 = args.get_unlabeled_kw_arg("number to divide", &RuntimeType::num_any(), exec_state)?;
    let d: TyF64 = args.get_kw_arg("divisor", &RuntimeType::num_any(), exec_state)?;
    let valid_d = d.n != 0.0;
    if !valid_d {
        exec_state.warn(
            CompilationIssue::err(args.source_range, "Divisor cannot be 0".to_string()),
            annotations::WARN_INVALID_MATH,
        );
    }

    let (n, d, ty) = NumericType::combine_mod(n, d);
    if ty == NumericType::Unknown {
        exec_state.err(CompilationIssue::err(
            args.source_range,
            "Calling `rem` on numbers which have unknown or incompatible units.\n\nYou may need to add information about the type of the argument, for example:\n  using a numeric suffix: `42{ty}`\n  or using type ascription: `foo(): number({ty})`"
        ));
    }
    let remainder = n % d;

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(remainder, ty)))
}

/// Compute the cosine of a number (in radians).
pub async fn cos(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let num: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::angle(), exec_state)?;
    let num = num.to_radians(exec_state, args.source_range);
    Ok(args.make_user_val_from_f64_with_type(TyF64::new(libm::cos(num), exec_state.current_default_units())))
}

/// Compute the sine of a number (in radians).
pub async fn sin(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let num: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::angle(), exec_state)?;
    let num = num.to_radians(exec_state, args.source_range);
    Ok(args.make_user_val_from_f64_with_type(TyF64::new(libm::sin(num), exec_state.current_default_units())))
}

/// Compute the tangent of a number (in radians).
pub async fn tan(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let num: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::angle(), exec_state)?;
    let num = num.to_radians(exec_state, args.source_range);
    Ok(args.make_user_val_from_f64_with_type(TyF64::new(libm::tan(num), exec_state.current_default_units())))
}

/// Compute the square root of a number.
pub async fn sqrt(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;

    if input.n < 0.0 {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            format!(
                "Attempt to take square root (`sqrt`) of a number less than zero ({})",
                input.n
            ),
            vec![args.source_range],
        )));
    }

    let result = input.n.sqrt();

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the absolute value of a number.
pub async fn abs(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let result = input.n.abs();

    Ok(args.make_user_val_from_f64_with_type(input.map_value(result)))
}

/// Round a number to the nearest integer.
pub async fn round(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let result = input.n.round();

    Ok(args.make_user_val_from_f64_with_type(input.map_value(result)))
}

/// Compute the largest integer less than or equal to a number.
pub async fn floor(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let result = input.n.floor();

    Ok(args.make_user_val_from_f64_with_type(input.map_value(result)))
}

/// Compute the smallest integer greater than or equal to a number.
pub async fn ceil(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let result = input.n.ceil();

    Ok(args.make_user_val_from_f64_with_type(input.map_value(result)))
}

/// Compute the minimum of the given arguments.
pub async fn min(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let nums: Vec<TyF64> = args.get_unlabeled_kw_arg(
        "input",
        &RuntimeType::Array(Box::new(RuntimeType::num_any()), ArrayLen::Minimum(1)),
        exec_state,
    )?;
    let (nums, ty) = NumericType::combine_eq_array(&nums);
    if ty == NumericType::Unknown {
        exec_state.warn(CompilationIssue::err(
            args.source_range,
            "Calling `min` on numbers which have unknown or incompatible units.\n\nYou may need to add information about the type of the argument, for example:\n  using a numeric suffix: `42{ty}`\n  or using type ascription: `foo(): number({ty})`",
        ), annotations::WARN_UNKNOWN_UNITS);
    }

    let mut result = f64::MAX;
    for num in nums {
        if num < result {
            result = num;
        }
    }

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, ty)))
}

/// Compute the maximum of the given arguments.
pub async fn max(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let nums: Vec<TyF64> = args.get_unlabeled_kw_arg(
        "input",
        &RuntimeType::Array(Box::new(RuntimeType::num_any()), ArrayLen::Minimum(1)),
        exec_state,
    )?;
    let (nums, ty) = NumericType::combine_eq_array(&nums);
    if ty == NumericType::Unknown {
        exec_state.warn(CompilationIssue::err(
            args.source_range,
            "Calling `max` on numbers which have unknown or incompatible units.\n\nYou may need to add information about the type of the argument, for example:\n  using a numeric suffix: `42{ty}`\n  or using type ascription: `foo(): number({ty})`",
        ), annotations::WARN_UNKNOWN_UNITS);
    }

    let mut result = f64::MIN;
    for num in nums {
        if num > result {
            result = num;
        }
    }

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, ty)))
}

/// Compute the number to a power.
pub async fn pow(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let exp: TyF64 = args.get_kw_arg("exp", &RuntimeType::count(), exec_state)?;
    let exp_is_int = exp.n.fract() == 0.0;
    if input.n < 0.0 && !exp_is_int {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!(
                    "Exponent must be an integer when input is negative, but it was {}",
                    exp.n
                ),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let valid_input = !(input.n == 0.0 && exp.n < 0.0);
    if !valid_input {
        exec_state.warn(
            CompilationIssue::err(args.source_range, "Input cannot be 0 when exp < 0".to_string()),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = libm::pow(input.n, exp.n);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the arccosine of a number (in radians).
pub async fn acos(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::count(), exec_state)?;
    let in_range = (-1.0..=1.0).contains(&input.n);
    if !in_range {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("The argument must be between -1 and 1, but it was {}", input.n),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = libm::acos(input.n);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::radians())))
}

/// Compute the arcsine of a number (in radians).
pub async fn asin(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::count(), exec_state)?;
    let in_range = (-1.0..=1.0).contains(&input.n);
    if !in_range {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("The argument must be between -1 and 1, but it was {}", input.n),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = libm::asin(input.n);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::radians())))
}

/// Compute the arctangent of a number (in radians).
pub async fn atan(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::count(), exec_state)?;
    let result = libm::atan(input.n);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::radians())))
}

/// Compute the four quadrant arctangent of Y and X (in radians).
pub async fn atan2(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let y = args.get_kw_arg("y", &RuntimeType::length(), exec_state)?;
    let x = args.get_kw_arg("x", &RuntimeType::length(), exec_state)?;
    let (y, x, _) = NumericType::combine_eq_coerce(y, x, Some((exec_state, args.source_range)));
    let result = libm::atan2(y, x);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::radians())))
}

/// Compute the logarithm of the number with respect to an arbitrary base.
///
/// The result might not be correctly rounded owing to implementation
/// details; `log2()` can produce more accurate results for base 2,
/// and `log10()` can produce more accurate results for base 10.
pub async fn log(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let base: TyF64 = args.get_kw_arg("base", &RuntimeType::count(), exec_state)?;
    let valid_input = input.n > 0.0;
    if !valid_input {
        exec_state.warn(
            CompilationIssue::err(args.source_range, format!("Input must be > 0, but it was {}", input.n)),
            annotations::WARN_INVALID_MATH,
        );
    }
    let valid_base = base.n > 0.0;
    if !valid_base {
        exec_state.warn(
            CompilationIssue::err(args.source_range, format!("Base must be > 0, but it was {}", base.n)),
            annotations::WARN_INVALID_MATH,
        );
    }
    let base_not_1 = base.n != 1.0;
    if !base_not_1 {
        exec_state.warn(
            CompilationIssue::err(args.source_range, "Base cannot be 1".to_string()),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = input.n.log(base.n);

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the base 2 logarithm of the number.
pub async fn log2(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let valid_input = input.n > 0.0;
    if !valid_input {
        exec_state.warn(
            CompilationIssue::err(args.source_range, format!("Input must be > 0, but it was {}", input.n)),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = input.n.log2();

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the base 10 logarithm of the number.
pub async fn log10(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let valid_input = input.n > 0.0;
    if !valid_input {
        exec_state.warn(
            CompilationIssue::err(args.source_range, format!("Input must be > 0, but it was {}", input.n)),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = input.n.log10();

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the natural logarithm of the number.
pub async fn ln(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let input: TyF64 = args.get_unlabeled_kw_arg("input", &RuntimeType::num_any(), exec_state)?;
    let valid_input = input.n > 0.0;
    if !valid_input {
        exec_state.warn(
            CompilationIssue::err(args.source_range, format!("Input must be > 0, but it was {}", input.n)),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = input.n.ln();

    Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, exec_state.current_default_units())))
}

/// Compute the length of the given leg.
pub async fn leg_length(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let hypotenuse: TyF64 = args.get_kw_arg("hypotenuse", &RuntimeType::length(), exec_state)?;
    let leg: TyF64 = args.get_kw_arg("leg", &RuntimeType::length(), exec_state)?;
    let (hypotenuse, leg, ty) = NumericType::combine_eq_coerce(hypotenuse, leg, Some((exec_state, args.source_range)));
    let result = (hypotenuse.squared() - libm::fmin(hypotenuse.abs(), leg.abs()).squared()).sqrt();
    Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
}

/// Compute the angle of the given leg for x.
pub async fn leg_angle_x(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let hypotenuse: TyF64 = args.get_kw_arg("hypotenuse", &RuntimeType::length(), exec_state)?;
    let leg: TyF64 = args.get_kw_arg("leg", &RuntimeType::length(), exec_state)?;
    let (hypotenuse, leg, _ty) = NumericType::combine_eq_coerce(hypotenuse, leg, Some((exec_state, args.source_range)));
    let valid_hypotenuse = hypotenuse > 0.0;
    if !valid_hypotenuse {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("Hypotenuse must be > 0, but it was {}", hypotenuse),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let ratio = libm::fmin(leg, hypotenuse) / hypotenuse;
    let in_range = (-1.0..=1.0).contains(&ratio);
    if !in_range {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("The argument must be between -1 and 1, but it was {}", ratio),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = libm::acos(ratio).to_degrees();
    Ok(KclValue::from_number_with_type(
        result,
        NumericType::degrees(),
        vec![args.into()],
    ))
}

/// Compute the angle of the given leg for y.
pub async fn leg_angle_y(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let hypotenuse: TyF64 = args.get_kw_arg("hypotenuse", &RuntimeType::length(), exec_state)?;
    let leg: TyF64 = args.get_kw_arg("leg", &RuntimeType::length(), exec_state)?;
    let (hypotenuse, leg, _ty) = NumericType::combine_eq_coerce(hypotenuse, leg, Some((exec_state, args.source_range)));
    let valid_hypotenuse = hypotenuse > 0.0;
    if !valid_hypotenuse {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("Hypotenuse must be > 0, but it was {}", hypotenuse),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let ratio = libm::fmin(leg, hypotenuse) / hypotenuse;
    let in_range = (-1.0..=1.0).contains(&ratio);
    if !in_range {
        exec_state.warn(
            CompilationIssue::err(
                args.source_range,
                format!("The argument must be between -1 and 1, but it was {}", ratio),
            ),
            annotations::WARN_INVALID_MATH,
        );
    }
    let result = libm::asin(ratio).to_degrees();
    Ok(KclValue::from_number_with_type(
        result,
        NumericType::degrees(),
        vec![args.into()],
    ))
}