shape-runtime 0.3.2

Bytecode compiler, builtins, and runtime infrastructure 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
//! Stdlib metadata extractor for LSP introspection
//!
//! This module parses Shape stdlib files to extract function and pattern
//! metadata for use in LSP completions and hover information.

use crate::metadata::{FunctionCategory, FunctionInfo, ParameterInfo, TypeInfo};
use shape_ast::ast::{
    BuiltinFunctionDecl, BuiltinTypeDecl, DocComment, FunctionDef, Item, Program, TypeAnnotation,
};
use shape_ast::error::Result;
#[cfg(test)]
use shape_ast::parser::parse_program;
use std::path::{Path, PathBuf};

/// Metadata extracted from Shape stdlib
#[derive(Debug, Default)]
pub struct StdlibMetadata {
    /// Exported functions from stdlib
    pub functions: Vec<FunctionInfo>,
    /// Exported patterns from stdlib
    pub patterns: Vec<PatternInfo>,
    /// Declaration-only intrinsic functions from std/core
    pub intrinsic_functions: Vec<FunctionInfo>,
    /// Declaration-only intrinsic types from std/core
    pub intrinsic_types: Vec<TypeInfo>,
}

/// Pattern metadata for LSP
#[derive(Debug, Clone)]
pub struct PatternInfo {
    /// Pattern name
    pub name: String,
    /// Pattern signature
    pub signature: String,
    /// Description (if available from comments)
    pub description: String,
    /// Parameters (pattern variables)
    pub parameters: Vec<ParameterInfo>,
}

impl StdlibMetadata {
    /// Create empty stdlib metadata
    pub fn empty() -> Self {
        Self::default()
    }

    /// Load and parse all stdlib modules from the given path
    pub fn load(stdlib_path: &Path) -> Result<Self> {
        let mut functions = Vec::new();
        let mut patterns = Vec::new();
        let mut intrinsic_functions = Vec::new();
        let mut intrinsic_types = Vec::new();

        if !stdlib_path.exists() {
            return Ok(Self::empty());
        }

        // Use the unified module loader for stdlib discovery + parsing.
        let mut loader = crate::module_loader::ModuleLoader::new();
        loader.set_stdlib_path(stdlib_path.to_path_buf());

        for import_path in loader.list_stdlib_module_imports()? {
            let module_path = import_path
                .strip_prefix("std::")
                .unwrap_or(&import_path)
                .replace("::", "/");
            match loader.load_module(&import_path) {
                Ok(module) => {
                    Self::extract_from_program(
                        &module.ast,
                        &module_path,
                        &mut functions,
                        &mut patterns,
                        &mut intrinsic_functions,
                        &mut intrinsic_types,
                    );
                }
                Err(_) => {
                    // Skip modules that fail to parse/compile metadata.
                }
            }
        }

        Ok(Self {
            functions,
            patterns,
            intrinsic_functions,
            intrinsic_types,
        })
    }

    fn extract_from_program(
        program: &Program,
        module_path: &str,
        functions: &mut Vec<FunctionInfo>,
        _patterns: &mut Vec<PatternInfo>,
        intrinsic_functions: &mut Vec<FunctionInfo>,
        intrinsic_types: &mut Vec<TypeInfo>,
    ) {
        for item in &program.items {
            match item {
                Item::Function(func, span) => {
                    // All top-level functions are considered exports
                    functions.push(Self::function_to_info(
                        func,
                        module_path,
                        program.docs.comment_for_span(*span),
                    ));
                }
                Item::Export(export, span) => {
                    // Handle explicit exports
                    match &export.item {
                        shape_ast::ast::ExportItem::Function(func) => {
                            functions.push(Self::function_to_info(
                                func,
                                module_path,
                                program.docs.comment_for_span(*span),
                            ));
                        }
                        shape_ast::ast::ExportItem::BuiltinFunction(func) => {
                            intrinsic_functions.push(Self::builtin_function_to_info(
                                func,
                                module_path,
                                program.docs.comment_for_span(*span),
                            ));
                        }
                        shape_ast::ast::ExportItem::BuiltinType(type_decl) => {
                            intrinsic_types.push(Self::builtin_type_to_info(
                                type_decl,
                                program.docs.comment_for_span(*span),
                            ));
                        }
                        shape_ast::ast::ExportItem::TypeAlias(_) => {}
                        shape_ast::ast::ExportItem::Named(_) => {}
                        shape_ast::ast::ExportItem::Enum(_) => {}
                        shape_ast::ast::ExportItem::Struct(_) => {}
                        shape_ast::ast::ExportItem::Trait(_) => {}
                        shape_ast::ast::ExportItem::Annotation(_) => {}
                        shape_ast::ast::ExportItem::ForeignFunction(_) => {
                            // Foreign functions are not stdlib intrinsics
                        }
                    }
                }
                Item::BuiltinTypeDecl(type_decl, span) => {
                    intrinsic_types.push(Self::builtin_type_to_info(
                        type_decl,
                        program.docs.comment_for_span(*span),
                    ));
                }
                Item::BuiltinFunctionDecl(func_decl, span) => {
                    intrinsic_functions.push(Self::builtin_function_to_info(
                        func_decl,
                        module_path,
                        program.docs.comment_for_span(*span),
                    ));
                }
                _ => {}
            }
        }
    }

    /// Infer function category from module path (domain-agnostic)
    ///
    /// Uses directory structure to determine category:
    /// - core/math, core/statistics → Math
    /// - */indicators/*, */backtesting/*, */simulation/* → Simulation
    /// - */patterns/* → Utility
    /// - Default → Utility
    fn infer_category_from_path(module_path: &str) -> FunctionCategory {
        let path_lower = module_path.to_lowercase().replace("::", "/");

        // Check path components for categorization
        if path_lower.contains("/math") || path_lower.contains("/statistics") {
            FunctionCategory::Math
        } else if path_lower.contains("/indicators")
            || path_lower.contains("/backtesting")
            || path_lower.contains("/simulation")
        {
            FunctionCategory::Simulation
        } else if path_lower.contains("/patterns") {
            FunctionCategory::Utility
        } else {
            FunctionCategory::Utility
        }
    }

    fn function_to_info(
        func: &FunctionDef,
        module_path: &str,
        doc: Option<&DocComment>,
    ) -> FunctionInfo {
        let params: Vec<ParameterInfo> = func
            .params
            .iter()
            .map(|p| ParameterInfo {
                name: p.simple_name().unwrap_or("_").to_string(),
                param_type: p
                    .type_annotation
                    .as_ref()
                    .map(Self::format_type_annotation)
                    .unwrap_or_else(|| "any".to_string()),
                optional: p.default_value.is_some(),
                description: doc
                    .and_then(|comment| comment.param_doc(p.simple_name().unwrap_or("_")))
                    .unwrap_or_default()
                    .to_string(),
                constraints: None,
            })
            .collect();

        let return_type = func
            .return_type
            .as_ref()
            .map(Self::format_type_annotation)
            .unwrap_or_else(|| "any".to_string());

        let param_strs: Vec<String> = params
            .iter()
            .map(|p| {
                if p.optional {
                    format!("{}?: {}", p.name, p.param_type)
                } else {
                    format!("{}: {}", p.name, p.param_type)
                }
            })
            .collect();

        let signature = format!(
            "{}({}) -> {}",
            func.name,
            param_strs.join(", "),
            return_type
        );

        // Determine category based on path structure (domain-agnostic)
        let category = Self::infer_category_from_path(module_path);

        FunctionInfo {
            name: func.name.clone(),
            signature,
            description: doc.map(Self::doc_text).unwrap_or_default(),
            category,
            parameters: params,
            return_type,
            example: doc
                .and_then(|comment| comment.example_doc())
                .map(str::to_string),
            implemented: true,
            comptime_only: false,
        }
    }

    fn builtin_type_to_info(type_decl: &BuiltinTypeDecl, doc: Option<&DocComment>) -> TypeInfo {
        TypeInfo {
            name: type_decl.name.clone(),
            description: doc.map(Self::doc_text).unwrap_or_default(),
        }
    }

    fn builtin_function_to_info(
        func: &BuiltinFunctionDecl,
        module_path: &str,
        doc: Option<&DocComment>,
    ) -> FunctionInfo {
        let params: Vec<ParameterInfo> = func
            .params
            .iter()
            .map(|p| ParameterInfo {
                name: p.simple_name().unwrap_or("_").to_string(),
                param_type: p
                    .type_annotation
                    .as_ref()
                    .map(Self::format_type_annotation)
                    .unwrap_or_else(|| "any".to_string()),
                optional: p.default_value.is_some(),
                description: doc
                    .and_then(|comment| comment.param_doc(p.simple_name().unwrap_or("_")))
                    .unwrap_or_default()
                    .to_string(),
                constraints: None,
            })
            .collect();
        let return_type = Self::format_type_annotation(&func.return_type);
        let type_params_str = func
            .type_params
            .as_ref()
            .filter(|params| !params.is_empty())
            .map(|params| {
                format!(
                    "<{}>",
                    params
                        .iter()
                        .map(|p| p.name())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .unwrap_or_default();
        let signature = format!(
            "{}{}({}) -> {}",
            func.name,
            type_params_str,
            params
                .iter()
                .map(|p| format!("{}: {}", p.name, p.param_type))
                .collect::<Vec<_>>()
                .join(", "),
            return_type
        );
        FunctionInfo {
            name: func.name.clone(),
            signature,
            description: doc.map(Self::doc_text).unwrap_or_default(),
            category: Self::infer_category_from_path(module_path),
            parameters: params,
            return_type,
            example: doc
                .and_then(|comment| comment.example_doc())
                .map(str::to_string),
            implemented: true,
            comptime_only: crate::builtin_metadata::is_comptime_builtin_function(&func.name),
        }
    }

    fn doc_text(comment: &DocComment) -> String {
        if !comment.body.is_empty() {
            comment.body.clone()
        } else {
            comment.summary.clone()
        }
    }

    fn format_type_annotation(ty: &TypeAnnotation) -> String {
        match ty {
            TypeAnnotation::Basic(name) => name.clone(),
            TypeAnnotation::Reference(path) => path.to_string(),
            TypeAnnotation::Array(inner) => format!("{}[]", Self::format_type_annotation(inner)),
            TypeAnnotation::Tuple(items) => format!(
                "[{}]",
                items
                    .iter()
                    .map(Self::format_type_annotation)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            TypeAnnotation::Object(fields) => {
                let inner = fields
                    .iter()
                    .map(|f| {
                        if f.optional {
                            format!(
                                "{}?: {}",
                                f.name,
                                Self::format_type_annotation(&f.type_annotation)
                            )
                        } else {
                            format!(
                                "{}: {}",
                                f.name,
                                Self::format_type_annotation(&f.type_annotation)
                            )
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{{ {} }}", inner)
            }
            TypeAnnotation::Function { params, returns } => {
                let param_list = params
                    .iter()
                    .map(|p| {
                        let ty = Self::format_type_annotation(&p.type_annotation);
                        if let Some(name) = &p.name {
                            if p.optional {
                                format!("{}?: {}", name, ty)
                            } else {
                                format!("{}: {}", name, ty)
                            }
                        } else {
                            ty
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "({}) -> {}",
                    param_list,
                    Self::format_type_annotation(returns)
                )
            }
            TypeAnnotation::Union(types) => types
                .iter()
                .map(Self::format_type_annotation)
                .collect::<Vec<_>>()
                .join(" | "),
            TypeAnnotation::Intersection(types) => types
                .iter()
                .map(Self::format_type_annotation)
                .collect::<Vec<_>>()
                .join(" + "),
            TypeAnnotation::Generic { name, args } => format!(
                "{}<{}>",
                name,
                args.iter()
                    .map(Self::format_type_annotation)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            TypeAnnotation::Void => "void".to_string(),
            TypeAnnotation::Never => "never".to_string(),
            TypeAnnotation::Null => "null".to_string(),
            TypeAnnotation::Undefined => "undefined".to_string(),
            TypeAnnotation::Dyn(bounds) => format!("dyn {}", bounds.join(" + ")),
        }
    }
}

/// Get the default stdlib path
pub fn default_stdlib_path() -> PathBuf {
    // Explicit override for non-workspace environments (packaged installs, custom dev layouts).
    if let Ok(path) = std::env::var("SHAPE_STDLIB_PATH") {
        return PathBuf::from(path);
    }

    // Workspace builds use the canonical stdlib source of truth.
    let workspace_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../shape-core/stdlib");
    if workspace_path.is_dir() {
        return workspace_path;
    }

    // Published crates carry a vendored stdlib copy inside shape-runtime itself.
    let packaged_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("stdlib-src");
    if packaged_path.is_dir() {
        return packaged_path;
    }

    packaged_path
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_load_stdlib() {
        let stdlib_path = default_stdlib_path();
        if stdlib_path.exists() {
            let metadata = StdlibMetadata::load(&stdlib_path).unwrap();
            // Stdlib may or may not have functions depending on development state
            println!("Stdlib path: {:?}", stdlib_path);
            println!("Found {} stdlib functions", metadata.functions.len());
            for func in &metadata.functions {
                println!("  - {}: {}", func.name, func.signature);
            }
            println!("Found {} stdlib patterns", metadata.patterns.len());
            // Note: stdlib functions (like sma, ema) will be added as stdlib is developed
        } else {
            println!("Stdlib path does not exist: {:?}", stdlib_path);
        }
    }

    #[test]
    fn test_empty_stdlib() {
        let metadata = StdlibMetadata::empty();
        assert!(metadata.functions.is_empty());
        assert!(metadata.patterns.is_empty());
    }

    #[test]
    fn test_parse_all_stdlib_files() {
        let stdlib_path = default_stdlib_path();
        println!("Stdlib path: {:?}", stdlib_path);

        // Test each file individually
        let files = [
            "core/snapshot.shape",
            "core/math.shape",
            "finance/indicators/moving_averages.shape",
        ];

        for file in &files {
            let path = stdlib_path.join(file);
            if path.exists() {
                let content = std::fs::read_to_string(&path).unwrap();
                match parse_program(&content) {
                    Ok(program) => {
                        let func_count = program
                            .items
                            .iter()
                            .filter(|i| {
                                matches!(
                                    i,
                                    shape_ast::ast::Item::Function(_, _)
                                        | shape_ast::ast::Item::Export(_, _)
                                )
                            })
                            .count();
                        println!("{} parsed: {} items", file, func_count);
                    }
                    Err(e) => {
                        panic!("✗ {} FAILED to parse: {:?}", file, e);
                    }
                }
            } else {
                println!("{} not found", file);
            }
        }
    }

    #[test]
    fn test_intrinsic_declarations_loaded_from_std_core() {
        let stdlib_path = default_stdlib_path();
        if !stdlib_path.exists() {
            return;
        }

        let metadata = StdlibMetadata::load(&stdlib_path).unwrap();
        assert!(
            metadata
                .intrinsic_types
                .iter()
                .any(|t| t.name == "AnyError"),
            "expected AnyError intrinsic type from std::core declarations"
        );
        let abs = metadata
            .intrinsic_functions
            .iter()
            .find(|f| f.name == "abs")
            .expect("abs intrinsic declaration should exist");
        assert_eq!(abs.signature, "abs(value: number) -> number");
        assert!(
            abs.description.contains("absolute value"),
            "abs description should come from doc comments"
        );
    }

}