use std::{fmt::Display, str::FromStr};
use winnow::{
ModalResult, Parser,
error::{ContextError, StrContext},
stream::AsChar,
token::take_till,
};
use crate::roles::SphinxType;
#[derive(Debug, PartialEq, Clone)]
pub enum CppRole {
Enum,
Enumerator,
Class,
Struct,
Union,
Concept,
Function,
FunctionParam,
Member,
Var,
TemplateParam,
Type,
}
impl Display for CppRole {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
CppRole::Enumerator => "enumerator",
CppRole::Enum => "enum",
CppRole::Class | CppRole::Struct => "class",
CppRole::Function => "function",
CppRole::FunctionParam => "functionParam",
CppRole::Member | CppRole::Var => "member",
CppRole::TemplateParam => "templateParam",
CppRole::Type => "type",
CppRole::Union => "union",
CppRole::Concept => "concept",
})
}
}
impl FromStr for CppRole {
type Err = ContextError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"class" => Ok(CppRole::Class),
"enumerator" => Ok(CppRole::Enumerator),
"enum" => Ok(CppRole::Enum),
"function" => Ok(CppRole::Function),
"functionParam" => Ok(CppRole::FunctionParam),
"member" => Ok(CppRole::Member),
"templateParam" => Ok(CppRole::TemplateParam),
"concept" => Ok(CppRole::Concept),
"union" => Ok(CppRole::Union),
"type" => Ok(CppRole::Type),
_ => Err(ContextError::new()),
}
}
}
pub(crate) fn cpp_role(input: &mut &str) -> ModalResult<SphinxType> {
let role = take_till(1.., AsChar::is_space)
.context(StrContext::Label("Cpp Role"))
.parse_to()
.parse_next(input)?;
Ok(SphinxType::Cpp(role))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_sphinx_role_parsing_std_err() {
assert!(CppRole::from_str("asdf").is_err());
assert!(CppRole::from_str("doc").is_err());
assert!(CppRole::from_str("").is_err());
assert!(CppRole::from_str("::::").is_err());
assert!(CppRole::from_str(" label").is_err());
assert!(CppRole::from_str(" asdf").is_err());
assert!(CppRole::from_str("function Param").is_err());
}
#[test]
fn test_sphinx_type_parsing_cpp() -> Result<(), ContextError> {
assert_eq!(CppRole::from_str("class")?, CppRole::Class);
assert_eq!(CppRole::from_str("function")?, CppRole::Function);
assert_eq!(CppRole::from_str("functionParam")?, CppRole::FunctionParam);
assert_eq!(CppRole::from_str("templateParam")?, CppRole::TemplateParam);
assert_eq!(CppRole::from_str("member")?, CppRole::Member);
Ok(())
}
}