arc-flow-core 0.1.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
//! 类型化端口(参考 ferrum-flow `PortType` / `PortScope`,Apache-2.0,已改写)。

use crate::ids::{NodeId, PortId};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// 端口所在的节点边。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Side {
    Left,
    #[default]
    Right,
    Top,
    Bottom,
}

impl Side {
    pub fn is_horizontal(self) -> bool {
        matches!(self, Side::Left | Side::Right)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortDirection {
    Input,
    Output,
}

/// 连接作用域:`Local` 只能连同一父节点下的兄弟;`Boundary` 可跨层级。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortScope {
    #[default]
    Local,
    Boundary,
}

/// 端口数据类型。`Any` 与任何类型兼容;`Union` 只要有一个分支兼容即可。
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortType {
    #[default]
    Any,
    Bool,
    Int,
    Float,
    String,
    List(Box<PortType>),
    Map(Box<PortType>, Box<PortType>),
    Custom(Arc<str>),
    Union(Vec<PortType>),
}

impl PortType {
    /// 输出端类型 `self` 能否流向输入端类型 `input`。`Int → Float` 视为可隐式提升。
    pub fn flows_into(&self, input: &PortType) -> bool {
        use PortType::*;
        match (self, input) {
            (Any, _) | (_, Any) => true,
            (Union(outs), _) => outs.iter().all(|o| o.flows_into(input)),
            (_, Union(ins)) => ins.iter().any(|i| self.flows_into(i)),
            (Int, Float) => true,
            (List(a), List(b)) => a.flows_into(b),
            (Map(ka, va), Map(kb, vb)) => ka.flows_into(kb) && va.flows_into(vb),
            (a, b) => a == b,
        }
    }

    /// 简短显示名,供连接失败提示使用。
    pub fn label(&self) -> String {
        use PortType::*;
        match self {
            Any => "any".into(),
            Bool => "bool".into(),
            Int => "int".into(),
            Float => "float".into(),
            String => "string".into(),
            List(t) => format!("list<{}>", t.label()),
            Map(k, v) => format!("map<{}, {}>", k.label(), v.label()),
            Custom(n) => n.to_string(),
            Union(ts) => ts.iter().map(|t| t.label()).collect::<Vec<_>>().join(" | "),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Port {
    pub id: PortId,
    pub node: NodeId,
    pub direction: PortDirection,
    pub side: Side,
    pub ty: PortType,
    #[serde(default)]
    pub scope: PortScope,
    /// 允许的最大连接数;`None` 为不限。输入端默认 1。
    pub max_connections: Option<usize>,
    pub label: Option<Arc<str>>,
    #[serde(default = "default_true")]
    pub connectable: bool,
}

fn default_true() -> bool {
    true
}

impl Port {
    pub fn new(id: PortId, node: NodeId, direction: PortDirection) -> Self {
        let (side, max_connections) = match direction {
            PortDirection::Input => (Side::Left, Some(1)),
            PortDirection::Output => (Side::Right, None),
        };
        Self {
            id,
            node,
            direction,
            side,
            ty: PortType::Any,
            scope: PortScope::Local,
            max_connections,
            label: None,
            connectable: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::PortType::*;

    #[test]
    fn type_compatibility() {
        assert!(Int.flows_into(&Float));
        assert!(!Float.flows_into(&Int));
        assert!(Any.flows_into(&String));
        assert!(String.flows_into(&Union(vec![Int, String])));
        assert!(!Union(vec![Int, String]).flows_into(&Int));
        assert!(List(Box::new(Int)).flows_into(&List(Box::new(Float))));
        assert!(!List(Box::new(String)).flows_into(&List(Box::new(Int))));
        assert_eq!(
            Map(Box::new(String), Box::new(Int)).label(),
            "map<string, int>"
        );
    }
}