lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
//! Code introspection and development tools for the enhanced REPL.

#![allow(dead_code, missing_docs)]

use crate::{Lambdust, Result, eval::Value};
use std::collections::HashMap;
use std::fmt;

/// Commands for code introspection
#[derive(Debug, Clone, PartialEq)]
pub enum IntrospectionCommand {
    Describe(String),
    Apropos(String),
    Source(String),
    Documentation(String),
    Type(String),
    Signature(String),
    Examples(String),
    ListBindings,
    ListModules,
    Profile(String),
    Trace(String),
    Untrace(String),
}

/// Information about a symbol or function
#[derive(Debug, Clone)]
pub struct SymbolInfo {
    pub name: String,
    pub symbol_type: SymbolType,
    pub value: Option<Value>,
    pub documentation: Option<String>,
    pub signature: Option<String>,
    pub source_location: Option<SourceLocation>,
    pub module: Option<String>,
    pub examples: Vec<String>,
}

/// Types of symbols that can be inspected
#[derive(Debug, Clone, PartialEq)]
pub enum SymbolType {
    Function,
    Macro,
    Variable,
    Constant,
    SpecialForm,
    Module,
    Type,
    Unknown,
}

/// Source location information
#[derive(Debug, Clone)]
pub struct SourceLocation {
    pub file: String,
    pub line: usize,
    pub column: usize,
}

/// Profiling information for functions
#[derive(Debug, Clone)]
pub struct ProfileInfo {
    pub function_name: String,
    pub call_count: usize,
    pub total_time: std::time::Duration,
    pub average_time: std::time::Duration,
    pub min_time: std::time::Duration,
    pub max_time: std::time::Duration,
}

/// The main code inspector
pub struct CodeInspector {
    symbol_database: HashMap<String, SymbolInfo>,
    profile_data: HashMap<String, ProfileInfo>,
    traced_functions: std::collections::HashSet<String>,
    documentation_cache: HashMap<String, String>,
}

impl CodeInspector {
    pub fn new() -> Self {
        let mut inspector = Self {
            symbol_database: HashMap::new(),
            profile_data: HashMap::new(),
            traced_functions: std::collections::HashSet::new(),
            documentation_cache: HashMap::new(),
        };

        inspector.initialize_builtin_docs();
        inspector
    }

    fn initialize_builtin_docs(&mut self) {
        // Initialize documentation for built-in functions
        let builtin_docs = vec![
            ("+", "Addition function. Adds all given numbers together.", "(+ number1 number2 ...)"),
            ("-", "Subtraction function. Subtracts subsequent numbers from the first.", "(- number1 number2 ...)"),
            ("*", "Multiplication function. Multiplies all given numbers together.", "(* number1 number2 ...)"),
            ("/", "Division function. Divides the first number by subsequent numbers.", "(/ number1 number2 ...)"),
            ("=", "Numeric equality predicate. Returns #t if all numbers are equal.", "(= number1 number2 ...)"),
            ("<", "Less-than predicate. Returns #t if numbers are in ascending order.", "(< number1 number2 ...)"),
            (">", "Greater-than predicate. Returns #t if numbers are in descending order.", "(> number1 number2 ...)"),
            
            ("car", "Returns the first element of a pair.", "(car pair)"),
            ("cdr", "Returns the second element of a pair.", "(cdr pair)"),
            ("cons", "Constructs a new pair from two objects.", "(cons obj1 obj2)"),
            ("list", "Creates a list from the given arguments.", "(list obj ...)"),
            ("length", "Returns the length of a proper list.", "(length list)"),
            ("append", "Concatenates lists together.", "(append list ...)"),
            ("reverse", "Returns a new list with elements in reverse order.", "(reverse list)"),
            
            ("map", "Applies a procedure to elements of lists, returning a new list.", "(map proc list1 list2 ...)"),
            ("filter", "Returns a list of elements that satisfy the predicate.", "(filter pred list)"),
            ("fold-left", "Reduces a list from left to right using a binary procedure.", "(fold-left proc init list1 list2 ...)"),
            ("fold-right", "Reduces a list from right to left using a binary procedure.", "(fold-right proc init list1 list2 ...)"),
            
            ("null?", "Returns #t if the object is the empty list.", "(null? obj)"),
            ("pair?", "Returns #t if the object is a pair.", "(pair? obj)"),
            ("list?", "Returns #t if the object is a proper list.", "(list? obj)"),
            ("number?", "Returns #t if the object is a number.", "(number? obj)"),
            ("string?", "Returns #t if the object is a string.", "(string? obj)"),
            ("symbol?", "Returns #t if the object is a symbol.", "(symbol? obj)"),
            ("boolean?", "Returns #t if the object is a boolean.", "(boolean? obj)"),
            ("procedure?", "Returns #t if the object is a procedure.", "(procedure? obj)"),
            
            ("define", "Binds a name to a value or creates a function.", "(define name value) or (define (name params) body)"),
            ("lambda", "Creates an anonymous procedure.", "(lambda (params) body)"),
            ("if", "Conditional expression. Evaluates test and returns then or else clause.", "(if test then else)"),
            ("cond", "Multi-way conditional with multiple test-result clauses.", "(cond (test result) ... (else result))"),
            ("let", "Creates local bindings for variables.", "(let ((var val) ...) body)"),
            ("let*", "Creates sequential local bindings.", "(let* ((var val) ...) body)"),
            ("letrec", "Creates recursive local bindings.", "(letrec ((var val) ...) body)"),
            
            ("display", "Writes an object to the output port in human-readable form.", "(display obj [port])"),
            ("write", "Writes an object to the output port in machine-readable form.", "(write obj [port])"),
            ("newline", "Writes a newline character to the output port.", "(newline [port])"),
            ("read", "Reads an object from the input port.", "(read [port])"),
        ];

        for (name, doc, sig) in builtin_docs {
            let symbol_info = SymbolInfo {
                name: name.to_string(),
                symbol_type: if name.starts_with("define") || name == "lambda" || name == "if" || name == "cond" || name == "let" || name == "let*" || name == "letrec" {
                    SymbolType::SpecialForm
                } else {
                    SymbolType::Function
                },
                value: None,
                documentation: Some(doc.to_string()),
                signature: Some(sig.to_string()),
                source_location: None,
                module: Some("scheme".to_string()),
                examples: Vec::new(),
            };
            
            self.symbol_database.insert(name.to_string(), symbol_info);
            self.documentation_cache.insert(name.to_string(), doc.to_string());
        }
    }

    pub fn inspect(&self, lambdust: &mut Lambdust, item: &str) -> Result<()> {
        if let Some(symbol_info) = self.symbol_database.get(item) {
            self.print_symbol_info(symbol_info);
        } else {
            // Try to introspect from the runtime
            match self.introspect_from_runtime(lambdust, item) {
                Ok(Some(info)) => self.print_symbol_info(&info),
                Ok(None) => println!("No information found for: {item}"),
                Err(e) => println!("Error inspecting {item}: {e}"),
            }
        }
        Ok(())
    }

    fn print_symbol_info(&self, info: &SymbolInfo) {
        let name = &info.name;
        println!("🔍 {name}");
        println!("   Type: {:?}", info.symbol_type);
        
        if let Some(ref doc) = info.documentation {
            println!("   Documentation: {doc}");
        }
        
        if let Some(ref sig) = info.signature {
            println!("   Signature: {sig}");
        }
        
        if let Some(ref module) = info.module {
            println!("   Module: {module}");
        }
        
        if let Some(ref value) = info.value {
            println!("   Value: {value}");
        }
        
        if let Some(ref location) = info.source_location {
            let file = &location.file;
            let line = location.line;
            let column = location.column;
            println!("   Source: {file}:{line}:{column}");
        }
        
        if !info.examples.is_empty() {
            println!("   Examples:");
            for example in &info.examples {
                println!("     {example}");
            }
        }
    }

    fn introspect_from_runtime(&self, _lambdust: &mut Lambdust, item: &str) -> Result<Option<SymbolInfo>> {
        // TODO: Implement runtime introspection
        // This would involve querying the runtime environment for information about the symbol
        println!("Runtime introspection not yet implemented for: {item}");
        Ok(None)
    }

    pub fn apropos(&self, pattern: &str) -> Result<()> {
        let pattern_lower = pattern.to_lowercase();
        let mut matches = Vec::new();

        for (name, info) in &self.symbol_database {
            let name_lower = name.to_lowercase();
            let doc_matches = info.documentation
                .as_ref()
                .map(|doc| doc.to_lowercase().contains(&pattern_lower))
                .unwrap_or(false);

            if name_lower.contains(&pattern_lower) || doc_matches {
                matches.push((name, info));
            }
        }

        if matches.is_empty() {
            println!("No matches found for: {pattern}");
        } else {
            let count = matches.len(); println!("Matches for '{pattern}' ({count} found):");
            for (name, info) in matches {
                let sym_type = &info.symbol_type; println!("  {name} - {sym_type:?}");
                if let Some(ref doc) = info.documentation {
                    let truncated_doc = if doc.len() > 60 {
                        doc[..57].to_string() + "..."
                    } else {
                        doc.clone()
                    };
                    println!("    {truncated_doc}");
                }
            }
        }

        Ok(())
    }

    pub fn describe(&self, item: &str) -> Result<()> {
        if let Some(symbol_info) = self.symbol_database.get(item) {
            self.print_detailed_description(symbol_info);
        } else {
            println!("No description available for: {item}");
        }
        Ok(())
    }

    fn print_detailed_description(&self, info: &SymbolInfo) {
        let name = &info.name; println!("📖 Detailed Description: {name}");
        println!("{}", "=".repeat(50));
        
        println!("Type: {:?}", info.symbol_type);
        
        if let Some(ref sig) = info.signature {
            println!("\nSignature:");
            println!("  {sig}");
        }
        
        if let Some(ref doc) = info.documentation {
            println!("\nDescription:");
            println!("  {doc}");
        }
        
        if let Some(ref module) = info.module {
            println!("\nDefined in module: {module}");
        }
        
        if !info.examples.is_empty() {
            println!("\nExamples:");
            for (i, example) in info.examples.iter().enumerate() {
                let index = i + 1; println!("  {index}. {example}");
            }
        }
        
        // Show related functions
        self.show_related_functions(&info.name);
    }

    fn show_related_functions(&self, name: &str) {
        let mut related = Vec::new();
        
        // Find functions with similar names or in the same category
        for other_name in self.symbol_database.keys() {
            if other_name != name {
                // Simple heuristic: same prefix or contains same keywords
                if self.are_related(name, other_name) {
                    related.push(other_name);
                }
            }
        }
        
        if !related.is_empty() {
            println!("\nRelated functions:");
            for related_name in related.iter().take(5) {
                println!("  {related_name}");
            }
            if related.len() > 5 {
                let more_count = related.len() - 5; println!("  ... and {more_count} more");
            }
        }
    }

    fn are_related(&self, name1: &str, name2: &str) -> bool {
        // Simple heuristic for finding related functions
        if name1.len() < 2 || name2.len() < 2 {
            return false;
        }
        
        // Check for common prefixes
        let prefix_len = name1.chars().zip(name2.chars())
            .take_while(|(a, b)| a == b)
            .count();
        
        if prefix_len >= 3 {
            return true;
        }
        
        // Check for common suffixes (like predicates ending in ?)
        if (name1.ends_with('?') && name2.ends_with('?')) ||
           (name1.ends_with('!') && name2.ends_with('!')) {
            return true;
        }
        
        // Check for similar categories
        let categories = [
            ("string", vec!["string-", "char-"]),
            ("list", vec!["list", "car", "cdr", "cons", "append", "reverse"]),
            ("math", vec!["+", "-", "*", "/", "=", "<", ">", "<=", ">="]),
            ("io", vec!["read", "write", "display", "open", "close", "port"]),
        ];
        
        for (_, category_words) in &categories {
            let name1_in_category = category_words.iter().any(|word| name1.contains(word));
            let name2_in_category = category_words.iter().any(|word| name2.contains(word));
            
            if name1_in_category && name2_in_category {
                return true;
            }
        }
        
        false
    }

    pub fn list_bindings(&self, _lambdust: &Lambdust) -> Result<()> {
        println!("Available bindings:");
        
        let mut bindings: Vec<_> = self.symbol_database.keys().collect();
        bindings.sort();
        
        let mut current_category = None;
        
        for name in bindings {
            if let Some(info) = self.symbol_database.get(name) {
                let category = match info.symbol_type {
                    SymbolType::Function => "Functions",
                    SymbolType::Macro => "Macros",
                    SymbolType::SpecialForm => "Special Forms",
                    SymbolType::Variable => "Variables",
                    SymbolType::Constant => "Constants",
                    _ => "Other",
                };
                
                if current_category != Some(category) {
                    println!("\n{category}:");
                    current_category = Some(category);
                }
                
                print!("  {name}");
                if let Some(ref sig) = info.signature {
                    println!(" - {sig}");
                } else {
                    println!();
                }
            }
        }
        
        Ok(())
    }

    pub fn start_profiling(&mut self, function_name: &str) -> Result<()> {
        // TODO: Implement actual profiling integration with the runtime
        self.profile_data.insert(function_name.to_string(), ProfileInfo {
            function_name: function_name.to_string(),
            call_count: 0,
            total_time: std::time::Duration::from_secs(0),
            average_time: std::time::Duration::from_secs(0),
            min_time: std::time::Duration::from_secs(u64::MAX),
            max_time: std::time::Duration::from_secs(0),
        });
        
        println!("Started profiling: {function_name}");
        Ok(())
    }

    pub fn stop_profiling(&mut self, function_name: &str) -> Result<()> {
        if let Some(profile_info) = self.profile_data.remove(function_name) {
            self.print_profile_results(&profile_info);
        } else {
            println!("No profiling data found for: {function_name}");
        }
        Ok(())
    }

    fn print_profile_results(&self, profile: &ProfileInfo) {
        let fn_name = &profile.function_name; println!("📊 Profile Results for: {fn_name}");
        let call_count = profile.call_count; println!("   Calls: {call_count}");
        println!("   Total time: {:?}", profile.total_time);
        println!("   Average time: {:?}", profile.average_time);
        println!("   Min time: {:?}", profile.min_time);
        println!("   Max time: {:?}", profile.max_time);
    }

    pub fn start_tracing(&mut self, function_name: &str) -> Result<()> {
        self.traced_functions.insert(function_name.to_string());
        println!("Started tracing: {function_name}");
        Ok(())
    }

    pub fn stop_tracing(&mut self, function_name: &str) -> Result<()> {
        if self.traced_functions.remove(function_name) {
            println!("Stopped tracing: {function_name}");
        } else {
            println!("Function was not being traced: {function_name}");
        }
        Ok(())
    }

    pub fn list_traced_functions(&self) -> Result<()> {
        if self.traced_functions.is_empty() {
            println!("No functions are currently being traced");
        } else {
            println!("Currently traced functions:");
            for function in &self.traced_functions {
                println!("  {function}");
            }
        }
        Ok(())
    }

    pub fn add_symbol_info(&mut self, name: String, info: SymbolInfo) {
        self.symbol_database.insert(name, info);
    }

    pub fn update_symbol_info<F>(&mut self, name: &str, updater: F) 
    where
        F: FnOnce(&mut SymbolInfo),
    {
        if let Some(info) = self.symbol_database.get_mut(name) {
            updater(info);
        }
    }

    pub fn remove_symbol_info(&mut self, name: &str) -> Option<SymbolInfo> {
        self.symbol_database.remove(name)
    }

    pub fn get_symbol_info(&self, name: &str) -> Option<&SymbolInfo> {
        self.symbol_database.get(name)
    }

    pub fn search_by_type(&self, symbol_type: SymbolType) -> Vec<&SymbolInfo> {
        self.symbol_database
            .values()
            .filter(|info| info.symbol_type == symbol_type)
            .collect()
    }
}

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

impl fmt::Display for SymbolType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SymbolType::Function => write!(f, "Function"),
            SymbolType::Macro => write!(f, "Macro"),
            SymbolType::Variable => write!(f, "Variable"),
            SymbolType::Constant => write!(f, "Constant"),
            SymbolType::SpecialForm => write!(f, "Special Form"),
            SymbolType::Module => write!(f, "Module"),
            SymbolType::Type => write!(f, "Type"),
            SymbolType::Unknown => write!(f, "Unknown"),
        }
    }
}

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

    #[test]
    fn test_inspector_initialization() {
        let inspector = CodeInspector::new();
        
        // Should have some built-in documentation
        assert!(!inspector.symbol_database.is_empty());
        assert!(inspector.symbol_database.contains_key("+"));
        assert!(inspector.symbol_database.contains_key("car"));
        assert!(inspector.symbol_database.contains_key("define"));
    }

    #[test]
    fn test_symbol_info_creation() {
        let info = SymbolInfo {
            name: "test-function".to_string(),
            symbol_type: SymbolType::Function,
            value: None,
            documentation: Some("A test function".to_string()),
            signature: Some("(test-function x)".to_string()),
            source_location: None,
            module: Some("test".to_string()),
            examples: vec!["(test-function 42)".to_string()],
        };
        
        assert_eq!(info.name, "test-function");
        assert_eq!(info.symbol_type, SymbolType::Function);
        assert_eq!(info.documentation, Some("A test function".to_string()));
    }

    #[test]
    fn test_related_functions() {
        let inspector = CodeInspector::new();
        
        // Test related function detection
        assert!(inspector.are_related("string-length", "string-append"));
        assert!(inspector.are_related("list?", "pair?"));
        assert!(inspector.are_related("+", "-"));
        assert!(!inspector.are_related("car", "newline"));
    }
}