1use crate::graph::Graph;
6use crate::ids::{EdgeId, PortId};
7use crate::port::{PortDirection, PortScope};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub enum ConnectErrorCode {
11 MissingPort,
12 NotConnectable,
13 DirectionMismatch,
15 SameNode,
16 TypeMismatch,
17 ScopeMismatch,
18 AlreadyConnected,
19 PortFull,
21 WouldCreateCycle,
22 Custom,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct ConnectError {
27 pub code: ConnectErrorCode,
28 pub message: String,
29}
30
31impl ConnectError {
32 pub fn new(code: ConnectErrorCode, message: impl Into<String>) -> Self {
33 Self {
34 code,
35 message: message.into(),
36 }
37 }
38}
39
40pub trait ConnectionValidator {
42 fn validate(
43 &self,
44 graph: &Graph,
45 from: PortId,
46 to: PortId,
47 replacing: Option<EdgeId>,
48 ) -> Result<(), ConnectError>;
49}
50
51#[derive(Clone, Copy, Debug)]
53pub struct DefaultValidator {
54 pub check_types: bool,
55 pub check_scope: bool,
56 pub allow_self_loops: bool,
57 pub allow_cycles: bool,
58}
59
60impl Default for DefaultValidator {
61 fn default() -> Self {
62 Self {
63 check_types: true,
64 check_scope: true,
65 allow_self_loops: false,
66 allow_cycles: true,
67 }
68 }
69}
70
71impl DefaultValidator {
72 pub fn dag() -> Self {
74 Self {
75 allow_cycles: false,
76 ..Self::default()
77 }
78 }
79
80 pub fn normalise(graph: &Graph, a: PortId, b: PortId) -> Option<(PortId, PortId)> {
82 let pa = graph.port(a)?;
83 let pb = graph.port(b)?;
84 match (pa.direction, pb.direction) {
85 (PortDirection::Output, PortDirection::Input) => Some((a, b)),
86 (PortDirection::Input, PortDirection::Output) => Some((b, a)),
87 _ => None,
88 }
89 }
90}
91
92impl ConnectionValidator for DefaultValidator {
93 fn validate(
94 &self,
95 graph: &Graph,
96 from: PortId,
97 to: PortId,
98 replacing: Option<EdgeId>,
99 ) -> Result<(), ConnectError> {
100 use ConnectErrorCode as C;
101 let (Some(out), Some(inp)) = (graph.port(from), graph.port(to)) else {
102 return Err(ConnectError::new(C::MissingPort, "端口不存在"));
103 };
104 if !out.connectable || !inp.connectable {
105 return Err(ConnectError::new(C::NotConnectable, "该端口不可连接"));
106 }
107 if out.direction != PortDirection::Output || inp.direction != PortDirection::Input {
108 return Err(ConnectError::new(
109 C::DirectionMismatch,
110 "只能从输出端连到输入端",
111 ));
112 }
113 if out.node == inp.node && !self.allow_self_loops {
114 return Err(ConnectError::new(C::SameNode, "不能连到同一个节点"));
115 }
116 if self.check_types && !out.ty.flows_into(&inp.ty) {
117 return Err(ConnectError::new(
118 C::TypeMismatch,
119 format!("类型不匹配:{} → {}", out.ty.label(), inp.ty.label()),
120 ));
121 }
122 if self.check_scope {
123 let pa = graph.node(out.node).and_then(|n| n.parent);
124 let pb = graph.node(inp.node).and_then(|n| n.parent);
125 let boundary = out.scope == PortScope::Boundary || inp.scope == PortScope::Boundary;
126 if pa != pb && !boundary {
127 return Err(ConnectError::new(
128 C::ScopeMismatch,
129 "只能连接同一分组内的节点",
130 ));
131 }
132 }
133 let live = |e: &&EdgeId| Some(**e) != replacing;
134 if graph
135 .edges_of_port(from)
136 .iter()
137 .filter(live)
138 .filter_map(|e| graph.edge(*e))
139 .any(|e| e.to == to)
140 {
141 return Err(ConnectError::new(C::AlreadyConnected, "这两个端口已经相连"));
142 }
143 if let Some(max) = inp.max_connections
144 && graph.edges_of_port(to).iter().filter(live).count() >= max
145 {
146 return Err(ConnectError::new(C::PortFull, "输入端口已被占用"));
147 }
148 if let Some(max) = out.max_connections
149 && graph.edges_of_port(from).iter().filter(live).count() >= max
150 {
151 return Err(ConnectError::new(C::PortFull, "输出端口连接数已满"));
152 }
153 if !self.allow_cycles && graph.would_create_cycle(out.node, inp.node) {
154 return Err(ConnectError::new(C::WouldCreateCycle, "连接后会形成环"));
155 }
156 Ok(())
157 }
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163 use crate::geometry::{Size2, Vec2};
164 use crate::port::PortType;
165
166 fn code(r: Result<(), ConnectError>) -> Option<ConnectErrorCode> {
167 r.err().map(|e| e.code)
168 }
169
170 #[test]
171 fn rules() {
172 let mut g = Graph::new();
173 let sz = Size2::new(10.0, 10.0);
174 let (_, ai, ao) = g.add_node_with("a", Vec2::ZERO, sz, 1, 1);
175 let (_, bi, bo) = g.add_node_with("b", Vec2::ZERO, sz, 1, 1);
176 let v = DefaultValidator::dag();
177 assert_eq!(code(v.validate(&g, ao[0], bi[0], None)), None);
178 assert_eq!(
179 code(v.validate(&g, bi[0], ao[0], None)),
180 Some(ConnectErrorCode::DirectionMismatch)
181 );
182 assert_eq!(
183 code(v.validate(&g, ao[0], ai[0], None)),
184 Some(ConnectErrorCode::SameNode)
185 );
186 let e = g.connect(ao[0], bi[0]).unwrap();
187 assert_eq!(
188 code(v.validate(&g, ao[0], bi[0], None)),
189 Some(ConnectErrorCode::AlreadyConnected)
190 );
191 assert_eq!(
192 code(v.validate(&g, ao[0], bi[0], Some(e))),
193 None,
194 "reconnect ignores old edge"
195 );
196 assert_eq!(
197 code(v.validate(&g, bo[0], ai[0], None)),
198 Some(ConnectErrorCode::WouldCreateCycle)
199 );
200 assert_eq!(
201 code(DefaultValidator::default().validate(&g, bo[0], ai[0], None)),
202 None
203 );
204
205 let (_, ci, _) = g.add_node_with("c", Vec2::ZERO, sz, 1, 0);
206 g.ports.get_mut(&ci[0]).unwrap().ty = PortType::Int;
207 g.ports.get_mut(&bo[0]).unwrap().ty = PortType::String;
208 assert_eq!(
209 code(v.validate(&g, bo[0], ci[0], None)),
210 Some(ConnectErrorCode::TypeMismatch)
211 );
212 let (_, _, do_) = g.add_node_with("d", Vec2::ZERO, sz, 0, 1);
213 g.connect(do_[0], ci[0]).unwrap();
214 g.ports.get_mut(&bo[0]).unwrap().ty = PortType::Int;
215 assert_eq!(
216 code(v.validate(&g, bo[0], ci[0], None)),
217 Some(ConnectErrorCode::PortFull)
218 );
219 }
220
221 #[test]
222 fn scope() {
223 let mut g = Graph::new();
224 let sz = Size2::new(10.0, 10.0);
225 let (group, _, _) = g.add_node_with("group", Vec2::ZERO, sz, 0, 0);
226 let (a, _, ao) = g.add_node_with("a", Vec2::ZERO, sz, 0, 1);
227 let (_, bi, _) = g.add_node_with("b", Vec2::ZERO, sz, 1, 0);
228 g.set_parent(a, Some(group)).unwrap();
229 let v = DefaultValidator::default();
230 assert_eq!(
231 code(v.validate(&g, ao[0], bi[0], None)),
232 Some(ConnectErrorCode::ScopeMismatch)
233 );
234 g.ports.get_mut(&ao[0]).unwrap().scope = PortScope::Boundary;
235 assert_eq!(code(v.validate(&g, ao[0], bi[0], None)), None);
236 }
237}