use std::io::{BufRead, Error};
use crate::aiger::{AigerHeader, LineReader, Literals};
use crate::graph::{AigBuilder, AigGraph, NodeId};
pub fn parse_ascii_aiger_into_graph(
header: AigerHeader,
reader: &mut impl BufRead,
pre_optimize: bool,
) -> Result<AigGraph, Error> {
assert_eq!(header.num_bad_states, 0, "bad states not supported");
assert_eq!(header.num_invariants, 0, "invariants not supported");
assert_eq!(header.num_justice, 0, "justice properties not supported");
assert_eq!(header.num_fairness, 0, "fairness constraints not supported");
let mut graph = AigBuilder::new();
let mut literals = Literals::new(header.max_var);
let mut line_reader = LineReader::new(reader);
for _ in 0..header.num_inputs {
let input_lit = line_reader.read_int()?.expect("malformed input line");
let input_id: NodeId = graph.add_input();
literals.add(input_lit, input_id);
}
let mut latch_inputs: Vec<(NodeId, usize)> = Vec::with_capacity(header.num_latches);
for _ in 0..header.num_latches {
let [latch_lit, latch_input_lit] = line_reader.read_ints()?.expect("malformed latch line");
let latch_id = graph.add_latch(NodeId::FALSE);
literals.add(latch_lit, latch_id);
latch_inputs.push((latch_id, latch_input_lit));
}
let mut output_lits: Vec<usize> = Vec::with_capacity(header.num_outputs);
for _ in 0..header.num_outputs {
let output_lit = line_reader.read_int()?.expect("malformed output line");
output_lits.push(output_lit);
}
for _ in 0..header.num_and_gates {
let [lhs_lit, rhs0_lit, rhs1_lit] = line_reader.read_ints()?.expect("malformed and line");
let left: NodeId = literals.get(rhs0_lit);
let right: NodeId = literals.get(rhs1_lit);
let and_id: NodeId = if pre_optimize {
graph.add_and_optimized(left, right)
} else {
graph.add_and_raw(left, right)
};
literals.add(lhs_lit, and_id);
}
for (latch_id, latch_input_lit) in latch_inputs {
let latch_input_id: NodeId = literals.get(latch_input_lit);
graph.node(latch_id).set_latch_input(latch_input_id);
}
for output_lit in output_lits {
let output_id: NodeId = literals.get(output_lit);
graph.add_output(output_id);
}
Ok(graph.build())
}