ruchy 4.1.2

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
#![allow(missing_docs)]
// PARSER-060: Module Resolution MVP Tests
//
// Scope: File resolution, loading, symbol extraction, imports
// Out of scope: Circular deps, namespaces, visibility, wildcards
//
// Test structure follows CLAUDE.md naming convention:
// test_parser_060_<section>_<feature>_<scenario>

use std::fs;
use std::rc::Rc;
use tempfile::TempDir;

// === RED PHASE: These tests MUST fail until implementation is complete ===

// -------------------------------------------------------------------
// Section 1: File Resolution Tests (use foo::bar → ./foo/bar.ruchy)
// -------------------------------------------------------------------

#[test]
fn test_parser_060_01_file_resolution_simple_module() {
    // Test: use utils → ./utils.ruchy
    let temp_dir = TempDir::new().unwrap();
    let utils_path = temp_dir.path().join("utils.ruchy");
    fs::write(&utils_path, "fun helper() { 42 }").unwrap();

    let module_path = "utils";
    let resolved = resolve_module_path(module_path, temp_dir.path()).unwrap();

    assert_eq!(resolved, utils_path);
}

#[test]
fn test_parser_060_01_file_resolution_nested_module() {
    // Test: use foo::bar → ./foo/bar.ruchy
    let temp_dir = TempDir::new().unwrap();
    let foo_dir = temp_dir.path().join("foo");
    fs::create_dir(&foo_dir).unwrap();
    let bar_path = foo_dir.join("bar.ruchy");
    fs::write(&bar_path, "fun baz() { 100 }").unwrap();

    let module_path = "foo::bar";
    let resolved = resolve_module_path(module_path, temp_dir.path()).unwrap();

    assert_eq!(resolved, bar_path);
}

#[test]
fn test_parser_060_01_file_resolution_deeply_nested() {
    // Test: use a::b::c → ./a/b/c.ruchy
    let temp_dir = TempDir::new().unwrap();
    let a_dir = temp_dir.path().join("a");
    let b_dir = a_dir.join("b");
    fs::create_dir_all(&b_dir).unwrap();
    let c_path = b_dir.join("c.ruchy");
    fs::write(&c_path, "fun deep() { 999 }").unwrap();

    let module_path = "a::b::c";
    let resolved = resolve_module_path(module_path, temp_dir.path()).unwrap();

    assert_eq!(resolved, c_path);
}

#[test]
fn test_parser_060_01_file_resolution_missing_file() {
    // Test: use nonexistent → Error
    let temp_dir = TempDir::new().unwrap();

    let module_path = "nonexistent";
    let result =
        std::panic::catch_unwind(|| resolve_module_path(module_path, temp_dir.path()).unwrap());

    assert!(
        result.is_err(),
        "Should fail when module file doesn't exist"
    );
}

#[test]
fn test_parser_060_01_file_resolution_dot_notation() {
    // Test: Python-style import foo.bar → ./foo/bar.ruchy
    let temp_dir = TempDir::new().unwrap();
    let foo_dir = temp_dir.path().join("foo");
    fs::create_dir(&foo_dir).unwrap();
    let bar_path = foo_dir.join("bar.ruchy");
    fs::write(&bar_path, "fun test() { 1 }").unwrap();

    let module_path = "foo.bar"; // Dot notation
    let resolved = resolve_module_path_dot_notation(module_path, temp_dir.path()).unwrap();

    assert_eq!(resolved, bar_path);
}

// -------------------------------------------------------------------
// Section 2: File Loading & Parsing Tests
// -------------------------------------------------------------------

#[test]
fn test_parser_060_02_loading_simple_module() {
    // Test: Load and parse a simple module file
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("math.ruchy");
    fs::write(&module_path, "fun add(x, y) { x + y }").unwrap();

    let loaded_module = load_module(&module_path).unwrap();

    assert!(loaded_module.is_loaded());
    assert_eq!(loaded_module.path(), &module_path);
}

#[test]
fn test_parser_060_02_loading_module_with_multiple_functions() {
    // Test: Load module with multiple function definitions
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("utils.ruchy");
    fs::write(
        &module_path,
        r"
        fun add(x, y) { x + y }
        fun sub(x, y) { x - y }
        fun mul(x, y) { x * y }
    ",
    )
    .unwrap();

    let loaded_module = load_module(&module_path).unwrap();
    let symbols = loaded_module.symbols();

    assert_eq!(symbols.len(), 3);
    assert!(symbols.contains_key("add"));
    assert!(symbols.contains_key("sub"));
    assert!(symbols.contains_key("mul"));
}

#[test]
fn test_parser_060_02_loading_module_parse_error() {
    // Test: Handle syntax errors gracefully
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("broken.ruchy");
    fs::write(&module_path, "fun broken( { incomplete syntax").unwrap();

    let result = load_module(&module_path);

    assert!(result.is_err(), "Should return error for invalid syntax");
}

// -------------------------------------------------------------------
// Section 3: Symbol Extraction Tests (functions, structs, consts)
// -------------------------------------------------------------------

#[test]
fn test_parser_060_03_extract_function_symbols() {
    // Test: Extract function definitions from AST
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("funcs.ruchy");
    fs::write(
        &module_path,
        r"
        fun public_func() { 1 }
        fun helper_func(x) { x * 2 }
    ",
    )
    .unwrap();

    let loaded_module = load_module(&module_path).unwrap();
    let functions = extract_functions(&loaded_module);

    assert_eq!(functions.len(), 2);
    assert!(functions.iter().any(|f| f.name == "public_func"));
    assert!(functions.iter().any(|f| f.name == "helper_func"));
}

#[test]
fn test_parser_060_03_extract_struct_symbols() {
    // Test: Extract struct definitions from AST
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("structs.ruchy");
    fs::write(
        &module_path,
        r"
        struct Point { x: i32, y: i32 }
        struct Circle { center: Point, radius: f64 }
    ",
    )
    .unwrap();

    let loaded_module = load_module(&module_path).unwrap();
    let structs = extract_structs(&loaded_module);

    assert_eq!(structs.len(), 2);
    assert!(structs.iter().any(|s| s.name == "Point"));
    assert!(structs.iter().any(|s| s.name == "Circle"));
}

#[test]
fn test_parser_060_03_extract_const_symbols() {
    // Test: Extract constant definitions from AST
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("consts.ruchy");
    fs::write(
        &module_path,
        r"
        const PI = 3.14159
        const MAX_SIZE = 1000
    ",
    )
    .unwrap();

    let loaded_module = load_module(&module_path).unwrap();
    let consts = extract_consts(&loaded_module);

    assert_eq!(consts.len(), 2);
    assert!(consts.iter().any(|c| c.name == "PI"));
    assert!(consts.iter().any(|c| c.name == "MAX_SIZE"));
}

#[test]
fn test_parser_060_03_extract_mixed_symbols() {
    // Test: Extract all symbol types from a single module
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("mixed.ruchy");
    fs::write(
        &module_path,
        r#"
        const VERSION = "1.0"
        struct Config { debug: bool }
        fun init() { Config { debug: true } }
    "#,
    )
    .unwrap();

    let loaded_module = load_module(&module_path).unwrap();
    let all_symbols = extract_all_symbols(&loaded_module);

    assert_eq!(all_symbols.functions.len(), 1);
    assert_eq!(all_symbols.structs.len(), 1);
    assert_eq!(all_symbols.consts.len(), 1);
}

// -------------------------------------------------------------------
// Section 4: Symbol Import Tests (inject into environment)
// -------------------------------------------------------------------

#[test]
fn test_parser_060_04_import_simple_function() {
    // Test: use utils::helper imports single function
    let temp_dir = TempDir::new().unwrap();
    let utils_path = temp_dir.path().join("utils.ruchy");
    fs::write(&utils_path, "fun helper() { 42 }").unwrap();

    let code = "use utils::helper\nhelper()";
    let result = execute_with_imports(code, temp_dir.path()).unwrap();

    assert_eq!(result, Value::Integer(42));
}

#[test]
#[ignore = "RED phase: multi-function imports not yet implemented - PARSER-060"]
fn test_parser_060_04_import_multiple_functions() {
    // Test: use utils::{add, sub} imports multiple functions
    let temp_dir = TempDir::new().unwrap();
    let utils_path = temp_dir.path().join("utils.ruchy");
    fs::write(
        &utils_path,
        r"
        fun add(x, y) { x + y }
        fun sub(x, y) { x - y }
    ",
    )
    .unwrap();

    let code = "use utils::{add, sub}\nadd(10, 5) + sub(10, 5)";
    let result = execute_with_imports(code, temp_dir.path()).unwrap();

    assert_eq!(result, Value::Integer(20)); // 15 + 5
}

#[test]
fn test_parser_060_04_import_struct_constructor() {
    // Test: use types::Point imports struct constructor
    let temp_dir = TempDir::new().unwrap();
    let types_path = temp_dir.path().join("types.ruchy");
    fs::write(&types_path, "struct Point { x: i32, y: i32 }").unwrap();

    let code = "use types::Point\nPoint { x: 10, y: 20 }.x";
    let result = execute_with_imports(code, temp_dir.path()).unwrap();

    assert_eq!(result, Value::Integer(10));
}

#[test]
fn test_parser_060_04_import_const_value() {
    // Test: use config::VERSION imports constant
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join("config.ruchy");
    fs::write(&config_path, "const VERSION = \"1.0\"").unwrap();

    let code = "use config::VERSION\nVERSION";
    let result = execute_with_imports(code, temp_dir.path()).unwrap();

    assert_eq!(result, Value::from_string("1.0".to_string()));
}

#[test]
fn test_parser_060_04_import_from_nested_module() {
    // Test: use foo::bar::baz imports from nested module
    let temp_dir = TempDir::new().unwrap();
    let foo_dir = temp_dir.path().join("foo");
    fs::create_dir(&foo_dir).unwrap();
    let bar_path = foo_dir.join("bar.ruchy");
    fs::write(&bar_path, "fun baz() { 100 }").unwrap();

    let code = "use foo::bar::baz\nbaz()";
    let result = execute_with_imports(code, temp_dir.path()).unwrap();

    assert_eq!(result, Value::Integer(100));
}

#[test]
fn test_parser_060_04_import_nonexistent_symbol() {
    // Test: use utils::missing fails with clear error
    let temp_dir = TempDir::new().unwrap();
    let utils_path = temp_dir.path().join("utils.ruchy");
    fs::write(&utils_path, "fun helper() { 1 }").unwrap();

    let code = "use utils::missing\nmissing()";
    let result = execute_with_imports(code, temp_dir.path());

    assert!(
        result.is_err(),
        "Should fail when importing nonexistent symbol"
    );
    let err_msg = format!("{:?}", result.unwrap_err());
    assert!(err_msg.contains("not found") || err_msg.contains("missing"));
}

// -------------------------------------------------------------------
// Section 5: Module Cache Tests (avoid re-parsing)
// -------------------------------------------------------------------

#[test]
fn test_parser_060_05_cache_module_on_first_load() {
    // Test: First load caches the parsed module
    let temp_dir = TempDir::new().unwrap();
    let module_path = temp_dir.path().join("cached.ruchy");
    fs::write(&module_path, "fun test() { 1 }").unwrap();

    let cache = ModuleCache::new();
    let module1 = cache.load(&module_path).unwrap();
    let module2 = cache.load(&module_path).unwrap();

    assert!(
        Rc::ptr_eq(&module1, &module2),
        "Should return same cached instance"
    );
}

#[test]
fn test_parser_060_05_cache_multiple_modules() {
    // Test: Cache handles multiple different modules
    let temp_dir = TempDir::new().unwrap();

    let mod1_path = temp_dir.path().join("mod1.ruchy");
    fs::write(&mod1_path, "fun test1() { 1 }").unwrap();

    let mod2_path = temp_dir.path().join("mod2.ruchy");
    fs::write(&mod2_path, "fun test2() { 2 }").unwrap();

    let cache = ModuleCache::new();
    let module1 = cache.load(&mod1_path).unwrap();
    let module2 = cache.load(&mod2_path).unwrap();

    assert!(
        !Rc::ptr_eq(&module1, &module2),
        "Different modules should be different instances"
    );
}

// -------------------------------------------------------------------
// Helper functions (will be implemented in GREEN phase)
// -------------------------------------------------------------------

// -------------------------------------------------------------------
// Import actual implementations from module_loader
// -------------------------------------------------------------------

use ruchy::frontend::ast::{Expr, ExprKind};
use ruchy::frontend::parser::Parser;
use ruchy::runtime::module_loader::{
    extract_all_symbols, extract_consts, extract_functions, extract_structs, load_module,
    resolve_module_path, resolve_module_path_dot_notation, ModuleCache,
};
use ruchy::runtime::{Interpreter, Value};

fn execute_with_imports(code: &str, base: &std::path::Path) -> Result<Value, String> {
    // Parse the code
    let ast = Parser::new(code)
        .parse()
        .map_err(|e| format!("Parse error: {e:?}"))?;

    // Create module cache and interpreter
    let cache = ModuleCache::new();
    let mut interpreter = Interpreter::new();

    // Extract import statements and process them
    let exprs: Vec<&Expr> = match &ast.kind {
        ExprKind::Block(exprs) => exprs.iter().collect(),
        _ => vec![&ast],
    };

    // Separate import statements from other code
    let mut non_import_exprs: Vec<Expr> = Vec::new();

    for expr in &exprs {
        if let ExprKind::Import { module, items } = &expr.kind {
            // Split module path into module file and symbols
            // For "utils::helper" with no items → module="utils", symbols=["helper"]
            // For "utils" with items=["add", "sub"] → module="utils", symbols=["add", "sub"]
            let (module_file, symbol_names): (String, Vec<String>) = if let Some(item_names) = items
            {
                // Explicit items: use module as-is, items as symbols
                (module.clone(), item_names.clone())
            } else {
                // No items: last segment is the symbol, rest is module path
                let parts: Vec<&str> = module.split("::").collect();
                if parts.len() == 1 {
                    // Single name with no items - import the whole module
                    (module.clone(), vec![])
                } else {
                    // Split into module and symbol
                    let module_part = parts[..parts.len() - 1].join("::");
                    let symbol_part = parts[parts.len() - 1].to_string();
                    (module_part, vec![symbol_part])
                }
            };

            // Resolve module path and load module
            let module_path = resolve_module_path(&module_file, base).map_err(|e| e.to_string())?;
            let loaded_module = cache.load(&module_path).map_err(|e| e.to_string())?;

            // Evaluate the entire module to register ALL symbols in the interpreter
            // This avoids issues with evaluating individual function expressions
            interpreter
                .eval_expr(loaded_module.ast())
                .map_err(|e| format!("Failed to load module: {e}"))?;

            // Verify requested symbols exist
            if !symbol_names.is_empty() {
                for item_name in &symbol_names {
                    loaded_module.get_symbol(item_name).ok_or_else(|| {
                        format!("Symbol '{item_name}' not found in module '{module_file}'")
                    })?;
                }
            }
        } else {
            // Not an import - keep for execution
            non_import_exprs.push((*expr).clone());
        }
    }

    // Execute the code (excluding import statements)
    if non_import_exprs.is_empty() {
        // No code to execute - return Nil
        Ok(Value::Nil)
    } else if non_import_exprs.len() == 1 {
        // Single expression - evaluate directly
        interpreter
            .eval_expr(&non_import_exprs[0])
            .map_err(|e| format!("Execution error: {e}"))
    } else {
        // Multiple expressions - create a block using ast's metadata
        let block_expr = Expr {
            kind: ExprKind::Block(non_import_exprs),
            span: ast.span,
            attributes: Vec::new(),
            leading_comments: Vec::new(),
            trailing_comment: None,
        };
        interpreter
            .eval_expr(&block_expr)
            .map_err(|e| format!("Execution error: {e}"))
    }
}