shape-lsp 0.3.1

Language Server Protocol implementation for Shape
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
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
//! Symbol extraction from Shape programs
//!
//! Extracts user-defined symbols (variables, functions, patterns) for completion.

use crate::doc_render::render_doc_comment;
use shape_ast::ast::{
    DestructurePattern, ExportItem, Item, Program, Span, TypeAnnotation, VarKind,
};
use tower_lsp_server::ls_types::{
    CompletionItem, CompletionItemKind, CompletionItemTag, Documentation, MarkupContent, MarkupKind,
};

/// Convert a TypeAnnotation to a readable string
fn format_type_annotation(annotation: &TypeAnnotation) -> String {
    match annotation {
        TypeAnnotation::Basic(name) => name.clone(),
        TypeAnnotation::Reference(name) => name.to_string(),
        TypeAnnotation::Generic { name, args } => {
            if args.is_empty() {
                name.to_string()
            } else {
                let arg_list: Vec<String> = args.iter().map(format_type_annotation).collect();
                format!("{}<{}>", name, arg_list.join(", "))
            }
        }
        TypeAnnotation::Array(inner) => format!("Array<{}>", format_type_annotation(inner)),
        TypeAnnotation::Tuple(types) => {
            let type_list: Vec<String> = types.iter().map(format_type_annotation).collect();
            format!("({})", type_list.join(", "))
        }
        TypeAnnotation::Object(_) => "Object".to_string(),
        TypeAnnotation::Function {
            params, returns, ..
        } => {
            let param_list: Vec<String> = params
                .iter()
                .map(|p| format_type_annotation(&p.type_annotation))
                .collect();
            format!(
                "({}) -> {}",
                param_list.join(", "),
                format_type_annotation(returns)
            )
        }
        TypeAnnotation::Union(types) => {
            let type_list: Vec<String> = types.iter().map(format_type_annotation).collect();
            type_list.join(" | ")
        }
        TypeAnnotation::Intersection(types) => {
            let type_list: Vec<String> = types.iter().map(format_type_annotation).collect();
            type_list.join(" + ")
        }
        TypeAnnotation::Void => "void".to_string(),
        TypeAnnotation::Never => "never".to_string(),
        TypeAnnotation::Null => "None".to_string(),
        TypeAnnotation::Undefined => "undefined".to_string(),
        TypeAnnotation::Dyn(traits) => format!("dyn {}", traits.iter().map(|t| t.as_str()).collect::<Vec<_>>().join(" + ")),
    }
}

/// Information about a symbol in the program
#[derive(Debug, Clone)]
pub struct SymbolInfo {
    pub name: String,
    pub kind: SymbolKind,
    pub detail: Option<String>,
    pub documentation: Option<String>,
    /// Type annotation for variables/constants
    pub type_annotation: Option<String>,
    /// All annotations applied to this symbol
    pub annotations: Vec<String>,
    /// Whether the symbol's doc-comment carries a `@deprecated` tag.
    /// Surfaces in completions via `CompletionItemTag::DEPRECATED`.
    pub deprecated: bool,
}

/// Type of symbol
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SymbolKind {
    Variable,
    Constant,
    Function,
    Type,
}

fn rendered_doc_for_span(program: &Program, span: Span) -> Option<String> {
    program
        .docs
        .comment_for_span(span)
        .map(|comment| render_doc_comment(program, comment, None, None, None))
}

/// Returns true when the doc-comment attached to `span` carries a `@deprecated`
/// tag. Used to emit `CompletionItemTag::DEPRECATED` (LSP feature 1.12).
fn deprecated_for_span(program: &Program, span: Span) -> bool {
    program
        .docs
        .comment_for_span(span)
        .is_some_and(|comment| comment.deprecated_doc().is_some())
}

/// Extract all symbols from a parsed program
pub fn extract_symbols(program: &Program) -> Vec<SymbolInfo> {
    let mut symbols = Vec::new();

    for item in &program.items {
        match item {
            Item::Statement(statement, _) => {
                // Extract symbols from statements (which may contain variable declarations)
                use shape_ast::ast::Statement;
                if let Statement::VariableDecl(var_decl, _) = statement {
                    let kind = match var_decl.kind {
                        VarKind::Let => SymbolKind::Variable,
                        VarKind::Var => SymbolKind::Variable,
                        VarKind::Const => SymbolKind::Constant,
                    };

                    let type_str = var_decl
                        .type_annotation
                        .as_ref()
                        .map(format_type_annotation);
                    for (name, _) in var_decl.pattern.get_bindings() {
                        symbols.push(SymbolInfo {
                            name,
                            kind,
                            detail: type_str.clone(),
                            documentation: None,
                            type_annotation: type_str.clone(),
                            annotations: vec![],
                            deprecated: false,
                        });
                    }
                }
            }
            Item::VariableDecl(var_decl, _) => {
                // Extract variable/constant names
                let kind = match var_decl.kind {
                    VarKind::Let => SymbolKind::Variable,
                    VarKind::Var => SymbolKind::Variable,
                    VarKind::Const => SymbolKind::Constant,
                };

                let type_str = var_decl
                    .type_annotation
                    .as_ref()
                    .map(format_type_annotation);
                for (name, _) in var_decl.pattern.get_bindings() {
                    symbols.push(SymbolInfo {
                        name,
                        kind,
                        detail: type_str.clone(),
                        documentation: None,
                        type_annotation: type_str.clone(),
                        annotations: vec![],
                        deprecated: false,
                    });
                }
            }
            Item::Function(func_def, span) => {
                // Extract function name and signature (including & for reference params)
                let params: Vec<String> = func_def
                    .params
                    .iter()
                    .flat_map(|p| {
                        let prefix = if p.is_reference { "&" } else { "" };
                        p.get_identifiers()
                            .into_iter()
                            .map(move |name| format!("{}{}", prefix, name))
                    })
                    .collect();

                // Extract all annotation names generically
                let annotations: Vec<String> = func_def
                    .annotations
                    .iter()
                    .map(|a| a.name.clone())
                    .collect();

                let signature = format!("{}({})", func_def.name, params.join(", "));
                let doc = rendered_doc_for_span(program, *span);

                symbols.push(SymbolInfo {
                    name: func_def.name.clone(),
                    kind: SymbolKind::Function,
                    detail: Some(signature),
                    documentation: doc,
                    type_annotation: None,
                    annotations,
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::TypeAlias(type_alias, span) => {
                symbols.push(SymbolInfo {
                    name: type_alias.name.clone(),
                    kind: SymbolKind::Type,
                    detail: Some("type alias".to_string()),
                    documentation: rendered_doc_for_span(program, *span),
                    type_annotation: None,
                    annotations: vec![],
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::StructType(struct_def, span) => {
                symbols.push(SymbolInfo {
                    name: struct_def.name.clone(),
                    kind: SymbolKind::Type,
                    detail: Some("type".to_string()),
                    documentation: rendered_doc_for_span(program, *span),
                    type_annotation: None,
                    annotations: vec![],
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::Trait(trait_def, span) => {
                symbols.push(SymbolInfo {
                    name: trait_def.name.clone(),
                    kind: SymbolKind::Type,
                    detail: Some("trait".to_string()),
                    documentation: rendered_doc_for_span(program, *span),
                    type_annotation: None,
                    annotations: vec![],
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::Enum(enum_def, span) => {
                symbols.push(SymbolInfo {
                    name: enum_def.name.clone(),
                    kind: SymbolKind::Type,
                    detail: Some("enum".to_string()),
                    documentation: rendered_doc_for_span(program, *span),
                    type_annotation: None,
                    annotations: vec![],
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::ForeignFunction(foreign_fn, span) => {
                let params: Vec<String> = foreign_fn
                    .params
                    .iter()
                    .flat_map(|p| {
                        let prefix = if p.is_reference { "&" } else { "" };
                        p.get_identifiers()
                            .into_iter()
                            .map(move |name| format!("{}{}", prefix, name))
                    })
                    .collect();
                let annotations: Vec<String> = foreign_fn
                    .annotations
                    .iter()
                    .map(|a| a.name.clone())
                    .collect();
                let signature = if let Some(ref rt) = foreign_fn.return_type {
                    format!(
                        "fn {} {}({}) -> {}",
                        foreign_fn.language,
                        foreign_fn.name,
                        params.join(", "),
                        format_type_annotation(rt)
                    )
                } else {
                    format!(
                        "fn {} {}({})",
                        foreign_fn.language,
                        foreign_fn.name,
                        params.join(", ")
                    )
                };
                symbols.push(SymbolInfo {
                    name: foreign_fn.name.clone(),
                    kind: SymbolKind::Function,
                    detail: Some(signature),
                    documentation: rendered_doc_for_span(program, *span),
                    type_annotation: None,
                    annotations,
                    deprecated: deprecated_for_span(program, *span),
                });
            }
            Item::Export(export_stmt, span) => {
                // Extract symbols from exported items
                match &export_stmt.item {
                    ExportItem::Function(func_def) => {
                        let params: Vec<String> = func_def
                            .params
                            .iter()
                            .flat_map(|p| p.get_identifiers())
                            .collect();

                        let annotations: Vec<String> = func_def
                            .annotations
                            .iter()
                            .map(|a| a.name.clone())
                            .collect();

                        let signature = format!("{}({})", func_def.name, params.join(", "));
                        let doc = rendered_doc_for_span(program, *span);

                        symbols.push(SymbolInfo {
                            name: func_def.name.clone(),
                            kind: SymbolKind::Function,
                            detail: Some(signature),
                            documentation: doc,
                            type_annotation: None,
                            annotations,
                            deprecated: deprecated_for_span(program, *span),
                        });
                    }
                    ExportItem::Enum(enum_def) => {
                        symbols.push(SymbolInfo {
                            name: enum_def.name.clone(),
                            kind: SymbolKind::Type,
                            detail: Some("enum".to_string()),
                            documentation: rendered_doc_for_span(program, *span),
                            type_annotation: None,
                            annotations: vec![],
                            deprecated: deprecated_for_span(program, *span),
                        });
                    }
                    ExportItem::Struct(struct_def) => {
                        symbols.push(SymbolInfo {
                            name: struct_def.name.clone(),
                            kind: SymbolKind::Type,
                            detail: Some("struct".to_string()),
                            documentation: rendered_doc_for_span(program, *span),
                            type_annotation: None,
                            annotations: vec![],
                            deprecated: deprecated_for_span(program, *span),
                        });
                    }
                    _ => {
                        // Skip named exports and re-exports for now
                    }
                }
            }
            _ => {
                // Skip other items for now
            }
        }
    }

    symbols
}

/// Extract name from a destructure pattern (simplified — returns first binding only)
pub fn get_pattern_name(pattern: &DestructurePattern) -> Option<String> {
    pattern
        .get_bindings()
        .into_iter()
        .next()
        .map(|(name, _)| name)
}

/// Extract all bound names and their spans from a destructure pattern.
/// Delegates to `DestructurePattern::get_bindings()` — the canonical implementation
/// shared with the compiler and semantic analyzer.
pub fn get_pattern_names(pattern: &DestructurePattern) -> Vec<(String, Span)> {
    pattern.get_bindings()
}

/// Convert symbols to completion items
pub fn symbols_to_completions(symbols: &[SymbolInfo]) -> Vec<CompletionItem> {
    symbols
        .iter()
        .map(|symbol| {
            let kind = match symbol.kind {
                SymbolKind::Variable | SymbolKind::Constant => CompletionItemKind::VARIABLE,
                SymbolKind::Function => CompletionItemKind::FUNCTION,
                SymbolKind::Type => CompletionItemKind::STRUCT,
            };

            let documentation = symbol.documentation.as_ref().map(|doc| {
                Documentation::MarkupContent(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: doc.clone(),
                })
            });

            // LSP feature 1.12 — surface `@deprecated` doc-tag as
            // CompletionItemTag::DEPRECATED so editors render the item struck-through.
            let tags = if symbol.deprecated {
                Some(vec![CompletionItemTag::DEPRECATED])
            } else {
                None
            };

            CompletionItem {
                label: symbol.name.clone(),
                kind: Some(kind),
                detail: symbol.detail.clone(),
                documentation,
                tags,
                ..CompletionItem::default()
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use shape_ast::parser::parse_program;

    #[test]
    fn test_extract_variables() {
        let code = r#"let x = 5;
const PI = 3.14;
var counter = 0;"#;

        let program = parse_program(code).expect("Failed to parse test code");
        eprintln!("Program items count: {}", program.items.len());
        for (i, item) in program.items.iter().enumerate() {
            eprintln!("Item {}: {:?}", i, std::mem::discriminant(item));
        }
        let symbols = extract_symbols(&program);

        assert_eq!(
            symbols.len(),
            3,
            "Expected 3 symbols, found {}: {:?}",
            symbols.len(),
            symbols
        );
        assert!(
            symbols
                .iter()
                .any(|s| s.name == "x" && s.kind == SymbolKind::Variable)
        );
        assert!(
            symbols
                .iter()
                .any(|s| s.name == "PI" && s.kind == SymbolKind::Constant)
        );
        assert!(
            symbols
                .iter()
                .any(|s| s.name == "counter" && s.kind == SymbolKind::Variable)
        );
    }

    #[test]
    fn test_extract_functions() {
        let code = r#"
            function add(a, b) {
                return a + b;
            }

            function greet(name) {
                return "Hello " + name;
            }
        "#;

        let program = parse_program(code).unwrap();
        let symbols = extract_symbols(&program);

        assert_eq!(symbols.len(), 2);
        assert!(
            symbols
                .iter()
                .any(|s| s.name == "add" && s.kind == SymbolKind::Function)
        );
        assert!(
            symbols
                .iter()
                .any(|s| s.name == "greet" && s.kind == SymbolKind::Function)
        );
    }

    // Note: The grammar now supports annotated functions at the top level.
    // The old pattern_def rule was removed, resolving the conflict.
    // Annotations work via `annotations? ~ function_def` in the `item` rule.

    #[test]
    fn test_extract_annotated_functions() {
        let code = r#"
annotation my_ann() {}

@my_ann
function hammer(candle) {
    return candle.close > candle.open;
}

@my_ann
function doji(candle) {
    return abs(candle.close - candle.open) < 0.1;
}
        "#;

        let program = parse_program(code).unwrap();
        let symbols = extract_symbols(&program);

        // 3 symbols: the annotation definition + 2 annotated functions
        assert!(symbols.len() >= 2);
        // Annotated functions are always SymbolKind::Function
        assert!(symbols.iter().any(|s| s.name == "hammer"
            && s.kind == SymbolKind::Function
            && s.annotations.contains(&"my_ann".to_string())));
        assert!(symbols.iter().any(|s| s.name == "doji"
            && s.kind == SymbolKind::Function
            && s.annotations.contains(&"my_ann".to_string())));
    }

    #[test]
    fn test_symbols_to_completions() {
        let symbols = vec![
            SymbolInfo {
                name: "myVar".to_string(),
                kind: SymbolKind::Variable,
                detail: Some("Number".to_string()),
                documentation: None,
                type_annotation: Some("Number".to_string()),
                annotations: vec![],
                deprecated: false,
            },
            SymbolInfo {
                name: "myFunc".to_string(),
                kind: SymbolKind::Function,
                detail: Some("myFunc(a, b)".to_string()),
                documentation: Some("A test function".to_string()),
                type_annotation: None,
                annotations: vec![],
                deprecated: false,
            },
        ];

        let completions = symbols_to_completions(&symbols);

        assert_eq!(completions.len(), 2);
        assert_eq!(completions[0].label, "myVar");
        assert_eq!(completions[0].kind, Some(CompletionItemKind::VARIABLE));
        assert_eq!(completions[1].label, "myFunc");
        assert_eq!(completions[1].kind, Some(CompletionItemKind::FUNCTION));
    }

    #[test]
    fn test_annotated_function_completion() {
        let symbols = vec![SymbolInfo {
            name: "my_strategy".to_string(),
            kind: SymbolKind::Function,
            detail: Some("my_strategy(row, ctx)".to_string()),
            documentation: None,
            type_annotation: None,
            annotations: vec!["strategy".to_string()],
            deprecated: false,
        }];

        let completions = symbols_to_completions(&symbols);

        assert_eq!(completions.len(), 1);
        // Annotated functions show as FUNCTION kind
        assert_eq!(completions[0].kind, Some(CompletionItemKind::FUNCTION));
    }

    #[test]
    fn test_filter_symbols_by_annotation() {
        let symbols = vec![
            SymbolInfo {
                name: "regular".to_string(),
                kind: SymbolKind::Function,
                detail: None,
                documentation: None,
                type_annotation: None,
                annotations: vec![],
                deprecated: false,
            },
            SymbolInfo {
                name: "my_strategy".to_string(),
                kind: SymbolKind::Function,
                detail: None,
                documentation: None,
                type_annotation: None,
                annotations: vec!["strategy".to_string()],
                deprecated: false,
            },
        ];

        let strategies: Vec<_> = symbols
            .iter()
            .filter(|s| s.annotations.contains(&"strategy".to_string()))
            .collect();
        assert_eq!(strategies.len(), 1);
        assert_eq!(strategies[0].name, "my_strategy");
    }

    /// W2.2 (LSP feature 1.12): a `@deprecated` doc-tag on a user-defined
    /// function should be captured on `SymbolInfo::deprecated`.
    #[test]
    fn test_deprecated_doc_tag_flag_extraction() {
        let code = r#"
/// Old computation kept for back-compat.
///
/// @deprecated Use `new_compute` instead.
fn old_compute(x: int) -> int {
    return x * 2;
}

fn new_compute(x: int) -> int {
    return x * 3;
}
"#;

        let program = parse_program(code).expect("parse failed");
        let symbols = extract_symbols(&program);
        let old = symbols
            .iter()
            .find(|s| s.name == "old_compute")
            .expect("old_compute symbol present");
        let new = symbols
            .iter()
            .find(|s| s.name == "new_compute")
            .expect("new_compute symbol present");

        assert!(
            old.deprecated,
            "old_compute carries @deprecated doc-tag → SymbolInfo.deprecated should be true"
        );
        assert!(
            !new.deprecated,
            "new_compute has no @deprecated → SymbolInfo.deprecated should be false"
        );
    }

    /// W2.2 (LSP feature 1.12): `symbols_to_completions` should emit
    /// `CompletionItemTag::DEPRECATED` for symbols flagged deprecated.
    #[test]
    fn test_symbols_to_completions_emits_deprecated_tag() {
        let symbols = vec![
            SymbolInfo {
                name: "fresh".to_string(),
                kind: SymbolKind::Function,
                detail: None,
                documentation: None,
                type_annotation: None,
                annotations: vec![],
                deprecated: false,
            },
            SymbolInfo {
                name: "stale".to_string(),
                kind: SymbolKind::Function,
                detail: None,
                documentation: None,
                type_annotation: None,
                annotations: vec![],
                deprecated: true,
            },
        ];

        let completions = symbols_to_completions(&symbols);
        let fresh = completions.iter().find(|c| c.label == "fresh").unwrap();
        let stale = completions.iter().find(|c| c.label == "stale").unwrap();

        assert!(fresh.tags.is_none(), "fresh symbol should carry no tags");
        let tags = stale.tags.as_ref().expect("stale symbol should carry tags");
        assert!(
            tags.contains(&CompletionItemTag::DEPRECATED),
            "stale symbol should carry CompletionItemTag::DEPRECATED, got {:?}",
            tags
        );
    }
}