kcl_lib/docs/
mod.rs

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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Functions for generating docs for our stdlib functions.

#[cfg(test)]
mod gen_std_tests;

use std::path::Path;

use anyhow::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tower_lsp::lsp_types::{
    CompletionItem, CompletionItemKind, CompletionItemLabelDetails, Documentation, InsertTextFormat, MarkupContent,
    MarkupKind, ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation,
};

use crate::std::Primitive;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct StdLibFnData {
    /// The name of the function.
    pub name: String,
    /// The summary of the function.
    pub summary: String,
    /// The description of the function.
    pub description: String,
    /// The tags of the function.
    pub tags: Vec<String>,
    /// The args of the function.
    pub args: Vec<StdLibFnArg>,
    /// The return value of the function.
    pub return_value: Option<StdLibFnArg>,
    /// If the function is unpublished.
    pub unpublished: bool,
    /// If the function is deprecated.
    pub deprecated: bool,
    /// Code examples.
    /// These are tested and we know they compile and execute.
    pub examples: Vec<String>,
}

/// This struct defines a single argument to a stdlib function.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, ts_rs::TS)]
// There's a bug in ts_rs where this isn't correctly imported by StdLibFnData.
#[ts(export_to = "StdLibFnData.ts")]
#[serde(rename_all = "camelCase")]
pub struct StdLibFnArg {
    /// The name of the argument.
    pub name: String,
    /// The type of the argument.
    pub type_: String,
    /// The schema of the argument.
    #[ts(type = "any")]
    pub schema: schemars::schema::RootSchema,
    /// If the argument is required.
    pub required: bool,
}

impl StdLibFnArg {
    /// If the argument is a primitive.
    pub fn is_primitive(&self) -> Result<bool> {
        is_primitive(&self.schema.schema.clone().into()).map(|r| r.is_some())
    }

    pub fn get_autocomplete_string(&self) -> Result<String> {
        get_autocomplete_string_from_schema(&self.schema.schema.clone().into())
    }

    pub fn get_autocomplete_snippet(&self, index: usize) -> Result<Option<(usize, String)>> {
        if self.type_ == "Sketch"
            || self.type_ == "SketchSet"
            || self.type_ == "Solid"
            || self.type_ == "SolidSet"
            || self.type_ == "SketchSurface"
            || self.type_ == "SketchOrSurface"
        {
            return Ok(Some((index, format!("${{{}:{}}}", index, "%"))));
        } else if self.type_ == "TagDeclarator" && self.required {
            return Ok(Some((index, format!("${{{}:{}}}", index, "$myTag"))));
        } else if self.type_ == "TagIdentifier" && self.required {
            // TODO: actually use the ast to populate this.
            return Ok(Some((index, format!("${{{}:{}}}", index, "myTag"))));
        } else if self.type_ == "[KclValue]" && self.required {
            return Ok(Some((index, format!("${{{}:{}}}", index, "[0..9]"))));
        } else if self.type_ == "KclValue" && self.required {
            return Ok(Some((index, format!("${{{}:{}}}", index, "3"))));
        }
        get_autocomplete_snippet_from_schema(&self.schema.schema.clone().into(), index)
    }

    pub fn description(&self) -> Option<String> {
        get_description_string_from_schema(&self.schema.clone())
    }
}

impl From<StdLibFnArg> for ParameterInformation {
    fn from(arg: StdLibFnArg) -> Self {
        ParameterInformation {
            label: ParameterLabel::Simple(arg.name.to_string()),
            documentation: arg.description().map(|description| {
                Documentation::MarkupContent(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: description,
                })
            }),
        }
    }
}

/// This trait defines functions called upon stdlib functions to generate
/// documentation for them.
pub trait StdLibFn: std::fmt::Debug + Send + Sync {
    /// The name of the function.
    fn name(&self) -> String;

    /// The summary of the function.
    fn summary(&self) -> String;

    /// The description of the function.
    fn description(&self) -> String;

    /// The tags of the function.
    fn tags(&self) -> Vec<String>;

    /// The args of the function.
    fn args(&self, inline_subschemas: bool) -> Vec<StdLibFnArg>;

    /// The return value of the function.
    fn return_value(&self, inline_subschemas: bool) -> Option<StdLibFnArg>;

    /// If the function is unpublished.
    fn unpublished(&self) -> bool;

    /// If the function is deprecated.
    fn deprecated(&self) -> bool;

    /// Any example code blocks.
    fn examples(&self) -> Vec<String>;

    /// The function itself.
    fn std_lib_fn(&self) -> crate::std::StdFn;

    /// Helper function to clone the boxed trait object.
    fn clone_box(&self) -> Box<dyn StdLibFn>;

    /// Return a JSON struct representing the function.
    fn to_json(&self) -> Result<StdLibFnData> {
        Ok(StdLibFnData {
            name: self.name(),
            summary: self.summary(),
            description: self.description(),
            tags: self.tags(),
            args: self.args(false),
            return_value: self.return_value(false),
            unpublished: self.unpublished(),
            deprecated: self.deprecated(),
            examples: self.examples(),
        })
    }

    fn fn_signature(&self) -> String {
        let mut signature = String::new();
        signature.push_str(&format!("{}(", self.name()));
        for (i, arg) in self.args(false).iter().enumerate() {
            if i > 0 {
                signature.push_str(", ");
            }
            if arg.required {
                signature.push_str(&format!("{}: {}", arg.name, arg.type_));
            } else {
                signature.push_str(&format!("{}?: {}", arg.name, arg.type_));
            }
        }
        signature.push(')');
        if let Some(return_value) = self.return_value(false) {
            signature.push_str(&format!(" -> {}", return_value.type_));
        }

        signature
    }

    fn to_completion_item(&self) -> Result<CompletionItem> {
        Ok(CompletionItem {
            label: self.name(),
            label_details: Some(CompletionItemLabelDetails {
                detail: Some(self.fn_signature().replace(&self.name(), "")),
                description: None,
            }),
            kind: Some(CompletionItemKind::FUNCTION),
            detail: None,
            documentation: Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: if !self.description().is_empty() {
                    format!("{}\n\n{}", self.summary(), self.description())
                } else {
                    self.summary()
                },
            })),
            deprecated: Some(self.deprecated()),
            preselect: None,
            sort_text: None,
            filter_text: None,
            insert_text: Some(self.to_autocomplete_snippet()?),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            insert_text_mode: None,
            text_edit: None,
            additional_text_edits: None,
            command: None,
            commit_characters: None,
            data: None,
            tags: None,
        })
    }

    fn to_autocomplete_snippet(&self) -> Result<String> {
        let mut args = Vec::new();
        let mut index = 0;
        for arg in self.args(true).iter() {
            if let Some((i, arg_str)) = arg.get_autocomplete_snippet(index)? {
                index = i + 1;
                args.push(arg_str);
            }
        }
        // We end with ${} so you can jump to the end of the snippet.
        // After the last argument.
        Ok(format!("{}({})${{}}", self.name(), args.join(", ")))
    }

    fn to_signature_help(&self) -> SignatureHelp {
        // Fill this in based on the current position of the cursor.
        let active_parameter = None;

        SignatureHelp {
            signatures: vec![SignatureInformation {
                label: self.name(),
                documentation: Some(Documentation::MarkupContent(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: if !self.description().is_empty() {
                        format!("{}\n\n{}", self.summary(), self.description())
                    } else {
                        self.summary()
                    },
                })),
                parameters: Some(self.args(true).into_iter().map(|arg| arg.into()).collect()),
                active_parameter,
            }],
            active_signature: Some(0),
            active_parameter,
        }
    }
}

impl JsonSchema for dyn StdLibFn {
    fn schema_name() -> String {
        "StdLibFn".to_string()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        gen.subschema_for::<StdLibFnData>()
    }
}

impl Serialize for Box<dyn StdLibFn> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_json().unwrap().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Box<dyn StdLibFn> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let data = StdLibFnData::deserialize(deserializer)?;
        let stdlib = crate::std::StdLib::new();
        let stdlib_fn = stdlib
            .get(&data.name)
            .ok_or_else(|| serde::de::Error::custom(format!("StdLibFn {} not found", data.name)))?;
        Ok(stdlib_fn)
    }
}

impl ts_rs::TS for dyn StdLibFn {
    type WithoutGenerics = Self;

    fn name() -> String {
        "StdLibFnData".to_string()
    }

    fn decl() -> String {
        StdLibFnData::decl()
    }

    fn decl_concrete() -> String {
        StdLibFnData::decl_concrete()
    }

    fn inline() -> String {
        StdLibFnData::inline()
    }

    fn inline_flattened() -> String {
        StdLibFnData::inline_flattened()
    }

    fn output_path() -> Option<&'static Path> {
        StdLibFnData::output_path()
    }
}

impl Clone for Box<dyn StdLibFn> {
    fn clone(&self) -> Box<dyn StdLibFn> {
        self.clone_box()
    }
}

pub fn get_description_string_from_schema(schema: &schemars::schema::RootSchema) -> Option<String> {
    if let Some(metadata) = &schema.schema.metadata {
        if let Some(description) = &metadata.description {
            return Some(description.to_string());
        }
    }

    if let Some(reference) = &schema.schema.reference {
        if let Some(definition) = schema.definitions.get(reference.split('/').last().unwrap_or("")) {
            let schemars::schema::Schema::Object(definition) = definition else {
                return None;
            };
            if let Some(metadata) = &definition.metadata {
                if let Some(description) = &metadata.description {
                    return Some(description.to_string());
                }
            }
        }
    }

    // If we have subschemas iterate over them and recursively create references.
    if let Some(subschema) = &schema.schema.subschemas {
        if let Some(one_of) = &subschema.one_of {
            if one_of.len() == 1 {
                return get_description_string_from_schema(&schemars::schema::RootSchema {
                    meta_schema: schema.meta_schema.clone(),
                    schema: one_of[0].clone().into(),
                    definitions: schema.definitions.clone(),
                });
            }
        }

        if let Some(all_of) = &subschema.all_of {
            if all_of.len() == 1 {
                return get_description_string_from_schema(&schemars::schema::RootSchema {
                    meta_schema: schema.meta_schema.clone(),
                    schema: all_of[0].clone().into(),
                    definitions: schema.definitions.clone(),
                });
            }
        }

        if let Some(any_of) = &subschema.any_of {
            if any_of.len() == 1 {
                return get_description_string_from_schema(&schemars::schema::RootSchema {
                    meta_schema: schema.meta_schema.clone(),
                    schema: any_of[0].clone().into(),
                    definitions: schema.definitions.clone(),
                });
            }
        }
    }

    None
}

pub fn is_primitive(schema: &schemars::schema::Schema) -> Result<Option<Primitive>> {
    match schema {
        schemars::schema::Schema::Object(o) => {
            if o.enum_values.is_some() {
                // It's an enum so it's not a primitive.
                return Ok(None);
            }

            // Check if there
            if let Some(format) = &o.format {
                if format == "uuid" {
                    return Ok(Some(Primitive::Uuid));
                } else if format == "double"
                    || format == "uint"
                    || format == "int32"
                    || format == "int64"
                    || format == "uint8"
                    || format == "uint32"
                    || format == "uint64"
                {
                    return Ok(Some(Primitive::Number));
                } else {
                    anyhow::bail!("unknown format: {}", format);
                }
            }

            if o.object.is_some() {
                // It's an object so it's not a primitive.
                return Ok(None);
            }

            if o.array.is_some() {
                return Ok(None);
            }

            if o.subschemas.is_some() {
                return Ok(None);
            }

            if let Some(schemars::schema::SingleOrVec::Single(single)) = &o.instance_type {
                if schemars::schema::InstanceType::Boolean == **single {
                    return Ok(Some(Primitive::Bool));
                } else if schemars::schema::InstanceType::String == **single
                    || schemars::schema::InstanceType::Null == **single
                {
                    return Ok(Some(Primitive::String));
                }
            }

            if o.reference.is_some() {
                return Ok(None);
            }

            anyhow::bail!("unknown type: {:#?}", o)
        }
        schemars::schema::Schema::Bool(_) => Ok(Some(Primitive::Bool)),
    }
}

fn get_autocomplete_snippet_from_schema(
    schema: &schemars::schema::Schema,
    index: usize,
) -> Result<Option<(usize, String)>> {
    match schema {
        schemars::schema::Schema::Object(o) => {
            if let Some(serde_json::Value::Bool(nullable)) = o.extensions.get("nullable") {
                if *nullable {
                    return Ok(None);
                }
            }
            if o.enum_values.is_some() {
                let auto_str = get_autocomplete_string_from_schema(schema)?;
                return Ok(Some((index, format!("${{{}:{}}}", index, auto_str))));
            }

            if let Some(format) = &o.format {
                if format == "uuid" {
                    return Ok(Some((index, format!(r#"${{{}:"tag_or_edge_fn"}}"#, index))));
                } else if format == "double" {
                    return Ok(Some((index, format!(r#"${{{}:3.14}}"#, index))));
                } else if format == "uint" || format == "int64" || format == "uint32" || format == "uint64" {
                    return Ok(Some((index, format!(r#"${{{}:10}}"#, index))));
                } else {
                    anyhow::bail!("unknown format: {}", format);
                }
            }

            if let Some(obj_val) = &o.object {
                let mut fn_docs = String::new();
                fn_docs.push_str("{\n");
                // Let's print out the object's properties.
                let mut i = index;
                for (prop_name, prop) in obj_val.properties.iter() {
                    if prop_name.starts_with('_') {
                        continue;
                    }

                    // Tolerance is a an optional property that we don't want to show in the
                    // autocomplete, since it is mostly for advanced users.
                    if prop_name == "tolerance" {
                        continue;
                    }

                    if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(prop, i)? {
                        fn_docs.push_str(&format!("\t{}: {},\n", prop_name, snippet));
                        i = new_index + 1;
                    }
                }

                fn_docs.push('}');

                return Ok(Some((i - 1, fn_docs)));
            }

            if let Some(array_val) = &o.array {
                if let Some(schemars::schema::SingleOrVec::Single(items)) = &array_val.items {
                    // Let's print out the object's properties.
                    match array_val.max_items {
                        Some(val) => {
                            return Ok(Some((
                                index + (val as usize) - 1,
                                format!(
                                    "[{}]",
                                    (0..val)
                                        .map(|v| get_autocomplete_snippet_from_schema(items, index + (v as usize))
                                            .unwrap()
                                            .unwrap()
                                            .1)
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                ),
                            )));
                        }
                        None => {
                            return Ok(Some((
                                index,
                                format!(
                                    "[{}]",
                                    get_autocomplete_snippet_from_schema(items, index)?
                                        .ok_or_else(|| anyhow::anyhow!("expected snippet"))?
                                        .1
                                ),
                            )));
                        }
                    };
                } else if let Some(items) = &array_val.contains {
                    return Ok(Some((
                        index,
                        format!(
                            "[{}]",
                            get_autocomplete_snippet_from_schema(items, index)?
                                .ok_or_else(|| anyhow::anyhow!("expected snippet"))?
                                .1
                        ),
                    )));
                }
            }

            if let Some(subschemas) = &o.subschemas {
                let mut fn_docs = String::new();
                let mut i = index;
                if let Some(items) = &subschemas.one_of {
                    let mut had_enum_string = false;
                    let mut parsed_enum_values: Vec<String> = Vec::new();
                    for item in items {
                        if let schemars::schema::Schema::Object(o) = item {
                            if let Some(enum_values) = &o.enum_values {
                                for enum_value in enum_values {
                                    if let serde_json::value::Value::String(enum_value) = enum_value {
                                        had_enum_string = true;
                                        parsed_enum_values.push(format!("\"{}\"", enum_value));
                                    } else {
                                        had_enum_string = false;
                                        break;
                                    }
                                }
                                if !had_enum_string {
                                    break;
                                }
                            } else {
                                had_enum_string = false;
                                break;
                            }
                        } else {
                            had_enum_string = false;
                            break;
                        }
                    }

                    if had_enum_string && !parsed_enum_values.is_empty() {
                        return Ok(Some((index, parsed_enum_values[0].to_string())));
                    } else if let Some(item) = items.iter().next() {
                        if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
                            i = new_index + 1;
                            fn_docs.push_str(&snippet);
                        }
                    }
                } else if let Some(items) = &subschemas.any_of {
                    if let Some(item) = items.iter().next() {
                        if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
                            i = new_index + 1;
                            fn_docs.push_str(&snippet);
                        }
                    }
                } else {
                    anyhow::bail!("unknown subschemas: {:#?}", subschemas);
                }

                return Ok(Some((i - 1, fn_docs)));
            }

            if let Some(schemars::schema::SingleOrVec::Single(single)) = &o.instance_type {
                if schemars::schema::InstanceType::Boolean == **single {
                    return Ok(Some((index, format!(r#"${{{}:false}}"#, index))));
                } else if schemars::schema::InstanceType::String == **single {
                    return Ok(Some((index, format!(r#"${{{}:"string"}}"#, index))));
                } else if schemars::schema::InstanceType::Null == **single {
                    return Ok(None);
                }
            }

            anyhow::bail!("unknown type: {:#?}", o)
        }
        schemars::schema::Schema::Bool(_) => Ok(Some((index, format!(r#"${{{}:false}}"#, index)))),
    }
}

fn get_autocomplete_string_from_schema(schema: &schemars::schema::Schema) -> Result<String> {
    match schema {
        schemars::schema::Schema::Object(o) => {
            if let Some(enum_values) = &o.enum_values {
                let mut parsed_enum_values: Vec<String> = Default::default();
                let mut had_enum_string = false;
                for enum_value in enum_values {
                    if let serde_json::value::Value::String(enum_value) = enum_value {
                        had_enum_string = true;
                        parsed_enum_values.push(format!("\"{}\"", enum_value));
                    } else {
                        had_enum_string = false;
                        break;
                    }
                }

                if had_enum_string && !parsed_enum_values.is_empty() {
                    return Ok(parsed_enum_values[0].to_string());
                }
            }

            if let Some(format) = &o.format {
                if format == "uuid" {
                    return Ok(Primitive::Uuid.to_string());
                } else if format == "double"
                    || format == "uint"
                    || format == "int64"
                    || format == "uint32"
                    || format == "uint64"
                {
                    return Ok(Primitive::Number.to_string());
                } else {
                    anyhow::bail!("unknown format: {}", format);
                }
            }

            if let Some(obj_val) = &o.object {
                let mut fn_docs = String::new();
                fn_docs.push_str("{\n");
                // Let's print out the object's properties.
                for (prop_name, prop) in obj_val.properties.iter() {
                    if prop_name.starts_with('_') {
                        continue;
                    }

                    fn_docs.push_str(&format!(
                        "\t{}: {},\n",
                        prop_name,
                        get_autocomplete_string_from_schema(prop)?,
                    ));
                }

                fn_docs.push('}');

                return Ok(fn_docs);
            }

            if let Some(array_val) = &o.array {
                if let Some(schemars::schema::SingleOrVec::Single(items)) = &array_val.items {
                    // Let's print out the object's properties.
                    match array_val.max_items {
                        Some(val) => {
                            return Ok(format!(
                                "[{}]",
                                (0..val).map(|_| "number").collect::<Vec<_>>().join(", ")
                            ));
                        }
                        None => {
                            return Ok(format!("[{}]", get_autocomplete_string_from_schema(items)?));
                        }
                    };
                } else if let Some(items) = &array_val.contains {
                    return Ok(format!("[{}]", get_autocomplete_string_from_schema(items)?));
                }
            }

            if let Some(subschemas) = &o.subschemas {
                let mut fn_docs = String::new();
                if let Some(items) = &subschemas.one_of {
                    let mut had_enum_string = false;
                    let mut parsed_enum_values: Vec<String> = Vec::new();
                    for item in items {
                        if let schemars::schema::Schema::Object(o) = item {
                            if let Some(enum_values) = &o.enum_values {
                                for enum_value in enum_values {
                                    if let serde_json::value::Value::String(enum_value) = enum_value {
                                        had_enum_string = true;
                                        parsed_enum_values.push(format!("\"{}\"", enum_value));
                                    } else {
                                        had_enum_string = false;
                                        break;
                                    }
                                }
                                if !had_enum_string {
                                    break;
                                }
                            } else {
                                had_enum_string = false;
                                break;
                            }
                        } else {
                            had_enum_string = false;
                            break;
                        }
                    }

                    if had_enum_string && !parsed_enum_values.is_empty() {
                        return Ok(parsed_enum_values[0].to_string());
                    } else if let Some(item) = items.iter().next() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_autocomplete_string_from_schema(item)?);
                    }
                } else if let Some(items) = &subschemas.any_of {
                    if let Some(item) = items.iter().next() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_autocomplete_string_from_schema(item)?);
                    }
                } else {
                    anyhow::bail!("unknown subschemas: {:#?}", subschemas);
                }

                return Ok(fn_docs);
            }

            if let Some(schemars::schema::SingleOrVec::Single(single)) = &o.instance_type {
                if schemars::schema::InstanceType::Boolean == **single {
                    return Ok(Primitive::Bool.to_string());
                } else if schemars::schema::InstanceType::String == **single
                    || schemars::schema::InstanceType::Null == **single
                {
                    return Ok(Primitive::String.to_string());
                }
            }

            anyhow::bail!("unknown type: {:#?}", o)
        }
        schemars::schema::Schema::Bool(_) => Ok(Primitive::Bool.to_string()),
    }
}

pub fn completion_item_from_enum_schema(
    schema: &schemars::schema::Schema,
    kind: CompletionItemKind,
) -> Result<CompletionItem> {
    // Get the docs for the schema.
    let schemars::schema::Schema::Object(o) = schema else {
        anyhow::bail!("expected object schema: {:#?}", schema);
    };
    let description = get_description_string_from_schema(&schemars::schema::RootSchema {
        schema: o.clone(),
        ..Default::default()
    })
    .unwrap_or_default();
    let Some(enum_values) = o.enum_values.as_ref() else {
        anyhow::bail!("expected enum values: {:#?}", o);
    };

    if enum_values.len() > 1 {
        anyhow::bail!("expected only one enum value: {:#?}", o);
    }

    if enum_values.is_empty() {
        anyhow::bail!("expected at least one enum value: {:#?}", o);
    }

    let serde_json::Value::String(ref enum_value) = enum_values[0] else {
        anyhow::bail!("expected string enum value: {:#?}", enum_values[0]);
    };

    Ok(CompletionItem {
        label: enum_value.to_string(),
        label_details: None,
        kind: Some(kind),
        detail: Some(description.to_string()),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: description.to_string(),
        })),
        deprecated: Some(false),
        preselect: None,
        sort_text: None,
        filter_text: None,
        insert_text: None,
        insert_text_format: None,
        insert_text_mode: None,
        text_edit: None,
        additional_text_edits: None,
        command: None,
        commit_characters: None,
        data: None,
        tags: None,
    })
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::StdLibFn;

    #[test]
    fn test_serialize_function() {
        let some_function = crate::ast::types::Function::StdLib {
            func: Box::new(crate::std::sketch::Line),
        };
        let serialized = serde_json::to_string(&some_function).unwrap();
        assert!(serialized.contains(r#"{"type":"StdLib""#));
    }

    #[test]
    fn test_deserialize_function() {
        let some_function_string = r#"{"type":"StdLib","func":{"name":"line","summary":"","description":"","tags":[],"returnValue":{"type":"","required":false,"name":"","schema":{},"schemaDefinitions":{}},"args":[],"unpublished":false,"deprecated":false, "examples": []}}"#;
        let some_function: crate::ast::types::Function = serde_json::from_str(some_function_string).unwrap();

        assert_eq!(
            some_function,
            crate::ast::types::Function::StdLib {
                func: Box::new(crate::std::sketch::Line)
            }
        );
    }

    #[test]
    fn get_autocomplete_snippet_line() {
        let line_fn: Box<dyn StdLibFn> = Box::new(crate::std::sketch::Line);
        let snippet = line_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(snippet, r#"line([${0:3.14}, ${1:3.14}], ${2:%})${}"#);
    }

    #[test]
    fn get_autocomplete_snippet_extrude() {
        let extrude_fn: Box<dyn StdLibFn> = Box::new(crate::std::extrude::Extrude);
        let snippet = extrude_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(snippet, r#"extrude(${0:3.14}, ${1:%})${}"#);
    }

    #[test]
    fn get_autocomplete_snippet_fillet() {
        let fillet_fn: Box<dyn StdLibFn> = Box::new(crate::std::fillet::Fillet);
        let snippet = fillet_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"fillet({
	radius: ${0:3.14},
	tags: [${1:"tag_or_edge_fn"}],
}, ${2:%})${}"#
        );
    }

    #[test]
    fn get_autocomplete_snippet_start_sketch_on() {
        let start_sketch_on_fn: Box<dyn StdLibFn> = Box::new(crate::std::sketch::StartSketchOn);
        let snippet = start_sketch_on_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(snippet, r#"startSketchOn(${0:"XY"})${}"#);
    }

    #[test]
    fn get_autocomplete_snippet_pattern_circular_3d() {
        // We test this one specifically because it has ints and floats and strings.
        let pattern_fn: Box<dyn StdLibFn> = Box::new(crate::std::patterns::PatternCircular3D);
        let snippet = pattern_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"patternCircular3d({
	repetitions: ${0:10},
	axis: [${1:3.14}, ${2:3.14}, ${3:3.14}],
	center: [${4:3.14}, ${5:3.14}, ${6:3.14}],
	arcDegrees: ${7:3.14},
	rotateDuplicates: ${8:false},
}, ${9:%})${}"#
        );
    }

    #[test]
    fn get_autocomplete_snippet_revolve() {
        let revolve_fn: Box<dyn StdLibFn> = Box::new(crate::std::revolve::Revolve);
        let snippet = revolve_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"revolve({
	axis: ${0:"X"},
}, ${1:%})${}"#
        );
    }

    #[test]
    fn get_autocomplete_snippet_circle() {
        let circle_fn: Box<dyn StdLibFn> = Box::new(crate::std::shapes::Circle);
        let snippet = circle_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"circle({
	center: [${0:3.14}, ${1:3.14}],
	radius: ${2:3.14},
}, ${3:%})${}"#
        );
    }

    #[test]
    fn get_autocomplete_snippet_arc() {
        let arc_fn: Box<dyn StdLibFn> = Box::new(crate::std::sketch::Arc);
        let snippet = arc_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"arc({
	angleStart: ${0:3.14},
	angleEnd: ${1:3.14},
	radius: ${2:3.14},
}, ${3:%})${}"#
        );
    }

    #[test]
    fn get_autocomplete_snippet_map() {
        let map_fn: Box<dyn StdLibFn> = Box::new(crate::std::array::Map);
        let snippet = map_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(snippet, r#"map(${0:[0..9]})${}"#);
    }

    #[test]
    fn get_autocomplete_snippet_pattern_linear_2d() {
        let pattern_fn: Box<dyn StdLibFn> = Box::new(crate::std::patterns::PatternLinear2D);
        let snippet = pattern_fn.to_autocomplete_snippet().unwrap();
        assert_eq!(
            snippet,
            r#"patternLinear2d({
	repetitions: ${0:10},
	distance: ${1:3.14},
	axis: [${2:3.14}, ${3:3.14}],
}, ${4:%})${}"#
        );
    }

    // We want to test the snippets we compile at lsp start.
    #[test]
    fn get_all_stdlib_autocomplete_snippets() {
        let stdlib = crate::std::StdLib::new();
        crate::lsp::kcl::get_completions_from_stdlib(&stdlib).unwrap();
    }

    // We want to test the signatures we compile at lsp start.
    #[test]
    fn get_all_stdlib_signatures() {
        let stdlib = crate::std::StdLib::new();
        crate::lsp::kcl::get_signatures_from_stdlib(&stdlib).unwrap();
    }
}