dist_agent_lang 1.0.21

Agentic programming with library and CLI support for Off/On-chain network integration
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
//! CT1: Compiler pipeline skeleton tests — driver, service selection, stub backend.

use dist_agent_lang::compile::{
    run_compile, select_services_for_target, set_compiler_available_override, CompileError,
};
use dist_agent_lang::lexer::tokens::{get_target_constraints, CompilationTarget, TargetConstraint};
use dist_agent_lang::manifest::{resolve_dependencies, write_lockfile};
use dist_agent_lang::parser::ast::{CompilationTargetInfo, Program, ServiceStatement, Statement};

/// Build a minimal program with one service that has compilation_target set (no parser validation).
fn program_with_native_service() -> Program {
    let service = ServiceStatement {
        name: "MyApp".to_string(),
        attributes: vec![dist_agent_lang::parser::ast::Attribute {
            name: "@native".to_string(),
            parameters: vec![],
            target: dist_agent_lang::parser::ast::AttributeTarget::Module,
        }],
        fields: vec![],
        methods: vec![],
        events: vec![],
        exported: false,
        compilation_target: Some(CompilationTargetInfo {
            target: CompilationTarget::Native,
            constraints: TargetConstraint::new(CompilationTarget::Native),
            validation_errors: vec![],
        }),
    };
    Program {
        statements: vec![Statement::Service(service)],
        statement_spans: vec![None],
    }
}

#[test]
fn test_select_services_for_target_native() {
    let program = program_with_native_service();
    let services = select_services_for_target(&program, &CompilationTarget::Native);
    assert_eq!(services.len(), 1);
    assert_eq!(services[0].name, "MyApp");
}

#[test]
fn test_select_services_for_target_empty_when_no_match() {
    let program = program_with_native_service();
    let services = select_services_for_target(&program, &CompilationTarget::Blockchain);
    assert!(services.is_empty());
}

#[test]
fn test_select_services_for_target_multiple() {
    // Build program with two blockchain services manually to avoid parser attribute validation
    let mk_service = |name: &str| ServiceStatement {
        name: name.to_string(),
        attributes: vec![],
        fields: vec![],
        methods: vec![],
        events: vec![],
        exported: false,
        compilation_target: Some(CompilationTargetInfo {
            target: CompilationTarget::Blockchain,
            constraints: TargetConstraint::new(CompilationTarget::Blockchain),
            validation_errors: vec![],
        }),
    };
    let program = Program {
        statements: vec![
            Statement::Service(mk_service("Token")),
            Statement::Service(mk_service("Vault")),
        ],
        statement_spans: vec![None, None],
    };
    let services = select_services_for_target(&program, &CompilationTarget::Blockchain);
    assert_eq!(services.len(), 2);
    let names: Vec<&str> = services.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Token"));
    assert!(names.contains(&"Vault"));
}

/// CT0: Runtime validate_compile_target rejects service missing required attributes.
#[test]
fn test_ct0_runtime_rejects_missing_required_attributes() {
    let constraints = get_target_constraints();
    let bc = constraints
        .get(&CompilationTarget::Blockchain)
        .cloned()
        .unwrap();
    let service = ServiceStatement {
        name: "Bad".to_string(),
        attributes: vec![], // missing @secure, @trust
        fields: vec![],
        methods: vec![],
        events: vec![],
        exported: false,
        compilation_target: Some(CompilationTargetInfo {
            target: CompilationTarget::Blockchain,
            constraints: bc,
            validation_errors: vec![],
        }),
    };
    let program = Program {
        statements: vec![Statement::Service(service)],
        statement_spans: vec![None],
    };
    let mut runtime = dist_agent_lang::Runtime::new();
    let result = runtime.execute_program(program, None);
    assert!(result.is_err());
    let err = result.unwrap_err();
    let msg = format!("{}", err);
    assert!(
        msg.contains("missing required attribute") || msg.contains("Missing required"),
        "expected compile-target validation error, got: {}",
        msg
    );
}

/// Build with imports: entry imports a sibling file; resolution runs and merged program compiles.
/// (Service with @compile_target lives in entry; lib is import-only so we don't hit parser @native validation in deps.)
#[test]
fn test_run_compile_with_imports_resolves() {
    let dir = tempfile::tempdir().unwrap();
    let main_path = dir.path().join("main.dal");
    let lib_path = dir.path().join("lib.dal");
    std::fs::write(&lib_path, "fn helper() { 0 }\n").unwrap();
    let main_source = r#"
import "./lib.dal" as m;
@native
service App @compile_target("native") {
    fn run() { 0 }
}
"#;
    std::fs::write(&main_path, main_source).unwrap();
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        main_path.clone(),
        CompilationTarget::Native,
        out.clone(),
        main_source,
    );

    assert!(
        result.is_ok(),
        "build with imports should resolve and compile: {:?}",
        result.err()
    );
    let artifacts = result.unwrap();
    assert_eq!(artifacts.service_names, vec!["App"]);
}

/// Catches: replace package_entry_path -> None/Some(Default). Dep with only lib.dal (no main.dal) must be found.
#[test]
fn test_run_compile_resolves_package_with_only_lib_dal() {
    let dir = tempfile::tempdir().unwrap();
    let app_dir = dir.path().join("app");
    let mylib_dir = dir.path().join("mylib");
    std::fs::create_dir_all(&app_dir).unwrap();
    std::fs::create_dir_all(&mylib_dir).unwrap();
    std::fs::write(mylib_dir.join("lib.dal"), "fn foo() { 42 }").unwrap();
    std::fs::write(
        app_dir.join("dal.toml"),
        r#"[package]
name = "app"
version = "0.1.0"

[dependencies]
mylib = { path = "../mylib" }
"#,
    )
    .unwrap();
    let (resolved, version_meta) = resolve_dependencies(&app_dir.join("dal.toml")).unwrap();
    write_lockfile(&app_dir.join("dal.toml"), &resolved, &version_meta).unwrap();
    let main_source = r#"
import "mylib" as m;
@native
service App @compile_target("native") {
    fn run() { m::foo() }
}
"#;
    std::fs::write(app_dir.join("main.dal"), main_source).unwrap();
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        app_dir.join("main.dal"),
        CompilationTarget::Native,
        out.clone(),
        main_source,
    );

    assert!(
        result.is_ok(),
        "compile with package (only lib.dal) should resolve and compile: {:?}",
        result.err()
    );
    let artifacts = result.unwrap();
    assert_eq!(artifacts.service_names, vec!["App"]);
}

/// CT2: Blockchain backend — when solc is present, produces .sol, .bin, .abi and stub: false.
#[test]
fn test_run_compile_blockchain_backend() {
    let source = r#"
@secure
@trust("hybrid")
@chain("ethereum")
service Token @compile_target("blockchain") {
    fn transfer(to: string, amount: int) { }
}
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Blockchain,
        out.clone(),
        source,
    );

    match result {
        Ok(artifacts) => {
            assert_eq!(artifacts.target, "blockchain");
            assert_eq!(artifacts.service_names, vec!["Token"]);
            assert!(
                !artifacts.stub,
                "blockchain backend should produce real artifacts when solc is available"
            );
            let has_bin = artifacts
                .artifact_paths
                .iter()
                .any(|p| p.extension().map(|e| e == "bin").unwrap_or(false));
            let has_abi = artifacts
                .artifact_paths
                .iter()
                .any(|p| p.extension().map(|e| e == "abi").unwrap_or(false));
            assert!(
                has_bin && has_abi,
                "expected .bin and .abi artifacts, got {:?}",
                artifacts.artifact_paths
            );
            let manifest = out.join("compile-manifest.json");
            assert!(manifest.exists());
            let content = std::fs::read_to_string(manifest).unwrap();
            assert!(content.contains("\"stub\":false"));
        }
        Err(CompileError::CompilerNotFound { .. }) => {
            // solc not installed — backend correctly reports it
        }
        Err(CompileError::Parse(_)) => {
            // Parser/attribute validation may fail in some configurations
        }
        Err(e) => panic!("unexpected error: {}", e),
    }
}

#[test]
fn test_hybrid_blockchain_autosplits_auth_namespace_for_http_artifacts() {
    let source = r#"
@secure
@trust("hybrid")
@chain("ethereum")
service Token @compile_target("blockchain") {
    fn transfer(to: string, amount: int) {
        let session = auth::session("user1", ["user"]);
        chain::call(1, "0x1234", "transfer", {"to": to, "amount": amount});
    }
}
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(entry, CompilationTarget::Blockchain, out, source);
    match result {
        Ok(artifacts) => {
            let has_http_split = artifacts
                .artifact_paths
                .iter()
                .any(|p| p.extension().map(|e| e == "json").unwrap_or(false));
            assert!(
                has_http_split,
                "expected HTTP split artifact for auth-routed block, got {:?}",
                artifacts.artifact_paths
            );
        }
        Err(CompileError::CompilerNotFound { .. }) => {
            // solc missing is acceptable here; critical assertion is no Parse rejection.
        }
        Err(CompileError::Parse(msg)) => panic!(
            "hybrid auth block should be auto-split, not parse-failed: {}",
            msg
        ),
        Err(e) => panic!("unexpected error: {}", e),
    }
}

#[test]
fn test_hybrid_blockchain_autosplits_cloudadmin_namespace_for_http_artifacts() {
    let source = r#"
@secure
@trust("hybrid")
@chain("ethereum")
service Governance @compile_target("blockchain") {
    fn rebalance() {
        cloudadmin::authorize("admin", "rebalance", "vault");
        chain::call(1, "0x1234", "rebalance", {});
    }
}
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(entry, CompilationTarget::Blockchain, out, source);
    match result {
        Ok(artifacts) => {
            let has_http_split = artifacts
                .artifact_paths
                .iter()
                .any(|p| p.extension().map(|e| e == "json").unwrap_or(false));
            assert!(
                has_http_split,
                "expected HTTP split artifact for cloudadmin-routed block, got {:?}",
                artifacts.artifact_paths
            );
        }
        Err(CompileError::CompilerNotFound { .. }) => {
            // solc missing is acceptable here; critical assertion is no Parse rejection.
        }
        Err(CompileError::Parse(msg)) => panic!(
            "hybrid cloudadmin block should be auto-split, not parse-failed: {}",
            msg
        ),
        Err(e) => panic!("unexpected error: {}", e),
    }
}

/// CT3: WASM backend — when wasm32 target is present, produces .wasm and stub: false.
#[test]
fn test_run_compile_wasm_backend() {
    let source = r#"
@web
service WebApp @compile_target("wasm") {
    fn handle() { }
}
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::WebAssembly,
        out.clone(),
        source,
    );

    match result {
        Ok(artifacts) => {
            assert_eq!(artifacts.target, "wasm");
            assert_eq!(artifacts.service_names, vec!["WebApp"]);
            assert!(
                !artifacts.stub,
                "wasm backend should produce real artifacts when wasm32 target is available"
            );
            let has_wasm = artifacts
                .artifact_paths
                .iter()
                .any(|p| p.extension().map(|e| e == "wasm").unwrap_or(false));
            assert!(
                has_wasm,
                "expected .wasm artifact, got {:?}",
                artifacts.artifact_paths
            );
            let manifest = out.join("compile-manifest.json");
            assert!(manifest.exists());
            let content = std::fs::read_to_string(manifest).unwrap();
            assert!(content.contains("\"stub\":false"));
        }
        Err(CompileError::CompilerNotFound { .. }) => {
            // wasm32 target not installed
        }
        Err(CompileError::Parse(_)) => {}
        Err(CompileError::Backend(_)) => {
            // cargo build failed (e.g. missing target)
        }
        Err(e) => panic!("unexpected error: {}", e),
    }
}

/// CT4: Native backend — when cargo is present, produces .rlib and stub: false.
#[test]
fn test_run_compile_native_backend() {
    let source = r#"
@native
service App @compile_target("native") { fn run() { 42 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Native,
        out.clone(),
        source,
    );

    match result {
        Ok(artifacts) => {
            assert_eq!(artifacts.target, "native");
            assert_eq!(artifacts.service_names, vec!["App"]);
            assert!(
                !artifacts.stub,
                "native backend should report real codegen when cargo is available"
            );
            if let Some(p) = artifacts
                .artifact_paths
                .iter()
                .find(|p| p.extension().map(|e| e == "rlib").unwrap_or(false))
            {
                assert!(p.exists(), "rlib path should exist: {}", p.display());
            }
            let manifest = out.join("compile-manifest.json");
            assert!(manifest.exists());
            let content = std::fs::read_to_string(manifest).unwrap();
            assert!(content.contains("\"stub\":false"));
        }
        Err(CompileError::CompilerNotFound { .. }) => {}
        Err(CompileError::Parse(_)) => {}
        Err(CompileError::Backend(_)) => {}
        Err(e) => panic!("unexpected error: {}", e),
    }
}

/// Edge/IoT backend rejects compile when no service is marked for edge (empty selection).
/// Catches: deleting `if services.is_empty()` or weakening the error in edge.rs.
#[test]
fn test_run_compile_edge_errors_when_no_edge_services() {
    let source = r#"
@native
service App @compile_target("native") { fn run() { 42 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(entry.clone(), CompilationTarget::Edge, out.clone(), source);

    match &result {
        Err(CompileError::Backend(msg)) => {
            assert!(
                msg.contains("edge") || msg.contains("iot"),
                "expected message about edge/iot services; got: {}",
                msg
            );
        }
        Ok(a) => panic!(
            "expected Backend error when no edge services, got Ok: {:?}",
            a
        ),
        Err(e) => panic!("expected CompileError::Backend, got: {}", e),
    }
}

/// StubBackend (Mobile/Edge) calls check_compiler_available("rustc"). When rustc is present,
/// compile must succeed. This catches mutants that replace check_compiler_available with false.
#[test]
fn test_run_compile_stub_backend_succeeds_when_rustc_available() {
    let source = r#"
@mobile
service StubApp @compile_target("mobile") { fn run() { 0 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Mobile,
        out.clone(),
        source,
    );

    match &result {
        Ok(artifacts) => {
            assert!(artifacts.stub, "StubBackend should produce stub: true");
            assert_eq!(artifacts.target, "mobile");
            assert_eq!(artifacts.service_names, vec!["StubApp"]);
        }
        Err(CompileError::CompilerNotFound { target, .. }) => {
            // rustc not in PATH (e.g. minimal env); skip asserting success
            assert_eq!(target.as_str(), "mobile");
        }
        Err(CompileError::Parse(e)) => panic!("parse error (fix source if grammar changed): {}", e),
        Err(e) => panic!("unexpected error: {}", e),
    }
}

/// With compiler-availability override set to false, compile returns CompilerNotFound.
/// Catches mutants that replace check_*_available with true (would incorrectly succeed).
#[test]
fn test_run_compile_returns_compiler_not_found_when_override_false() {
    struct Guard;
    impl Drop for Guard {
        fn drop(&mut self) {
            set_compiler_available_override(None);
        }
    }
    let _guard = Guard;
    set_compiler_available_override(Some(false));

    let source = r#"
@mobile
service StubApp @compile_target("mobile") { fn run() { 0 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Mobile,
        out.clone(),
        source,
    );

    match &result {
        Err(CompileError::CompilerNotFound { target, hint }) => {
            assert_eq!(target.as_str(), "mobile");
            assert!(!hint.is_empty());
        }
        Ok(_) => panic!("expected CompilerNotFound when override is false"),
        Err(e) => panic!("expected CompilerNotFound, got: {}", e),
    }
}

/// With override set to true, StubBackend succeeds even if rustc is not in PATH (tests override path).
#[test]
fn test_run_compile_stub_backend_succeeds_when_override_true() {
    struct Guard;
    impl Drop for Guard {
        fn drop(&mut self) {
            set_compiler_available_override(None);
        }
    }
    let _guard = Guard;
    set_compiler_available_override(Some(true));

    let source = r#"
@mobile
service StubApp @compile_target("mobile") { fn run() { 0 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Mobile,
        out.clone(),
        source,
    );

    assert!(
        result.is_ok(),
        "with override true, StubBackend should succeed: {:?}",
        result.err()
    );
    let artifacts = result.unwrap();
    assert!(artifacts.stub);
    assert_eq!(artifacts.service_names, vec!["StubApp"]);
}

/// Native backend respects override: when false, returns CompilerNotFound (no real cargo check).
#[test]
fn test_run_compile_native_returns_compiler_not_found_when_override_false() {
    struct Guard;
    impl Drop for Guard {
        fn drop(&mut self) {
            set_compiler_available_override(None);
        }
    }
    let _guard = Guard;
    set_compiler_available_override(Some(false));

    let source = r#"
@native
service App @compile_target("native") { fn run() { 42 } }
"#;
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("main.dal");
    let out = dir.path().join("out");
    std::fs::create_dir_all(&out).unwrap();

    let result = run_compile(
        entry.clone(),
        CompilationTarget::Native,
        out.clone(),
        source,
    );

    match &result {
        Err(CompileError::CompilerNotFound { target, .. }) => assert_eq!(target.as_str(), "native"),
        Ok(_) => panic!("expected CompilerNotFound when override is false"),
        Err(e) => panic!("expected CompilerNotFound, got: {}", e),
    }
}