1use alloc::string::{String, ToString};
28use alloc::vec::Vec;
29use core::fmt;
30use core::str::FromStr;
31
32use crate::graph::Grid;
33use crate::instance::{Agent, Instance, InstanceError};
34
35pub fn parse_map(text: &str) -> Result<Grid, ParseError> {
48 let mut lines = numbered_lines(text);
49 let (width, height) = parse_map_header(&mut lines)?;
50
51 let rows = read_map_rows(text, &mut lines, width, height)?;
54 let mut grid = Grid::new(width, height);
55 for (y, row) in rows.iter().enumerate() {
56 block_map_row(&mut grid, y, row);
57 }
58
59 Ok(grid)
60}
61
62#[derive(Debug, Clone, PartialEq)]
64pub struct ScenarioEntry {
65 pub bucket: u32,
67 pub map: String,
69 pub map_width: usize,
71 pub map_height: usize,
73 pub start: (usize, usize),
75 pub goal: (usize, usize),
77 pub optimal_length: f64,
80}
81
82pub fn parse_scenario(text: &str) -> Result<Vec<ScenarioEntry>, ParseError> {
90 let mut lines = numbered_lines(text).filter(|(_, line)| !line.is_empty());
91 match lines.next() {
92 Some((_, line)) if line.starts_with("version") => {}
93 other => {
94 return Err(ParseError {
95 line: other.map_or(1, |(line, _)| line),
96 kind: ParseErrorKind::MissingHeader("version"),
97 });
98 }
99 }
100
101 lines
102 .map(|(line, text)| parse_scenario_entry(line, text))
103 .collect()
104}
105
106pub fn scenario_instance(
116 grid: Grid,
117 entries: &[ScenarioEntry],
118 agents: usize,
119) -> Result<Instance<Grid>, ScenarioError> {
120 let chosen = entries.get(..agents).ok_or(ScenarioError::TooFewEntries {
121 available: entries.len(),
122 })?;
123 let agents = chosen
124 .iter()
125 .enumerate()
126 .map(|(index, entry)| entry_agent(&grid, index, entry))
127 .collect::<Result<Vec<_>, _>>()?;
128
129 Instance::new(grid, agents).map_err(ScenarioError::Instance)
130}
131
132fn entry_agent(grid: &Grid, index: usize, entry: &ScenarioEntry) -> Result<Agent, ScenarioError> {
134 if (entry.map_width, entry.map_height) != (grid.width(), grid.height()) {
135 return Err(ScenarioError::MapSize { entry: index });
136 }
137
138 let start = grid.vertex(entry.start.0, entry.start.1);
139 let goal = grid.vertex(entry.goal.0, entry.goal.1);
140 if grid.is_blocked(start) || grid.is_blocked(goal) {
141 return Err(ScenarioError::BlockedCell { entry: index });
142 }
143
144 Ok(Agent { start, goal })
145}
146
147fn numbered_lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
149 text.lines()
150 .enumerate()
151 .map(|(index, line)| (index + 1, line.trim_end()))
152}
153
154fn parse_map_header<'a>(
157 lines: &mut impl Iterator<Item = (usize, &'a str)>,
158) -> Result<(usize, usize), ParseError> {
159 let (mut width, mut height, mut kind) = (None, None, None);
160 let mut last = 0;
161
162 for (line, text) in lines.by_ref() {
163 last = line;
164 let mut words = text.split_whitespace();
165 match (words.next(), words.next()) {
166 (Some("map"), None) => return header_size(width, height, kind, line),
167 (Some("type"), Some(value)) => kind = Some(value),
168 (Some("height"), Some(value)) => height = Some(number(line, value)?),
169 (Some("width"), Some(value)) => width = Some(number(line, value)?),
170 (None, _) => {}
171 _ => return Err(ParseError::new(line, ParseErrorKind::UnknownHeader)),
172 }
173 }
174
175 Err(ParseError::new(
176 last + 1,
177 ParseErrorKind::MissingHeader("map"),
178 ))
179}
180
181fn header_size(
183 width: Option<usize>,
184 height: Option<usize>,
185 kind: Option<&str>,
186 line: usize,
187) -> Result<(usize, usize), ParseError> {
188 let missing = |field| ParseError::new(line, ParseErrorKind::MissingHeader(field));
189 kind.ok_or_else(|| missing("type"))?;
190 let width = width.ok_or_else(|| missing("width"))?;
191 let height = height.ok_or_else(|| missing("height"))?;
192
193 if width == 0 || height == 0 {
194 return Err(ParseError::new(line, ParseErrorKind::EmptyMap));
195 }
196
197 Ok((width, height))
198}
199
200fn read_map_rows<'a>(
204 text: &str,
205 lines: &mut impl Iterator<Item = (usize, &'a str)>,
206 width: usize,
207 height: usize,
208) -> Result<Vec<&'a str>, ParseError> {
209 let rows = (0..height)
210 .map(|_| {
211 let (line, row) = lines.next().ok_or_else(|| {
212 ParseError::new(text.lines().count() + 1, ParseErrorKind::MissingRows)
213 })?;
214 check_map_row(width, line, row)?;
215
216 Ok(row)
217 })
218 .collect::<Result<Vec<_>, _>>()?;
219
220 if let Some((line, _)) = lines.find(|(_, row)| !row.is_empty()) {
221 return Err(ParseError::new(line, ParseErrorKind::ExtraRows));
222 }
223
224 Ok(rows)
225}
226
227fn check_map_row(width: usize, line: usize, row: &str) -> Result<(), ParseError> {
229 let found = row.chars().count();
230 if found != width {
231 return Err(ParseError::new(
232 line,
233 ParseErrorKind::RowLength {
234 expected: width,
235 found,
236 },
237 ));
238 }
239
240 match row
241 .chars()
242 .find(|cell| !is_free_cell(*cell) && !is_blocked_cell(*cell))
243 {
244 Some(other) => Err(ParseError::new(line, ParseErrorKind::UnknownCell(other))),
245 None => Ok(()),
246 }
247}
248
249fn block_map_row(grid: &mut Grid, y: usize, row: &str) {
251 for (x, _) in row
252 .chars()
253 .enumerate()
254 .filter(|(_, cell)| is_blocked_cell(*cell))
255 {
256 grid.block(x, y);
257 }
258}
259
260fn is_free_cell(cell: char) -> bool {
262 matches!(cell, '.' | 'G' | 'S')
263}
264
265fn is_blocked_cell(cell: char) -> bool {
267 matches!(cell, '@' | 'O' | 'T' | 'W')
268}
269
270fn parse_scenario_entry(line: usize, text: &str) -> Result<ScenarioEntry, ParseError> {
272 let fields: Vec<&str> = text.split_whitespace().collect();
273 let [bucket, map, width, height, sx, sy, gx, gy, optimal] = fields[..] else {
274 return Err(ParseError::new(
275 line,
276 ParseErrorKind::FieldCount {
277 found: fields.len(),
278 },
279 ));
280 };
281
282 let entry = ScenarioEntry {
283 bucket: number(line, bucket)?,
284 map: map.to_string(),
285 map_width: number(line, width)?,
286 map_height: number(line, height)?,
287 start: (number(line, sx)?, number(line, sy)?),
288 goal: (number(line, gx)?, number(line, gy)?),
289 optimal_length: number(line, optimal)?,
290 };
291
292 let inside = |(x, y): (usize, usize)| x < entry.map_width && y < entry.map_height;
293 if !inside(entry.start) || !inside(entry.goal) {
294 return Err(ParseError::new(line, ParseErrorKind::OutsideMap));
295 }
296
297 Ok(entry)
298}
299
300fn number<T: FromStr>(line: usize, text: &str) -> Result<T, ParseError> {
302 text.parse()
303 .map_err(|_| ParseError::new(line, ParseErrorKind::BadNumber))
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct ParseError {
309 pub line: usize,
311 pub kind: ParseErrorKind,
313}
314
315impl ParseError {
316 fn new(line: usize, kind: ParseErrorKind) -> Self {
318 Self { line, kind }
319 }
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324#[non_exhaustive]
325pub enum ParseErrorKind {
326 MissingHeader(&'static str),
329 UnknownHeader,
331 EmptyMap,
333 BadNumber,
335 RowLength {
337 expected: usize,
339 found: usize,
341 },
342 UnknownCell(char),
344 MissingRows,
346 ExtraRows,
348 FieldCount {
350 found: usize,
352 },
353 OutsideMap,
355}
356
357impl fmt::Display for ParseError {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 write!(f, "line {}: ", self.line)?;
360 match self.kind {
361 ParseErrorKind::MissingHeader(field) => write!(f, "missing `{field}` header"),
362 ParseErrorKind::UnknownHeader => f.write_str("unknown header line"),
363 ParseErrorKind::EmptyMap => f.write_str("map has no cells"),
364 ParseErrorKind::BadNumber => f.write_str("expected a number"),
365 ParseErrorKind::RowLength { expected, found } => {
366 write!(f, "row has {found} cells, expected {expected}")
367 }
368 ParseErrorKind::UnknownCell(cell) => write!(f, "unknown map cell {cell:?}"),
369 ParseErrorKind::MissingRows => f.write_str("map has too few rows"),
370 ParseErrorKind::ExtraRows => f.write_str("map has too many rows"),
371 ParseErrorKind::FieldCount { found } => {
372 write!(f, "scenario line has {found} fields, expected 9")
373 }
374 ParseErrorKind::OutsideMap => f.write_str("start or goal outside the map"),
375 }
376 }
377}
378
379impl core::error::Error for ParseError {}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383#[non_exhaustive]
384pub enum ScenarioError {
385 MapSize {
387 entry: usize,
389 },
390 TooFewEntries {
392 available: usize,
394 },
395 BlockedCell {
397 entry: usize,
399 },
400 Instance(InstanceError),
402}
403
404impl fmt::Display for ScenarioError {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 match self {
407 Self::MapSize { entry } => write!(f, "scenario entry {entry} is for another map size"),
408 Self::TooFewEntries { available } => {
409 write!(f, "the scenario has only {available} entries")
410 }
411 Self::BlockedCell { entry } => {
412 write!(f, "scenario entry {entry} starts or ends on a blocked cell")
413 }
414 Self::Instance(error) => write!(f, "invalid instance: {error}"),
415 }
416 }
417}
418
419impl core::error::Error for ScenarioError {
420 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
421 match self {
422 Self::Instance(error) => Some(error),
423 _ => None,
424 }
425 }
426}