Skip to main content

pddl_ish_parser/parser/
object.rs

1use regex::Regex;
2
3use crate::models::parser_error::ParserError;
4
5use super::error_context::get_error_context;
6
7
8#[derive(Debug, PartialEq, Clone)]
9pub struct Object {
10    pub name: String,
11    pub object_type: String,
12}
13
14// Function to parse objects
15pub fn parse_object_line(line: &str) -> Option<Object> {
16    if let Some(index) = line.rfind(" - ") {
17        let (name, object_type) = line.split_at(index);
18        Some(Object {
19            name: name.trim().to_string(),
20            object_type: object_type.replace(" - ", "").trim().to_string(),
21        })
22    } else {
23        None
24    }
25}
26
27
28pub fn parse_objects(input: &str) -> Result<(&str, Vec<Object>), ParserError> {
29    let object_regex = Regex::new(r"\(:objects\s((.|\n)*?)\)").unwrap();
30
31    if let Some(captures) = object_regex.captures(input) {
32        let objects_str = &captures[1];
33
34        let objects: Vec<Object> = objects_str
35            .lines()
36            .map(|line| line.trim())
37            .filter(|line| !line.is_empty())
38            .filter_map(parse_object_line)
39            .collect();
40
41
42        let next_input = &input[captures.get(0).unwrap().end()..];
43        Ok((next_input, objects))
44    } else {
45        Err(ParserError {
46            description: "Failed to parse objects".to_string(),
47            code: get_error_context(input),
48        })
49    }
50}