ligen_python_parser/
path.rs

1use rustpython_parser::ast::{ExprAttribute, Expr, Identifier, ExprName};
2
3use crate::{prelude::*, identifier::IdentifierParser};
4
5use ligen::{ir::Path, parser::ParserConfig};
6
7#[derive(Default)]
8pub struct PathParser {
9    identifier_parser: IdentifierParser,
10}
11
12impl Parser<&ExprAttribute> for PathParser {
13    type Output = Path;
14    fn parse(&self, input: &ExprAttribute, config: &ParserConfig) -> Result<Self::Output> {
15        Ok(self.parse(&input.attr, config)?.join(self.parse(&*input.value, config)?))
16    }
17}
18
19impl Parser<&ExprName> for PathParser {
20    type Output = Path;
21    fn parse(&self, input: &ExprName, config: &ParserConfig) -> Result<Self::Output> {
22        self.parse(&input.id, config)
23    }
24
25}
26
27impl Parser<&Identifier> for PathParser {
28    type Output = Path;
29    fn parse(&self, input: &Identifier, config: &ParserConfig) -> Result<Self::Output> {
30        let identifier = self.identifier_parser.parse(input.as_str(), config)?;
31        Ok(Path::from(identifier))
32    }
33}
34
35impl Parser<&Expr> for PathParser {
36    type Output = Path;
37    fn parse(&self, input: &Expr, config: &ParserConfig) -> Result<Self::Output> {
38        match input {
39            Expr::Attribute(attribute) => self.parse(attribute, config),
40            Expr::Name(name) => self.parse(name, config),
41            _ => Err(Error::Message(format!("Failed to parse path from {:?}", input))),
42        }
43    }
44}