use std::fmt;
use std::path::PathBuf;
use crate::registry_core::declaration::RuntimeCheckSpec;
use crate::registry_core::syntax::nesting::guard_nesting;
use crate::registry_core::syntax::parse_face as parse_face_syntax;
use super::validation::{normalized_path, rust_string};
#[path = "flow.rs"]
mod flow;
pub use flow::*;
#[path = "admission.rs"]
mod admission;
pub use admission::*;
#[path = "rules.rs"]
mod rules;
pub use rules::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FaceParseError {
pub message: String,
}
impl FaceParseError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for FaceParseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for FaceParseError {}
impl From<String> for FaceParseError {
fn from(message: String) -> Self {
Self { message }
}
}
impl From<FaceParseError> for String {
fn from(error: FaceParseError) -> Self {
error.message
}
}
pub fn module_source_from_node_path(module: &str) -> Option<String> {
let module = module.strip_prefix("crate::").unwrap_or(module);
let mut segments = module.split("::").filter(|segment| !segment.is_empty());
let first = segments.next()?;
let mut path = PathBuf::from(first);
let mut last = first;
for segment in segments {
path.push(segment);
last = segment;
}
path.push(format!("{last}.rs"));
Some(normalized_path(&path))
}
pub fn kind_from_source_text(text: &str) -> Option<String> {
parse_face_syntax(text)
.ok()?
.and_then(|face| face.path("kind"))
}
pub fn quoted_list_field(text: &str, marker: &str) -> Vec<String> {
let Some(start) = text.find(marker) else {
return Vec::new();
};
let rest = &text[start + marker.len()..];
let Some(open) = rest.find('[') else {
return Vec::new();
};
let Some(close) = rest[open + 1..].find(']') else {
return Vec::new();
};
rest[open + 1..open + 1 + close]
.split(',')
.filter_map(|value| {
value
.trim()
.strip_prefix('"')
.and_then(|value| value.strip_suffix('"'))
.map(str::to_owned)
})
.collect()
}
pub fn module_name_from_path(path: &std::path::Path) -> String {
path.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("module")
.to_owned()
}
pub fn render_face_list(field: &str, value: &str) -> String {
let values = value
.split(',')
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| format!("\"{}\"", rust_string(value)))
.collect::<Vec<_>>();
if values.is_empty() {
String::new()
} else {
format!(" {field}: [{}],\n", values.join(", "))
}
}
pub fn render_literal_list(value: &str) -> String {
value
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| format!("\"{}\"", rust_string(item)))
.collect::<Vec<_>>()
.join(", ")
}
pub fn render_path_list(value: &str) -> String {
value
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.collect::<Vec<_>>()
.join(", ")
}
pub fn trait_names_from_paths(value: &str) -> Result<String, FaceParseError> {
split_type_paths(value)
.into_iter()
.map(str::trim)
.filter(|path| !path.is_empty())
.map(|source| {
guard_nesting(source).map_err(|error| FaceParseError::new(error.to_string()))?;
let path = syn::parse_str::<syn::Path>(source)
.map_err(|_| FaceParseError::new(format!("`{source}` is not a Rust trait path")))?;
path.segments
.last()
.map(|segment| segment.ident.to_string())
.ok_or_else(|| FaceParseError::new(format!("`{source}` has no trait name")))
})
.collect::<Result<Vec<_>, _>>()
.map(|names| names.join(","))
}
fn split_type_paths(value: &str) -> Vec<&str> {
let mut paths = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (offset, character) in value.char_indices() {
match character {
'<' => depth += 1,
'>' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
paths.push(&value[start..offset]);
start = offset + 1;
}
_ => {}
}
}
paths.push(&value[start..]);
paths
}
pub fn render_expression_list(value: &str) -> Result<String, FaceParseError> {
RuntimeCheckSpec::parse_list(value)
.map_err(FaceParseError::from)
.map(|checks| {
checks
.into_iter()
.map(RuntimeCheckSpec::expression)
.collect::<Vec<_>>()
.join(", ")
})
}
pub fn render_optional_source(value: &str) -> Result<String, FaceParseError> {
let value = value.trim();
if value.is_empty() || value.eq_ignore_ascii_case("none") {
Ok("None".to_owned())
} else {
Ok(format!("Some(\"{}\")", rust_string(value)))
}
}
pub fn parse_field_list(value: &str) -> Vec<String> {
value
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.map(str::to_owned)
.collect()
}
pub fn split_csv_owned(value: &str) -> Vec<String> {
parse_field_list(value)
}
pub fn parse_optional_source(value: &str) -> Result<(), FaceParseError> {
let value = value.trim();
if value.is_empty() || value.eq_ignore_ascii_case("none") {
return Ok(());
}
if value.contains(['\n', '\r']) {
return Err("getting_from_other_registry cannot contain a newline"
.to_owned()
.into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::trait_names_from_paths;
#[test]
fn compiler_checked_trait_paths_supply_searchable_labels() {
assert_eq!(
trait_names_from_paths("crate::ui::ControlHandle, crate::parts::ActionParts").unwrap(),
"ControlHandle,ActionParts"
);
assert!(trait_names_from_paths("not a path").is_err());
}
}