use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;
use crate::graph::Grid;
use crate::instance::{Agent, Instance, InstanceError};
pub fn parse_map(text: &str) -> Result<Grid, ParseError> {
let mut lines = numbered_lines(text);
let (width, height) = parse_map_header(&mut lines)?;
let rows = read_map_rows(text, &mut lines, width, height)?;
let mut grid = Grid::new(width, height);
for (y, row) in rows.iter().enumerate() {
block_map_row(&mut grid, y, row);
}
Ok(grid)
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScenarioEntry {
pub bucket: u32,
pub map: String,
pub map_width: usize,
pub map_height: usize,
pub start: (usize, usize),
pub goal: (usize, usize),
pub optimal_length: f64,
}
pub fn parse_scenario(text: &str) -> Result<Vec<ScenarioEntry>, ParseError> {
let mut lines = numbered_lines(text).filter(|(_, line)| !line.is_empty());
match lines.next() {
Some((_, line)) if line.starts_with("version") => {}
other => {
return Err(ParseError {
line: other.map_or(1, |(line, _)| line),
kind: ParseErrorKind::MissingHeader("version"),
});
}
}
lines
.map(|(line, text)| parse_scenario_entry(line, text))
.collect()
}
pub fn scenario_instance(
grid: Grid,
entries: &[ScenarioEntry],
agents: usize,
) -> Result<Instance<Grid>, ScenarioError> {
let chosen = entries.get(..agents).ok_or(ScenarioError::TooFewEntries {
available: entries.len(),
})?;
let agents = chosen
.iter()
.enumerate()
.map(|(index, entry)| entry_agent(&grid, index, entry))
.collect::<Result<Vec<_>, _>>()?;
Instance::new(grid, agents).map_err(ScenarioError::Instance)
}
fn entry_agent(grid: &Grid, index: usize, entry: &ScenarioEntry) -> Result<Agent, ScenarioError> {
if (entry.map_width, entry.map_height) != (grid.width(), grid.height()) {
return Err(ScenarioError::MapSize { entry: index });
}
let start = grid.vertex(entry.start.0, entry.start.1);
let goal = grid.vertex(entry.goal.0, entry.goal.1);
if grid.is_blocked(start) || grid.is_blocked(goal) {
return Err(ScenarioError::BlockedCell { entry: index });
}
Ok(Agent { start, goal })
}
fn numbered_lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.lines()
.enumerate()
.map(|(index, line)| (index + 1, line.trim_end()))
}
fn parse_map_header<'a>(
lines: &mut impl Iterator<Item = (usize, &'a str)>,
) -> Result<(usize, usize), ParseError> {
let (mut width, mut height, mut kind) = (None, None, None);
let mut last = 0;
for (line, text) in lines.by_ref() {
last = line;
let mut words = text.split_whitespace();
match (words.next(), words.next()) {
(Some("map"), None) => return header_size(width, height, kind, line),
(Some("type"), Some(value)) => kind = Some(value),
(Some("height"), Some(value)) => height = Some(number(line, value)?),
(Some("width"), Some(value)) => width = Some(number(line, value)?),
(None, _) => {}
_ => return Err(ParseError::new(line, ParseErrorKind::UnknownHeader)),
}
}
Err(ParseError::new(
last + 1,
ParseErrorKind::MissingHeader("map"),
))
}
fn header_size(
width: Option<usize>,
height: Option<usize>,
kind: Option<&str>,
line: usize,
) -> Result<(usize, usize), ParseError> {
let missing = |field| ParseError::new(line, ParseErrorKind::MissingHeader(field));
kind.ok_or_else(|| missing("type"))?;
let width = width.ok_or_else(|| missing("width"))?;
let height = height.ok_or_else(|| missing("height"))?;
if width == 0 || height == 0 {
return Err(ParseError::new(line, ParseErrorKind::EmptyMap));
}
Ok((width, height))
}
fn read_map_rows<'a>(
text: &str,
lines: &mut impl Iterator<Item = (usize, &'a str)>,
width: usize,
height: usize,
) -> Result<Vec<&'a str>, ParseError> {
let rows = (0..height)
.map(|_| {
let (line, row) = lines.next().ok_or_else(|| {
ParseError::new(text.lines().count() + 1, ParseErrorKind::MissingRows)
})?;
check_map_row(width, line, row)?;
Ok(row)
})
.collect::<Result<Vec<_>, _>>()?;
if let Some((line, _)) = lines.find(|(_, row)| !row.is_empty()) {
return Err(ParseError::new(line, ParseErrorKind::ExtraRows));
}
Ok(rows)
}
fn check_map_row(width: usize, line: usize, row: &str) -> Result<(), ParseError> {
let found = row.chars().count();
if found != width {
return Err(ParseError::new(
line,
ParseErrorKind::RowLength {
expected: width,
found,
},
));
}
match row
.chars()
.find(|cell| !is_free_cell(*cell) && !is_blocked_cell(*cell))
{
Some(other) => Err(ParseError::new(line, ParseErrorKind::UnknownCell(other))),
None => Ok(()),
}
}
fn block_map_row(grid: &mut Grid, y: usize, row: &str) {
for (x, _) in row
.chars()
.enumerate()
.filter(|(_, cell)| is_blocked_cell(*cell))
{
grid.block(x, y);
}
}
fn is_free_cell(cell: char) -> bool {
matches!(cell, '.' | 'G' | 'S')
}
fn is_blocked_cell(cell: char) -> bool {
matches!(cell, '@' | 'O' | 'T' | 'W')
}
fn parse_scenario_entry(line: usize, text: &str) -> Result<ScenarioEntry, ParseError> {
let fields: Vec<&str> = text.split_whitespace().collect();
let [bucket, map, width, height, sx, sy, gx, gy, optimal] = fields[..] else {
return Err(ParseError::new(
line,
ParseErrorKind::FieldCount {
found: fields.len(),
},
));
};
let entry = ScenarioEntry {
bucket: number(line, bucket)?,
map: map.to_string(),
map_width: number(line, width)?,
map_height: number(line, height)?,
start: (number(line, sx)?, number(line, sy)?),
goal: (number(line, gx)?, number(line, gy)?),
optimal_length: number(line, optimal)?,
};
let inside = |(x, y): (usize, usize)| x < entry.map_width && y < entry.map_height;
if !inside(entry.start) || !inside(entry.goal) {
return Err(ParseError::new(line, ParseErrorKind::OutsideMap));
}
Ok(entry)
}
fn number<T: FromStr>(line: usize, text: &str) -> Result<T, ParseError> {
text.parse()
.map_err(|_| ParseError::new(line, ParseErrorKind::BadNumber))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseError {
pub line: usize,
pub kind: ParseErrorKind,
}
impl ParseError {
fn new(line: usize, kind: ParseErrorKind) -> Self {
Self { line, kind }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseErrorKind {
MissingHeader(&'static str),
UnknownHeader,
EmptyMap,
BadNumber,
RowLength {
expected: usize,
found: usize,
},
UnknownCell(char),
MissingRows,
ExtraRows,
FieldCount {
found: usize,
},
OutsideMap,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "line {}: ", self.line)?;
match self.kind {
ParseErrorKind::MissingHeader(field) => write!(f, "missing `{field}` header"),
ParseErrorKind::UnknownHeader => f.write_str("unknown header line"),
ParseErrorKind::EmptyMap => f.write_str("map has no cells"),
ParseErrorKind::BadNumber => f.write_str("expected a number"),
ParseErrorKind::RowLength { expected, found } => {
write!(f, "row has {found} cells, expected {expected}")
}
ParseErrorKind::UnknownCell(cell) => write!(f, "unknown map cell {cell:?}"),
ParseErrorKind::MissingRows => f.write_str("map has too few rows"),
ParseErrorKind::ExtraRows => f.write_str("map has too many rows"),
ParseErrorKind::FieldCount { found } => {
write!(f, "scenario line has {found} fields, expected 9")
}
ParseErrorKind::OutsideMap => f.write_str("start or goal outside the map"),
}
}
}
impl core::error::Error for ParseError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScenarioError {
MapSize {
entry: usize,
},
TooFewEntries {
available: usize,
},
BlockedCell {
entry: usize,
},
Instance(InstanceError),
}
impl fmt::Display for ScenarioError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MapSize { entry } => write!(f, "scenario entry {entry} is for another map size"),
Self::TooFewEntries { available } => {
write!(f, "the scenario has only {available} entries")
}
Self::BlockedCell { entry } => {
write!(f, "scenario entry {entry} starts or ends on a blocked cell")
}
Self::Instance(error) => write!(f, "invalid instance: {error}"),
}
}
}
impl core::error::Error for ScenarioError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Instance(error) => Some(error),
_ => None,
}
}
}