assura 0.4.0

Contract-first AI-native language. Write what it should do. AI proves it does.
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
use super::*;

// `assura diff` -- structural diff between contract files
// ---------------------------------------------------------------------------

pub(crate) fn extract_decl_summary(
    sf: &SourceFile,
) -> std::collections::BTreeMap<String, Vec<String>> {
    let mut result = std::collections::BTreeMap::new();
    for spanned_decl in &sf.decls {
        let decl = &spanned_decl.node;
        let name = decl
            .name()
            .map(|s| s.to_string())
            .unwrap_or_else(|| "<anon>".to_string());
        let clauses: Vec<String> = decl
            .clauses()
            .iter()
            .map(|cl| format!("{:?}: {}", cl.kind, format_clause_body(cl)))
            .collect();
        result.insert(name, clauses);
    }
    result
}

/// Human-readable clause body (Assura surface syntax), not Debug.
pub(crate) fn format_clause_body(clause: &assura_parser::ast::Clause) -> String {
    assura_parser::display::expr_to_string(&clause.body)
}

fn validate_diff_format(format: &str, as_json: bool) {
    crate::validate_human_json_format(format, "diff", as_json);
}

/// Structural diff result. When `emit` is false, JSON is not printed (used so
/// `--verify --json` can emit a single combined document).
pub(crate) fn run_diff(
    old_path: &str,
    new_path: &str,
    format: &str,
    as_json: bool,
) -> (bool, serde_json::Value) {
    validate_diff_format(format, as_json);
    let is_json = format == "json";
    let old_src = match fs::read_to_string(old_path) {
        Ok(s) => s,
        Err(e) => {
            if is_json {
                let report = serde_json::json!({
                    "ok": false,
                    "error": "cannot_read",
                    "path": old_path,
                    "message": format!("Error reading {old_path}: {e}"),
                });
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
            } else {
                eprintln!("Error reading {old_path}: {e}");
            }
            process::exit(1);
        }
    };
    let new_src = match fs::read_to_string(new_path) {
        Ok(s) => s,
        Err(e) => {
            if is_json {
                let report = serde_json::json!({
                    "ok": false,
                    "error": "cannot_read",
                    "path": new_path,
                    "message": format!("Error reading {new_path}: {e}"),
                });
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
            } else {
                eprintln!("Error reading {new_path}: {e}");
            }
            process::exit(1);
        }
    };

    let (old_ast, old_errs) = assura_parser::parse(&old_src);
    let (new_ast, new_errs) = assura_parser::parse(&new_src);

    if !old_errs.is_empty() && !is_json {
        eprintln!("Warning: {old_path} has {} parse error(s)", old_errs.len());
    }
    if !new_errs.is_empty() && !is_json {
        eprintln!("Warning: {new_path} has {} parse error(s)", new_errs.len());
    }

    let old_decls = old_ast
        .as_ref()
        .map(extract_decl_summary)
        .unwrap_or_default();
    let new_decls = new_ast
        .as_ref()
        .map(extract_decl_summary)
        .unwrap_or_default();

    let mut changes = Vec::new();
    let mut has_diff = false;

    for (name, old_clauses) in &old_decls {
        if !new_decls.contains_key(name) {
            has_diff = true;
            changes.push(DiffEntry {
                name: name.clone(),
                kind: "removed".to_string(),
                added_clauses: Vec::new(),
                removed_clauses: old_clauses.clone(),
                unchanged_clauses: Vec::new(),
            });
        }
    }

    for (name, new_clauses) in &new_decls {
        match old_decls.get(name) {
            None => {
                has_diff = true;
                changes.push(DiffEntry {
                    name: name.clone(),
                    kind: "added".to_string(),
                    added_clauses: new_clauses.clone(),
                    removed_clauses: Vec::new(),
                    unchanged_clauses: Vec::new(),
                });
            }
            Some(old_clauses) => {
                let added: Vec<String> = new_clauses
                    .iter()
                    .filter(|c| !old_clauses.contains(c))
                    .cloned()
                    .collect();
                let removed: Vec<String> = old_clauses
                    .iter()
                    .filter(|c| !new_clauses.contains(c))
                    .cloned()
                    .collect();
                let unchanged: Vec<String> = new_clauses
                    .iter()
                    .filter(|c| old_clauses.contains(c))
                    .cloned()
                    .collect();
                if !added.is_empty() || !removed.is_empty() {
                    has_diff = true;
                    changes.push(DiffEntry {
                        name: name.clone(),
                        kind: "modified".to_string(),
                        added_clauses: added,
                        removed_clauses: removed,
                        unchanged_clauses: unchanged,
                    });
                }
            }
        }
    }

    let json = serde_json::json!({
        "identical": !has_diff,
        "changes": changes.iter().map(|c| serde_json::json!({
            "name": c.name,
            "kind": c.kind,
            "added_clauses": c.added_clauses,
            "removed_clauses": c.removed_clauses,
            "unchanged_clauses": c.unchanged_clauses,
        })).collect::<Vec<_>>(),
    });

    if format == "json" {
        // Caller may suppress print when combining with --verify.
        // Default path prints here only when used alone; cli.rs decides.
    } else {
        if !has_diff {
            println!("No structural differences.");
        }
        for entry in &changes {
            match entry.kind.as_str() {
                "added" => println!("{}:  (new)", entry.name),
                "removed" => println!("{}:  (removed)", entry.name),
                _ => println!("{}:", entry.name),
            }
            for c in &entry.removed_clauses {
                println!("  - {c}");
            }
            for c in &entry.added_clauses {
                println!("  + {c}");
            }
            for c in &entry.unchanged_clauses {
                println!("    {c}");
            }
            println!();
        }
    }

    (has_diff, json)
}

/// Structured evolution result for JSON (no Debug dumps).
fn evolution_check_json(r: &assura_smt::VerificationResult) -> serde_json::Value {
    r.to_json_value()
}

fn evolution_is_ok(r: &assura_smt::VerificationResult) -> bool {
    matches!(r, assura_smt::VerificationResult::Verified { .. })
}

/// Run SMT-based evolution verification on two contract files.
///
/// Parses both files and checks backward compatibility:
/// - Precondition weakening: old_requires => new_requires
/// - Postcondition strengthening: new_ensures => old_ensures
///
/// When `structural` is `Some`, JSON mode emits a **single** document that
/// includes both the structural diff and evolution results (avoids two JSON
/// objects on stdout that break `json.loads`).
pub(crate) fn run_diff_verify(
    old_path: &str,
    new_path: &str,
    format: &str,
    structural: Option<serde_json::Value>,
    as_json: bool,
) {
    validate_diff_format(format, as_json);
    let is_json = format == "json";
    let old_src = match fs::read_to_string(old_path) {
        Ok(s) => s,
        Err(e) => {
            if is_json {
                let report = serde_json::json!({
                    "ok": false,
                    "error": "cannot_read",
                    "path": old_path,
                    "message": format!("Error reading {old_path}: {e}"),
                });
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
            } else {
                eprintln!("Error reading {old_path}: {e}");
            }
            process::exit(1);
        }
    };
    let new_src = match fs::read_to_string(new_path) {
        Ok(s) => s,
        Err(e) => {
            if is_json {
                let report = serde_json::json!({
                    "ok": false,
                    "error": "cannot_read",
                    "path": new_path,
                    "message": format!("Error reading {new_path}: {e}"),
                });
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
            } else {
                eprintln!("Error reading {new_path}: {e}");
            }
            process::exit(1);
        }
    };

    let (old_ast, old_errs) = assura_parser::parse(&old_src);
    let (new_ast, new_errs) = assura_parser::parse(&new_src);

    if !old_errs.is_empty() || old_ast.is_none() {
        eprintln!("Cannot verify evolution: {old_path} has parse errors");
        process::exit(1);
    }
    if !new_errs.is_empty() || new_ast.is_none() {
        eprintln!("Cannot verify evolution: {new_path} has parse errors");
        process::exit(1);
    }

    let old_ast = old_ast.unwrap();
    let new_ast = new_ast.unwrap();

    let results = assura_smt::verify_file_evolution(&old_ast, &new_ast);

    if results.is_empty() {
        if format == "json" {
            let mut doc = serde_json::json!({
                "evolution": [],
                "compatible": true,
            });
            if let Some(s) = structural {
                doc["identical"] = s
                    .get("identical")
                    .cloned()
                    .unwrap_or(serde_json::json!(true));
                doc["changes"] = s
                    .get("changes")
                    .cloned()
                    .unwrap_or_else(|| serde_json::json!([]));
            }
            println!("{}", serde_json::to_string_pretty(&doc).unwrap());
        } else {
            println!("No matching contracts to verify evolution.");
        }
        return;
    }

    let mut all_pass = true;
    if format == "json" {
        let json_results: Vec<serde_json::Value> = results
            .iter()
            .map(|r| {
                let pre_ok = evolution_is_ok(&r.precondition_weakening);
                let post_ok = evolution_is_ok(&r.postcondition_strengthening);
                if !pre_ok || !post_ok {
                    all_pass = false;
                }
                serde_json::json!({
                    "contract": r.contract_name,
                    "precondition_weakening": evolution_check_json(&r.precondition_weakening),
                    "postcondition_strengthening": evolution_check_json(&r.postcondition_strengthening),
                    "compatible": pre_ok && post_ok,
                })
            })
            .collect();
        let mut doc = serde_json::json!({
            "evolution": json_results,
            "compatible": all_pass,
        });
        if let Some(s) = structural {
            doc["identical"] = s
                .get("identical")
                .cloned()
                .unwrap_or(serde_json::json!(false));
            doc["changes"] = s
                .get("changes")
                .cloned()
                .unwrap_or_else(|| serde_json::json!([]));
        }
        println!("{}", serde_json::to_string_pretty(&doc).unwrap());
    } else {
        println!("\nContract evolution verification:");
        for r in &results {
            println!("  {}:", r.contract_name);
            let pre_status = match &r.precondition_weakening {
                assura_smt::VerificationResult::Verified { .. } => "verified",
                assura_smt::VerificationResult::Counterexample { .. } => {
                    all_pass = false;
                    "FAILED (preconditions strengthened)"
                }
                assura_smt::VerificationResult::Unknown { reason, .. } => {
                    eprintln!("    warning: {reason}");
                    "unknown"
                }
                assura_smt::VerificationResult::Timeout { .. } => {
                    all_pass = false;
                    "timeout"
                }
            };
            println!("    precondition weakening  ... {pre_status}");

            let post_status = match &r.postcondition_strengthening {
                assura_smt::VerificationResult::Verified { .. } => "verified",
                assura_smt::VerificationResult::Counterexample { .. } => {
                    all_pass = false;
                    "FAILED (postconditions weakened)"
                }
                assura_smt::VerificationResult::Unknown { reason, .. } => {
                    eprintln!("    warning: {reason}");
                    "unknown"
                }
                assura_smt::VerificationResult::Timeout { .. } => {
                    all_pass = false;
                    "timeout"
                }
            };
            println!("    postcondition strength. ... {post_status}");
        }
    }

    if !all_pass {
        process::exit(1);
    }
}

pub(crate) struct DiffEntry {
    name: String,
    kind: String,
    added_clauses: Vec<String>,
    removed_clauses: Vec<String>,
    unchanged_clauses: Vec<String>,
}

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

    #[test]
    fn format_clause_body_is_surface_syntax_not_debug() {
        let src = r#"
contract C {
  input(x: Int)
  ensures { x >= 0 }
}
"#;
        let (ast, errs) = assura_parser::parse(src);
        assert!(errs.is_empty(), "{errs:?}");
        let sf = ast.expect("ast");
        let summary = extract_decl_summary(&sf);
        let clauses = summary.get("C").expect("contract C");
        let ensures = clauses
            .iter()
            .find(|c| c.starts_with("Ensures:"))
            .expect("ensures clause");
        // Must not dump Debug(Spanned { node: ... })
        assert!(
            !ensures.contains("Spanned"),
            "diff body must not use Debug format: {ensures}"
        );
        assert!(
            ensures.contains("x") && ensures.contains("0"),
            "expected surface expression, got {ensures}"
        );
        // Prefer readable comparison operator
        assert!(
            ensures.contains(">=") || ensures.contains(""),
            "expected comparison in body: {ensures}"
        );
    }
}

// ===========================================================================
// Integration tests: full pipeline from source text through all passes
// ===========================================================================