pasta_lua 0.2.4

Pasta Lua - Lua integration for Pasta DSL
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
//! Integration tests for Lua passthrough feature.
//!
//! Tests that .lua files placed in dictionary directories are detected,
//! copied to cache without transpilation, and included in scene_dic.lua.

use crate::common;

use common::copy_dir_recursive;
use pasta_lua::loader::{CacheManager, LoaderError, PastaLoader};
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

/// Helper: Copy scripts/scriptlibs from crate root to temp dir.
fn copy_runtime_deps(base_dir: &std::path::Path) {
    let crate_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));

    for dir_name in &["pasta_scripts", "scriptlibs"] {
        let src = crate_root.join(dir_name);
        let dst = base_dir.join(dir_name);
        if src.exists() {
            fs::create_dir_all(&dst).unwrap();
            copy_dir_recursive(&src, &dst).unwrap();
        }
    }
}

/// Helper: Create a temp dir with pasta.toml and runtime deps.
fn create_test_base() -> TempDir {
    let temp = TempDir::new().unwrap();
    let base_dir = temp.path();

    fs::write(base_dir.join("pasta.toml"), "[loader]\ndebug_mode = true\n").unwrap();

    copy_runtime_deps(base_dir);
    temp
}

/// Helper to extract string from Lua value.
#[allow(dead_code)]
fn value_as_str(value: &mlua::Value) -> Option<String> {
    value
        .as_string()
        .and_then(|s| s.to_str().ok())
        .map(|s| s.to_string())
}

// ============================================================================
// Task 1: init.* file rejection
// ============================================================================

#[test]
fn test_init_lua_rejected() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with init.lua
    fs::create_dir_all(base_dir.join("dic/test")).unwrap();
    fs::write(base_dir.join("dic/test/init.lua"), "-- init lua").unwrap();

    let result = PastaLoader::load(base_dir);
    assert!(result.is_err());
    match &result {
        Err(LoaderError::InvalidFileName(path)) => {
            assert!(
                path.to_string_lossy().contains("init.lua"),
                "Expected path containing init.lua, got: {}",
                path.display()
            );
        }
        Err(other) => panic!("Expected InvalidFileName error, got: {}", other),
        Ok(_) => panic!("Expected InvalidFileName error, got Ok"),
    }
}

#[test]
fn test_init_pasta_rejected() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with init.pasta
    fs::create_dir_all(base_dir.join("dic/test")).unwrap();
    fs::write(base_dir.join("dic/test/init.pasta"), "# init pasta").unwrap();

    let result = PastaLoader::load(base_dir);
    assert!(result.is_err());
    match &result {
        Err(LoaderError::InvalidFileName(path)) => {
            assert!(
                path.to_string_lossy().contains("init.pasta"),
                "Expected path containing init.pasta, got: {}",
                path.display()
            );
        }
        Err(other) => panic!("Expected InvalidFileName error, got: {}", other),
        Ok(_) => panic!("Expected InvalidFileName error, got Ok"),
    }
}

// ============================================================================
// Task 2: .lua file detection
// ============================================================================

#[test]
fn test_lua_file_detected_and_cached() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with a .lua file
    fs::create_dir_all(base_dir.join("dic/utils")).unwrap();
    fs::write(
        base_dir.join("dic/utils/helper.lua"),
        "-- helper lua\nreturn { helper = true }\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify cache file was created
    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/utils/helper.lua");
    assert!(
        cache_path.exists(),
        "Cache file should exist at: {}",
        cache_path.display()
    );

    // Verify cache content is the original lua (not transpiled)
    let cached = fs::read_to_string(&cache_path).unwrap();
    assert!(cached.contains("-- helper lua"));
    assert!(cached.contains("return { helper = true }"));
}

#[test]
fn test_lua_file_in_scene_dic() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with a .lua file
    fs::create_dir_all(base_dir.join("dic/utils")).unwrap();
    fs::write(
        base_dir.join("dic/utils/helper.lua"),
        "-- helper lua\nreturn {}\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify scene_dic.lua contains require for the .lua module
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    assert!(
        scene_dic.contains("require(\"pasta.scene.utils.helper\")"),
        "scene_dic.lua should contain require for lua module, got:\n{}",
        scene_dic
    );
}

#[test]
fn test_profile_lua_excluded() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with a valid .lua file
    fs::create_dir_all(base_dir.join("dic/test")).unwrap();
    fs::write(base_dir.join("dic/test/valid.lua"), "return {}\n").unwrap();

    // Create profile .lua file (should NOT be picked up)
    fs::create_dir_all(base_dir.join("profile/pasta/some")).unwrap();
    fs::write(
        base_dir.join("profile/pasta/some/internal.lua"),
        "return {}\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify only dic/test/valid.lua is in scene_dic
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    assert!(scene_dic.contains("pasta.scene.test.valid"));
    assert!(!scene_dic.contains("internal"));
}

// ============================================================================
// Task 3: Module name conflict detection
// ============================================================================

#[test]
fn test_pasta_takes_priority_over_lua_on_conflict() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create dic structure with both .pasta and .lua having same module name
    fs::create_dir_all(base_dir.join("dic/test")).unwrap();
    fs::write(
        base_dir.join("dic/test/conflict.pasta"),
        "*コンフリクト\n  ゴースト:「パスタ優先」\n",
    )
    .unwrap();
    fs::write(
        base_dir.join("dic/test/conflict.lua"),
        "-- this should be ignored\nreturn {}\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify scene_dic.lua contains the module only once
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    let count = scene_dic.matches("pasta.scene.test.conflict").count();
    assert_eq!(
        count, 1,
        "Module should appear exactly once in scene_dic.lua, found: {}",
        count
    );

    // Verify cached file is from .pasta (transpiled), not raw .lua
    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/test/conflict.lua");
    let cached = fs::read_to_string(&cache_path).unwrap();
    assert!(
        !cached.contains("-- this should be ignored"),
        "Cache should contain transpiled .pasta code, not raw .lua"
    );
}

#[test]
fn test_hyphen_normalized_module_name_conflict() {
    // Module names normalize '-' to '_', so "my-mod.pasta" and "my_mod.lua"
    // collide on the same module key -> .pasta wins, .lua is ignored.
    let temp = create_test_base();
    let base_dir = temp.path();

    fs::create_dir_all(base_dir.join("dic/test")).unwrap();
    fs::write(
        base_dir.join("dic/test/my-mod.pasta"),
        "*ハイフン\n  ゴースト:「パスタ優先」\n",
    )
    .unwrap();
    fs::write(
        base_dir.join("dic/test/my_mod.lua"),
        "-- lua side should be ignored\nreturn {}\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Normalized module appears exactly once in scene_dic.lua
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    let count = scene_dic.matches("pasta.scene.test.my_mod").count();
    assert_eq!(
        count, 1,
        "Normalized module should appear exactly once, found {} in:\n{}",
        count, scene_dic
    );

    // Cached module body comes from the transpiled .pasta, not the raw .lua
    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/test/my_mod.lua");
    assert!(
        cache_path.exists(),
        "Cache file should exist at: {}",
        cache_path.display()
    );
    let cached = fs::read_to_string(&cache_path).unwrap();
    assert!(
        !cached.contains("-- lua side should be ignored"),
        "Cache must contain transpiled .pasta code, not the conflicting raw .lua"
    );
}

#[test]
fn test_no_conflict_different_dirs() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create .pasta in one dir and .lua in another (no conflict)
    fs::create_dir_all(base_dir.join("dic/a")).unwrap();
    fs::create_dir_all(base_dir.join("dic/b")).unwrap();
    fs::write(
        base_dir.join("dic/a/helper.pasta"),
        "*ヘルパーA\n  ゴースト:「A」\n",
    )
    .unwrap();
    fs::write(
        base_dir.join("dic/b/helper.lua"),
        "-- helper B\nreturn {}\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Both should appear in scene_dic.lua
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    assert!(
        scene_dic.contains("pasta.scene.a.helper"),
        "Should contain a.helper"
    );
    assert!(
        scene_dic.contains("pasta.scene.b.helper"),
        "Should contain b.helper"
    );
}

// ============================================================================
// Task 4: .lua passthrough processing
// ============================================================================

#[test]
fn test_lua_not_transpiled() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create a .lua file with content that would fail parsing as Pasta
    fs::create_dir_all(base_dir.join("dic/raw")).unwrap();
    fs::write(
        base_dir.join("dic/raw/custom.lua"),
        r#"
-- Pure Lua code that is NOT valid Pasta DSL
local M = {}

function M.greet(name)
    return "Hello, " .. name .. "!"
end

return M
"#,
    )
    .unwrap();

    // Should succeed (no parse/transpile attempt on .lua)
    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify cache content matches source exactly
    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/raw/custom.lua");
    let cached = fs::read_to_string(&cache_path).unwrap();
    assert!(cached.contains("function M.greet(name)"));
    assert!(cached.contains("return M"));
}

#[test]
fn test_pasta_and_lua_mixed() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create both .pasta and .lua (different names, no conflict)
    fs::create_dir_all(base_dir.join("dic/mix")).unwrap();
    fs::write(
        base_dir.join("dic/mix/scene.pasta"),
        "*ミックス\n  ゴースト:「混在テスト」\n",
    )
    .unwrap();
    fs::write(
        base_dir.join("dic/mix/util.lua"),
        "-- utility\nreturn { util = true }\n",
    )
    .unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Both should be in scene_dic
    let scene_dic_path = base_dir.join("profile/pasta/cache/lua/pasta/scene_dic.lua");
    let scene_dic = fs::read_to_string(&scene_dic_path).unwrap();
    assert!(scene_dic.contains("pasta.scene.mix.scene"));
    assert!(scene_dic.contains("pasta.scene.mix.util"));
}

// ============================================================================
// Task 4.3: Incremental update
// ============================================================================

#[test]
fn test_lua_incremental_update() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create .lua file
    fs::create_dir_all(base_dir.join("dic/inc")).unwrap();
    fs::write(
        base_dir.join("dic/inc/module.lua"),
        "return { version = 1 }\n",
    )
    .unwrap();

    // First load
    let _runtime = PastaLoader::load(base_dir).unwrap();

    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/inc/module.lua");
    let cached_v1 = fs::read_to_string(&cache_path).unwrap();
    assert!(cached_v1.contains("version = 1"));

    // Modify source
    std::thread::sleep(std::time::Duration::from_millis(50));
    fs::write(
        base_dir.join("dic/inc/module.lua"),
        "return { version = 2 }\n",
    )
    .unwrap();

    // Second load
    let _runtime2 = PastaLoader::load(base_dir).unwrap();

    let cached_v2 = fs::read_to_string(&cache_path).unwrap();
    assert!(
        cached_v2.contains("version = 2"),
        "Cache should be updated after source change"
    );
}

// ============================================================================
// Task 5: Orphan cache detection
// ============================================================================

#[test]
fn test_lua_orphan_cache_detected() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create .lua file and load
    fs::create_dir_all(base_dir.join("dic/orphan")).unwrap();
    fs::write(base_dir.join("dic/orphan/target.lua"), "return {}\n").unwrap();

    let _runtime = PastaLoader::load(base_dir).unwrap();

    // Verify cache exists
    let cache_path = base_dir.join("profile/pasta/cache/lua/pasta/scene/orphan/target.lua");
    assert!(cache_path.exists(), "Cache should exist after first load");

    // Delete source .lua
    fs::remove_file(base_dir.join("dic/orphan/target.lua")).unwrap();

    // Second load - orphan should be detected (but not deleted)
    let _runtime2 = PastaLoader::load(base_dir).unwrap();

    // Cache file should still exist (orphan detection only, no auto-delete)
    assert!(
        cache_path.exists(),
        "Orphan cache should still exist (not auto-deleted)"
    );
}

// ============================================================================
// Task 5: Orphan detection via CacheManager directly
// ============================================================================

#[test]
fn test_cache_manager_orphan_with_lua_source() {
    let temp = TempDir::new().unwrap();
    let base_dir = temp.path();
    let manager = CacheManager::new(base_dir.to_path_buf(), "profile/pasta/cache/lua");
    manager.prepare_cache_dir().unwrap();

    // Create cache files
    let scene_dir = base_dir.join("profile/pasta/cache/lua/pasta/scene");
    fs::create_dir_all(scene_dir.join("sub")).unwrap();
    fs::write(scene_dir.join("sub/active_pasta.lua"), "-- from pasta").unwrap();
    fs::write(scene_dir.join("sub/active_lua.lua"), "-- from lua").unwrap();
    fs::write(scene_dir.join("sub/orphan.lua"), "-- orphan").unwrap();

    // Source paths include both .pasta and .lua
    let source_paths = vec![
        base_dir.join("dic/sub/active_pasta.pasta"),
        base_dir.join("dic/sub/active_lua.lua"),
    ];

    let orphans = manager.find_orphaned_caches(&source_paths);

    assert_eq!(orphans.len(), 1, "Should find exactly 1 orphan");
    assert!(
        orphans[0].to_string_lossy().contains("orphan"),
        "Orphan should be the unmatched cache file"
    );
}

// ============================================================================
// load-error-logging: Task 6.2 - process_incremental error propagation tests
// ============================================================================

/// Verify that a broken .pasta file causes PastaLoader::load to return Err.
#[test]
fn test_partial_transpile_error_on_broken_pasta() {
    let temp = create_test_base();
    let base_dir = temp.path();

    // Create a valid .pasta file
    fs::create_dir_all(base_dir.join("dic/ok")).unwrap();
    fs::write(
        base_dir.join("dic/ok/good.pasta"),
        "*テスト\n  ゴースト:「こんにちは」\n",
    )
    .unwrap();

    // Create a broken .pasta file (invalid syntax)
    fs::create_dir_all(base_dir.join("dic/bad")).unwrap();
    fs::write(
        base_dir.join("dic/bad/broken.pasta"),
        "*壊れた\n  {{{{invalid syntax}}}}\n",
    )
    .unwrap();

    let result = PastaLoader::load(base_dir);
    assert!(result.is_err(), "Should fail with partial transpile error");
    let err = match result {
        Err(e) => e,
        Ok(_) => panic!("Expected error but got Ok"),
    };
    let msg = format!("{}", err);
    assert!(
        msg.contains("Partial transpilation failure"),
        "Error should mention partial transpilation failure: {}",
        msg
    );
    assert!(
        msg.contains("broken.pasta"),
        "Error should contain failed filename: {}",
        msg
    );
}

/// Verify that PartialTranspileError Display includes file paths.
#[test]
fn test_partial_transpile_error_display_includes_paths() {
    use pasta_lua::loader::TranspileFailure;
    use std::path::PathBuf;

    let err = LoaderError::partial_transpile(
        3,
        2,
        vec![
            TranspileFailure {
                source_path: PathBuf::from("dic/talk.pasta"),
                error: "Parse error".to_string(),
            },
            TranspileFailure {
                source_path: PathBuf::from("dic/click.pasta"),
                error: "Transpile error".to_string(),
            },
        ],
    );

    let msg = format!("{}", err);
    assert!(
        msg.contains("3 succeeded"),
        "Should show success count: {}",
        msg
    );
    assert!(
        msg.contains("2 failed"),
        "Should show failure count: {}",
        msg
    );
    assert!(
        msg.contains("dic/talk.pasta"),
        "Should contain first failure path: {}",
        msg
    );
    assert!(
        msg.contains("dic/click.pasta"),
        "Should contain second failure path: {}",
        msg
    );
}