// ---- Bloc moteur Dynamics-08 (std seul) — a recopier tel quel en tete des cellules 10 a 35 ----
use std::collections::{BTreeMap, BTreeSet, HashMap};
const T: i64 = 5;
const R: i64 = 3;
const P: i64 = 1;
const S: i64 = 0;
fn gain(mien: &str, adverse: &str) -> i64 {
if mien == "C" { if adverse == "C" { R } else { S } } else if adverse == "C" { T } else { P }
}
const K_DEFAUT: usize = 3;
const REGLES: [(&[&str], &[&str]); 9] = [
(&["uncond_coop"], &["intent_coop"]),
(&["uncond_defect"], &["intent_defect"]),
(&["self_cond_coop"], &["implies_own_coop"]),
(&["intent_coop"], &["coops_against_any", "coops_with_db"]),
(&["intent_defect"], &["defects_against_any", "defects_with_db"]),
(&["needs_proof_of_coop"], &["defects_with_db"]),
(&["needs_proof_of_defect"], &["defects_with_db"]),
(&["self_cond_coop"], &["defects_with_db"]),
(&["prudent"], &["defects_with_db"]),
];
// Textes publies, ordre d'insertion du dict source (valeurs exactes des litteraux Python).
const SOURCES: [(&str, &str); 7] = [
("CooperateBot", r#"def CooperateBot(opp_source, k):
return "C"
# BYLAW: uncond_coop
bylaws_json = '{"atoms": ["uncond_coop"]}'
"#),
("DefectBot", r#"def DefectBot(opp_source, k):
return "D"
# BYLAW: uncond_defect
bylaws_json = '{"atoms": ["uncond_defect"]}'
"#),
("CooperateBotOpake", r#"def CooperateBotOpake(opp_source, k):
_code = 67
return chr(_code)
# BYLAW:
bylaws_json = '{"atoms": []}'
"#),
("CUPOD", r#"def CUPOD(opp_source, k):
if proof_search(k, opp_source, "defects_against_any"):
return "D"
return "C"
# BYLAW: needs_proof_of_defect
bylaws_json = '{"atoms": ["needs_proof_of_defect"]}'
"#),
("DUPOC", r#"def DUPOC(opp_source, k):
if proof_search(k, opp_source, "coops_against_any"):
return "C"
return "D"
# BYLAW: needs_proof_of_coop
bylaws_json = '{"atoms": ["needs_proof_of_coop"]}'
"#),
("CIMCIC", r#"def CIMCIC(opp_source, k):
if proof_search(k, opp_source, "implies_own_coop"):
return "C"
return "D"
# BYLAW: self_cond_coop
bylaws_json = '{"atoms": ["self_cond_coop"]}'
"#),
("PrudentBot_borne", r#"def PrudentBot_borne(opp_source, k):
if not proof_search(k, opp_source, "coops_against_any"):
return "D"
if not proof_search(k, opp_source, "defects_with_db"):
return "D"
return "C"
# BYLAW: prudent
# BYLAW: needs_proof_of_coop
bylaws_json = '{"atoms": ["prudent", "needs_proof_of_coop"]}'
"#),
];
const ORDRE: [&str; 7] = ["CooperateBot", "DefectBot", "CooperateBotOpake",
"CUPOD", "DUPOC", "CIMCIC", "PrudentBot_borne"];
fn source(nom: &str) -> &'static str {
SOURCES.iter().find(|(n, _)| *n == nom).map(|(_, s)| *s).expect("programme publie")
}
// Equivalent ligne a ligne de re.compile(r"^#\s*BYLAW:\s*([a-z_]+)\s*$", re.MULTILINE).
fn atome_bylaw(ligne: &str) -> Option<String> {
let reste = ligne.strip_prefix('#')?.trim_start().strip_prefix("BYLAW:")?.trim();
if !reste.is_empty() && reste.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
Some(reste.to_string())
} else {
None
}
}
fn parse_certificat_a(source: &str) -> BTreeSet<String> {
source.lines().filter_map(atome_bylaw).collect()
}
fn cloture_a(graine: &BTreeSet<String>, k: usize) -> BTreeSet<String> {
let mut faits = graine.clone();
for _ in 0..k {
let mut grossi = faits.clone();
for (premisse, conclusions) in REGLES.iter() {
if premisse.iter().all(|p| faits.contains(*p)) {
grossi.extend(conclusions.iter().map(|c| c.to_string()));
}
}
if grossi == faits {
break;
}
faits = grossi;
}
faits
}
fn proof_search(k: usize, opp_source: &str, but: &str) -> bool {
cloture_a(&parse_certificat_a(opp_source), k).contains(but)
}
// Interprete du sous-langage des textes publies (remplace exec : la decision vient du texte).
#[derive(Debug)]
enum Instr {
Retour(String), // return "X"
Affecte(String, i64), // _code = 67
RetourChr(String), // return chr(_code) | return chr(67)
Si { negation: bool, but: String, retour: String }, // if [not] proof_search(k, opp_source, "but"): return "X"
}
#[derive(Debug)]
struct Programme { nom: String, corps: Vec<Instr> }
fn chaine_python(s: &str) -> Option<String> {
let s = s.trim();
let q = s.chars().next()?;
if (q == '"' || q == '\'') && s.len() >= 2 && s.ends_with(q) {
let interieur = &s[1..s.len() - 1];
if !interieur.contains(q) && !interieur.contains('\\') {
return Some(interieur.to_string());
}
}
None
}
fn charger(source: &str) -> Result<Programme, String> {
let mut lignes = source.lines();
let tete = lignes.next().ok_or("source vide")?;
let nom = tete.strip_prefix("def ").and_then(|r| r.strip_suffix("(opp_source, k):"))
.ok_or(format!("en-tete non reconnu : {}", tete))?.to_string();
let corps_lignes: Vec<&str> = lignes.take_while(|l| l.starts_with(" ")).collect();
let mut corps = Vec::new();
let mut i = 0;
while i < corps_lignes.len() {
let l = &corps_lignes[i][4..];
if let Some(cond) = l.strip_prefix("if ").and_then(|r| r.strip_suffix(':')) {
let (negation, appel) = match cond.strip_prefix("not ") {
Some(r) => (true, r),
None => (false, cond),
};
let but = appel.strip_prefix("proof_search(k, opp_source, ").and_then(|r| r.strip_suffix(')'))
.and_then(chaine_python).ok_or(format!("condition non reconnue : {}", l))?;
let retour = corps_lignes.get(i + 1).and_then(|s| s.strip_prefix(" return "))
.and_then(chaine_python).ok_or(format!("bloc if non reconnu apres : {}", l))?;
corps.push(Instr::Si { negation, but, retour });
i += 2;
continue;
}
if let Some(e) = l.strip_prefix("return ") {
if let Some(v) = chaine_python(e) {
corps.push(Instr::Retour(v));
} else if let Some(arg) = e.strip_prefix("chr(").and_then(|r| r.strip_suffix(')')) {
corps.push(Instr::RetourChr(arg.trim().to_string()));
} else {
return Err(format!("retour non reconnu : {}", l));
}
} else if let Some((var, val)) = l.split_once(" = ") {
let v: i64 = val.trim().parse().map_err(|_| format!("affectation non reconnue : {}", l))?;
corps.push(Instr::Affecte(var.trim().to_string(), v));
} else {
return Err(format!("instruction non reconnue : {}", l));
}
i += 1;
}
Ok(Programme { nom, corps })
}
fn executer(p: &Programme, opp_source: &str, k: usize) -> Result<String, String> {
let mut vars: HashMap<String, i64> = HashMap::new();
for ins in &p.corps {
match ins {
Instr::Retour(v) => return Ok(v.clone()),
Instr::Affecte(n, v) => {
vars.insert(n.clone(), *v);
}
Instr::RetourChr(arg) => {
let code = match arg.parse::<i64>() {
Ok(v) => v,
Err(_) => *vars.get(arg).ok_or(format!("nom inconnu : {}", arg))?,
};
return char::from_u32(code as u32).map(|c| c.to_string()).ok_or(format!("chr hors domaine : {}", code));
}
Instr::Si { negation, but, retour } => {
if proof_search(k, opp_source, but) != *negation {
return Ok(retour.clone());
}
}
}
}
Err(format!("{} se termine sans return", p.nom))
}
type Issue = (String, String, (i64, i64));
struct Moteur { programmes: Vec<(String, Programme)> }
impl Moteur {
// PROGRAMMES = {nom: charger(SOURCES[nom])[nom] for nom in ORDRE}
fn charger_tout() -> Moteur {
let programmes = ORDRE.iter().map(|nom| {
let p = charger(source(nom)).expect("texte publie interpretable");
assert!(p.nom == *nom, "la source ne definit pas {}", nom);
(nom.to_string(), p)
}).collect();
Moteur { programmes }
}
fn programme(&self, nom: &str) -> &Programme {
&self.programmes.iter().find(|(n, _)| n == nom).expect("programme charge").1
}
fn action(&self, nom: &str, adverse: &str, k: usize) -> String {
executer(self.programme(nom), source(adverse), k).expect("execution du programme")
}
fn issue(&self, nom_a: &str, nom_b: &str, k: usize) -> Issue {
let act_a = self.action(nom_a, nom_b, k);
let act_b = self.action(nom_b, nom_a, k);
let g = (gain(&act_a, &act_b), gain(&act_b, &act_a));
(act_a, act_b, g)
}
}
fn paires() -> Vec<(String, String)> {
ORDRE.iter().flat_map(|a| ORDRE.iter().map(move |b| (a.to_string(), b.to_string()))).collect()
}
// ISSUE_MOTEUR = {(a, b): issue(a, b) for a, b in itertools.product(ORDRE, repeat=2)} (ordre d'insertion)
fn table_moteur(m: &Moteur) -> Vec<((String, String), Issue)> {
paires().into_iter().map(|(a, b)| {
let i = m.issue(&a, &b, K_DEFAUT);
((a, b), i)
}).collect()
}
fn chercher<'a>(table: &'a [((String, String), Issue)], a: &str, b: &str) -> &'a Issue {
&table.iter().find(|((x, y), _)| x == a && y == b).expect("paire du registre").1
}
fn py_list(items: &BTreeSet<String>) -> String {
format!("[{}]", items.iter().map(|s| format!("'{}'", s)).collect::<Vec<_>>().join(", "))
}
fn py_pair(a: &str, b: &str) -> String { format!("('{}', '{}')", a, b) }
fn py_gains(g: (i64, i64)) -> String { format!("({}, {})", g.0, g.1) }
fn py_bool(b: bool) -> &'static str { if b { "True" } else { "False" } }
// ---- fin du bloc moteur ----
// ---- Bloc verificateur Dynamics-08 (std seul) — en tete des cellules 29, 31 et 33, apres le bloc moteur ----
const REGLES_B: [(&str, &[&str]); 8] = [
("uncond_coop", &["intent_coop"]),
("uncond_defect", &["intent_defect"]),
("self_cond_coop", &["implies_own_coop", "defects_with_db"]),
("intent_coop", &["coops_against_any", "coops_with_db"]),
("intent_defect", &["defects_against_any", "defects_with_db"]),
("needs_proof_of_coop", &["defects_with_db"]),
("needs_proof_of_defect", &["defects_with_db"]),
("prudent", &["defects_with_db"]),
];
// Equivalent de re.search(r"bylaws_json\s*=\s*'([^']*)'", source) : premiere occurrence complete.
fn champ_bylaws_json(source: &str) -> Option<&str> {
for (i, _) in source.match_indices("bylaws_json") {
let r = source[i + "bylaws_json".len()..].trim_start();
if let Some(r) = r.strip_prefix('=') {
if let Some(r) = r.trim_start().strip_prefix('\'') {
if let Some(fin) = r.find('\'') {
return Some(&r[..fin]);
}
}
}
}
None
}
// Lecteur du seul format publie : {"atoms": ["a", "b", ...]} (chaines sans echappement).
fn atomes_json(texte: &str) -> Result<BTreeSet<String>, String> {
let interieur = texte.trim().strip_prefix('{').and_then(|r| r.strip_suffix('}')).ok_or("objet JSON attendu")?;
let liste = interieur.trim().strip_prefix("\"atoms\"").map(str::trim_start).and_then(|r| r.strip_prefix(':'))
.map(str::trim).and_then(|r| r.strip_prefix('[')).and_then(|r| r.strip_suffix(']'))
.ok_or("champ atoms attendu")?;
let mut atomes = BTreeSet::new();
for brut in liste.split(',').map(str::trim).filter(|s| !s.is_empty()) {
let a = brut.strip_prefix('"').and_then(|r| r.strip_suffix('"'))
.ok_or(format!("chaine JSON attendue : {}", brut))?;
if a.contains('"') || a.contains('\\') {
return Err(format!("echappement non gere : {}", brut));
}
atomes.insert(a.to_string());
}
Ok(atomes)
}
fn parse_certificat_b(source: &str) -> BTreeSet<String> {
let champ = champ_bylaws_json(source).expect("champ bylaws_json absent");
atomes_json(champ).expect("JSON du certificat")
}
fn cloture_b(graine: &BTreeSet<String>, k: usize) -> BTreeSet<String> {
let mut faits = graine.clone();
for _ in 0..k {
let mut ajouts = BTreeSet::new();
for (premisse, conclusions) in REGLES_B.iter() {
if faits.contains(*premisse) {
ajouts.extend(conclusions.iter().map(|c| c.to_string()));
}
}
if ajouts.is_subset(&faits) {
return faits;
}
faits.extend(ajouts);
}
faits
}
fn decision_verificateur(nom: &str, source: &str, k: usize) -> Result<String, String> {
let faits = cloture_b(&parse_certificat_b(source), k);
let choix = |b: bool, si: &str, sinon: &str| if b { si.to_string() } else { sinon.to_string() };
match nom {
"CooperateBot" | "CooperateBotOpake" => Ok("C".to_string()),
"DefectBot" => Ok("D".to_string()),
"CUPOD" => Ok(choix(faits.contains("defects_against_any"), "D", "C")),
"DUPOC" => Ok(choix(faits.contains("coops_against_any"), "C", "D")),
"CIMCIC" => Ok(choix(faits.contains("implies_own_coop"), "C", "D")),
"PrudentBot_borne" => Ok(if !faits.contains("coops_against_any") {
"D".to_string()
} else {
choix(faits.contains("defects_with_db"), "C", "D")
}),
_ => Err(format!("role inconnu : {}", nom)),
}
}
fn issue_verificateur(nom_a: &str, nom_b: &str, k: usize) -> Issue {
let act_a = decision_verificateur(nom_a, source(nom_b), k).expect("role connu");
let act_b = decision_verificateur(nom_b, source(nom_a), k).expect("role connu");
let g = (gain(&act_a, &act_b), gain(&act_b, &act_a));
(act_a, act_b, g)
}
// ---- fin du bloc verificateur ----
// ---------------------------------------------------------------------------
// Comparaison mecanique : actions, relation de cooperation, matrice de gains.
// ---------------------------------------------------------------------------
let m = Moteur::charger_tout();
let ps = paires();
let im = table_moteur(&m);
let desaccords: Vec<((String, String), Issue)> = im.iter()
.filter(|((a, b), i)| *i != issue_verificateur(a, b, K_DEFAUT))
.map(|(p, i)| (p.clone(), i.clone()))
.collect();
assert!(desaccords.is_empty(), "{} desaccords", desaccords.len());
let relation_moteur: BTreeSet<(String, String)> = im.iter()
.filter(|(_, i)| i.0 == "C")
.map(|((a, b), _)| (a.clone(), b.clone()))
.collect();
let relation_verif: BTreeSet<(String, String)> = ps.iter()
.filter(|(a, b)| issue_verificateur(a, b, K_DEFAUT).0 == "C")
.map(|(a, b)| (a.clone(), b.clone()))
.collect();
let gains_moteur: BTreeMap<(String, String), (i64, i64)> = im.iter()
.map(|((a, b), i)| ((a.clone(), b.clone()), i.2))
.collect();
let gains_verif: BTreeMap<(String, String), (i64, i64)> = ps.iter()
.map(|(a, b)| ((a.clone(), b.clone()), issue_verificateur(a, b, K_DEFAUT).2))
.collect();
assert!(relation_moteur == relation_verif);
assert!(gains_moteur == gains_verif);
println!("Paires ordonnees comparees : {}", ps.len());
println!("Desaccords moteur / verificateur : {}", desaccords.len());
println!("Relation de cooperation identique : {}", py_bool(relation_moteur == relation_verif));
println!("Matrice de gains identique : {}", py_bool(gains_moteur == gains_verif));
println!();
println!("Deux implementations independantes, un seul verdict sur les trois objets compares.");