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
//! Functions implemented for language execution.

pub mod extrude;
pub mod segment;
pub mod sketch;
pub mod utils;

// TODO: Something that would be nice is if we could generate docs for Kcl based on the
// actual stdlib functions below.

use std::collections::HashMap;

use anyhow::Result;
use derive_docs::stdlib;
use parse_display::{Display, FromStr};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{
    abstract_syntax_tree_types::parse_json_number_as_f64,
    engine::EngineConnection,
    errors::{KclError, KclErrorDetails},
    executor::{ExtrudeGroup, MemoryItem, Metadata, SketchGroup, SourceRange},
};

pub type StdFn = fn(&mut Args) -> Result<MemoryItem, KclError>;
pub type FnMap = HashMap<String, StdFn>;

pub struct StdLib {
    pub fns: HashMap<String, Box<(dyn crate::docs::StdLibFn)>>,
}

impl StdLib {
    pub fn new() -> Self {
        let internal_fns: Vec<Box<(dyn crate::docs::StdLibFn)>> = vec![
            Box::new(Show),
            Box::new(Min),
            Box::new(LegLen),
            Box::new(LegAngX),
            Box::new(LegAngY),
            Box::new(crate::std::extrude::Extrude),
            Box::new(crate::std::extrude::GetExtrudeWallTransform),
            Box::new(crate::std::segment::SegEndX),
            Box::new(crate::std::segment::SegEndY),
            Box::new(crate::std::segment::LastSegX),
            Box::new(crate::std::segment::LastSegY),
            Box::new(crate::std::segment::SegLen),
            Box::new(crate::std::segment::SegAng),
            Box::new(crate::std::segment::AngleToMatchLengthX),
            Box::new(crate::std::segment::AngleToMatchLengthY),
            Box::new(crate::std::sketch::LineTo),
            Box::new(crate::std::sketch::Line),
            Box::new(crate::std::sketch::XLineTo),
            Box::new(crate::std::sketch::XLine),
            Box::new(crate::std::sketch::YLineTo),
            Box::new(crate::std::sketch::YLine),
            Box::new(crate::std::sketch::AngledLineToX),
            Box::new(crate::std::sketch::AngledLineToY),
            Box::new(crate::std::sketch::AngledLine),
            Box::new(crate::std::sketch::AngledLineOfXLength),
            Box::new(crate::std::sketch::AngledLineOfYLength),
            Box::new(crate::std::sketch::AngledLineThatIntersects),
            Box::new(crate::std::sketch::StartSketchAt),
            Box::new(crate::std::sketch::Close),
            Box::new(crate::std::sketch::Arc),
            Box::new(crate::std::sketch::BezierCurve),
        ];

        let mut fns = HashMap::new();
        for internal_fn in &internal_fns {
            fns.insert(internal_fn.name().to_string(), internal_fn.clone());
        }

        Self { fns }
    }

    pub fn get(&self, name: &str) -> Option<Box<dyn crate::docs::StdLibFn>> {
        self.fns.get(name).cloned()
    }
}

impl Default for StdLib {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug)]
pub struct Args<'a> {
    pub args: Vec<MemoryItem>,
    pub source_range: SourceRange,
    engine: &'a mut EngineConnection,
}

impl<'a> Args<'a> {
    pub fn new(args: Vec<MemoryItem>, source_range: SourceRange, engine: &'a mut EngineConnection) -> Self {
        Self {
            args,
            source_range,
            engine,
        }
    }

    pub fn send_modeling_cmd(&mut self, id: uuid::Uuid, cmd: kittycad::types::ModelingCmd) -> Result<(), KclError> {
        self.engine.send_modeling_cmd(id, self.source_range, cmd)
    }

    fn make_user_val_from_json(&self, j: serde_json::Value) -> Result<MemoryItem, KclError> {
        Ok(MemoryItem::UserVal {
            value: j,
            meta: vec![Metadata {
                source_range: self.source_range,
            }],
        })
    }

    fn make_user_val_from_f64(&self, f: f64) -> Result<MemoryItem, KclError> {
        self.make_user_val_from_json(serde_json::Value::Number(serde_json::Number::from_f64(f).ok_or_else(
            || {
                KclError::Type(KclErrorDetails {
                    message: format!("Failed to convert `{}` to a number", f),
                    source_ranges: vec![self.source_range],
                })
            },
        )?))
    }

    fn get_number_array(&self) -> Result<Vec<f64>, KclError> {
        let mut numbers: Vec<f64> = Vec::new();
        for arg in &self.args {
            let parsed = arg.get_json_value()?;
            numbers.push(parse_json_number_as_f64(&parsed, self.source_range)?);
        }
        Ok(numbers)
    }

    fn get_hypotenuse_leg(&self) -> Result<(f64, f64), KclError> {
        let numbers = self.get_number_array()?;

        if numbers.len() != 2 {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a number array of length 2, found `{:?}`", numbers),
                source_ranges: vec![self.source_range],
            }));
        }

        Ok((numbers[0], numbers[1]))
    }

    fn get_segment_name_sketch_group(&self) -> Result<(String, SketchGroup), KclError> {
        // Iterate over our args, the first argument should be a UserVal with a string value.
        // The second argument should be a SketchGroup.
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let segment_name = if let serde_json::Value::String(s) = first_value {
            s.to_string()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        let second_value = self.args.get(1).ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            })
        })?;

        let sketch_group = if let MemoryItem::SketchGroup(sg) = second_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok((segment_name, sketch_group))
    }

    fn get_sketch_group(&self) -> Result<SketchGroup, KclError> {
        let first_value = self.args.first().ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the first argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            })
        })?;

        let sketch_group = if let MemoryItem::SketchGroup(sg) = first_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the first argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok(sketch_group)
    }

    fn get_data<T: serde::de::DeserializeOwned>(&self) -> Result<T, KclError> {
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a struct as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let data: T = serde_json::from_value(first_value).map_err(|e| {
            KclError::Type(KclErrorDetails {
                message: format!("Failed to deserialize struct from JSON: {}", e),
                source_ranges: vec![self.source_range],
            })
        })?;

        Ok(data)
    }

    fn get_data_and_sketch_group<T: serde::de::DeserializeOwned>(&self) -> Result<(T, SketchGroup), KclError> {
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a struct as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let data: T = serde_json::from_value(first_value).map_err(|e| {
            KclError::Type(KclErrorDetails {
                message: format!("Failed to deserialize struct from JSON: {}", e),
                source_ranges: vec![self.source_range],
            })
        })?;

        let second_value = self.args.get(1).ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            })
        })?;

        let sketch_group = if let MemoryItem::SketchGroup(sg) = second_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok((data, sketch_group))
    }

    fn get_segment_name_to_number_sketch_group(&self) -> Result<(String, f64, SketchGroup), KclError> {
        // Iterate over our args, the first argument should be a UserVal with a string value.
        // The second argument should be a number.
        // The third argument should be a SketchGroup.
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let segment_name = if let serde_json::Value::String(s) = first_value {
            s.to_string()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        let second_value = self
            .args
            .get(1)
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a number as the second argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let to_number = parse_json_number_as_f64(&second_value, self.source_range)?;

        let third_value = self.args.get(2).ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the third argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            })
        })?;

        let sketch_group = if let MemoryItem::SketchGroup(sg) = third_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the third argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok((segment_name, to_number, sketch_group))
    }

    fn get_number_sketch_group(&self) -> Result<(f64, SketchGroup), KclError> {
        // Iterate over our args, the first argument should be a number.
        // The second argument should be a SketchGroup.
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a number as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let number = parse_json_number_as_f64(&first_value, self.source_range)?;

        let second_value = self.args.get(1).ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            })
        })?;

        let sketch_group = if let MemoryItem::SketchGroup(sg) = second_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok((number, sketch_group))
    }

    fn get_path_name_extrude_group(&self) -> Result<(String, ExtrudeGroup), KclError> {
        // Iterate over our args, the first argument should be a UserVal with a string value.
        // The second argument should be a ExtrudeGroup.
        let first_value = self
            .args
            .first()
            .ok_or_else(|| {
                KclError::Type(KclErrorDetails {
                    message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                    source_ranges: vec![self.source_range],
                })
            })?
            .get_json_value()?;

        let path_name = if let serde_json::Value::String(s) = first_value {
            s.to_string()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!("Expected a string as the first argument, found `{:?}`", self.args),
                source_ranges: vec![self.source_range],
            }));
        };

        let second_value = self.args.get(1).ok_or_else(|| {
            KclError::Type(KclErrorDetails {
                message: format!(
                    "Expected a ExtrudeGroup as the second argument, found `{:?}`",
                    self.args
                ),
                source_ranges: vec![self.source_range],
            })
        })?;

        let extrude_group = if let MemoryItem::ExtrudeGroup(sg) = second_value {
            sg.clone()
        } else {
            return Err(KclError::Type(KclErrorDetails {
                message: format!(
                    "Expected a ExtrudeGroup as the second argument, found `{:?}`",
                    self.args
                ),
                source_ranges: vec![self.source_range],
            }));
        };

        Ok((path_name, extrude_group))
    }
}

/// Returns the minimum of the given arguments.
pub fn min(args: &mut Args) -> Result<MemoryItem, KclError> {
    let nums = args.get_number_array()?;
    let result = inner_min(nums);

    args.make_user_val_from_f64(result)
}

/// Returns the minimum of the given arguments.
#[stdlib {
    name = "min",
}]
fn inner_min(args: Vec<f64>) -> f64 {
    let mut min = std::f64::MAX;
    for arg in args.iter() {
        if *arg < min {
            min = *arg;
        }
    }

    min
}

/// Render a model.
// This never actually gets called so this is fine.
pub fn show(args: &mut Args) -> Result<MemoryItem, KclError> {
    let sketch_group = args.get_sketch_group()?;
    inner_show(sketch_group);

    args.make_user_val_from_f64(0.0)
}

/// Render a model.
#[stdlib {
    name = "show",
}]
fn inner_show(_sketch: SketchGroup) {}

/// Returns the length of the given leg.
pub fn leg_length(args: &mut Args) -> Result<MemoryItem, KclError> {
    let (hypotenuse, leg) = args.get_hypotenuse_leg()?;
    let result = inner_leg_length(hypotenuse, leg);
    args.make_user_val_from_f64(result)
}

/// Returns the length of the given leg.
#[stdlib {
    name = "legLen",
}]
fn inner_leg_length(hypotenuse: f64, leg: f64) -> f64 {
    (hypotenuse.powi(2) - f64::min(hypotenuse.abs(), leg.abs()).powi(2)).sqrt()
}

/// Returns the angle of the given leg for x.
pub fn leg_angle_x(args: &mut Args) -> Result<MemoryItem, KclError> {
    let (hypotenuse, leg) = args.get_hypotenuse_leg()?;
    let result = inner_leg_angle_x(hypotenuse, leg);
    args.make_user_val_from_f64(result)
}

/// Returns the angle of the given leg for x.
#[stdlib {
    name = "legAngX",
}]
fn inner_leg_angle_x(hypotenuse: f64, leg: f64) -> f64 {
    (leg.min(hypotenuse) / hypotenuse).acos() * 180.0 / std::f64::consts::PI
}

/// Returns the angle of the given leg for y.
pub fn leg_angle_y(args: &mut Args) -> Result<MemoryItem, KclError> {
    let (hypotenuse, leg) = args.get_hypotenuse_leg()?;
    let result = inner_leg_angle_y(hypotenuse, leg);
    args.make_user_val_from_f64(result)
}

/// Returns the angle of the given leg for y.
#[stdlib {
    name = "legAngY",
}]
fn inner_leg_angle_y(hypotenuse: f64, leg: f64) -> f64 {
    (leg.min(hypotenuse) / hypotenuse).asin() * 180.0 / std::f64::consts::PI
}

/// The primitive types that can be used in a KCL file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Display, FromStr)]
#[serde(rename_all = "lowercase")]
#[display(style = "lowercase")]
pub enum Primitive {
    /// A boolean value.
    Bool,
    /// A number value.
    Number,
    /// A string value.
    String,
    /// A uuid value.
    Uuid,
}

#[cfg(test)]
mod tests {
    use crate::std::StdLib;
    use itertools::Itertools;

    #[test]
    fn test_generate_stdlib_markdown_docs() {
        let stdlib = StdLib::new();
        let mut buf = String::new();

        buf.push_str("<!--- DO NOT EDIT THIS FILE. IT IS AUTOMATICALLY GENERATED. -->\n\n");

        buf.push_str("# KCL Standard Library\n\n");

        // Generate a table of contents.
        buf.push_str("## Table of Contents\n\n");

        buf.push_str("* [Functions](#functions)\n");

        for key in stdlib.fns.keys().sorted() {
            let internal_fn = stdlib.fns.get(key).unwrap();
            if internal_fn.unpublished() || internal_fn.deprecated() {
                continue;
            }

            buf.push_str(&format!("\t* [`{}`](#{})\n", internal_fn.name(), internal_fn.name()));
        }

        buf.push_str("\n\n");

        buf.push_str("## Functions\n\n");

        for key in stdlib.fns.keys().sorted() {
            let internal_fn = stdlib.fns.get(key).unwrap();
            if internal_fn.unpublished() {
                continue;
            }

            let mut fn_docs = String::new();

            if internal_fn.deprecated() {
                fn_docs.push_str(&format!("### {} DEPRECATED\n\n", internal_fn.name()));
            } else {
                fn_docs.push_str(&format!("### {}\n\n", internal_fn.name()));
            }

            fn_docs.push_str(&format!("{}\n\n", internal_fn.summary()));
            fn_docs.push_str(&format!("{}\n\n", internal_fn.description()));

            fn_docs.push_str("```\n");
            let signature = internal_fn.fn_signature();
            fn_docs.push_str(&signature);
            fn_docs.push_str("\n```\n\n");

            fn_docs.push_str("#### Arguments\n\n");
            for arg in internal_fn.args() {
                let (format, should_be_indented) = arg.get_type_string().unwrap();
                if let Some(description) = arg.description() {
                    fn_docs.push_str(&format!("* `{}`: `{}` - {}\n", arg.name, arg.type_, description));
                } else {
                    fn_docs.push_str(&format!("* `{}`: `{}`\n", arg.name, arg.type_));
                }

                if should_be_indented {
                    fn_docs.push_str(&format!("```\n{}\n```\n", format));
                }
            }

            if let Some(return_type) = internal_fn.return_value() {
                fn_docs.push_str("\n#### Returns\n\n");
                if let Some(description) = return_type.description() {
                    fn_docs.push_str(&format!("* `{}` - {}\n", return_type.type_, description));
                } else {
                    fn_docs.push_str(&format!("* `{}`\n", return_type.type_));
                }

                let (format, should_be_indented) = return_type.get_type_string().unwrap();
                if should_be_indented {
                    fn_docs.push_str(&format!("```\n{}\n```\n", format));
                }
            }

            fn_docs.push_str("\n\n\n");

            buf.push_str(&fn_docs);
        }

        expectorate::assert_contents("../../../docs/kcl.md", &buf);
    }

    #[test]
    fn test_generate_stdlib_json_schema() {
        let stdlib = StdLib::new();

        let mut json_data = vec![];

        for key in stdlib.fns.keys().sorted() {
            let internal_fn = stdlib.fns.get(key).unwrap();
            json_data.push(internal_fn.to_json().unwrap());
        }

        expectorate::assert_contents(
            "../../../docs/kcl.json",
            &serde_json::to_string_pretty(&json_data).unwrap(),
        );
    }
}