1use std::borrow::Cow;
4use std::hash::Hash;
5
6use proc_macro2::{Ident, Span, TokenStream};
7use quote::ToTokens;
8use serde::{Deserialize, Serialize};
9use slotmap::new_key_type;
10use syn::punctuated::Punctuated;
11use syn::spanned::Spanned;
12use syn::{Expr, ExprPath, GenericArgument, Token, Type};
13
14use self::ops::{OperatorConstraints, Persistence};
15use crate::diagnostic::{Diagnostic, Level};
16use crate::parse::{DfirCode, IndexInt, Operator, PortIndex, Ported};
17use crate::pretty_span::PrettySpan;
18
19mod di_mul_graph;
20mod eliminate_extra_unions_tees;
21mod flat_graph_builder;
22mod flat_to_partitioned;
23mod graph_write;
24mod meta_graph;
25mod meta_graph_debugging;
26
27use std::fmt::Display;
28
29pub use di_mul_graph::DiMulGraph;
30pub use eliminate_extra_unions_tees::eliminate_extra_unions_tees;
31pub use flat_graph_builder::FlatGraphBuilder;
32pub use flat_to_partitioned::partition_graph;
33pub use meta_graph::{DfirGraph, WriteConfig, WriteGraphType};
34
35pub mod graph_algorithms;
36pub mod ops;
37
38new_key_type! {
39 pub struct GraphNodeId;
41
42 pub struct GraphEdgeId;
44
45 pub struct GraphSubgraphId;
47
48 pub struct GraphLoopId;
50}
51
52impl GraphSubgraphId {
53 pub fn as_ident(self, span: Span) -> Ident {
55 use slotmap::Key;
56 Ident::new(&format!("sgid_{:?}", self.data()), span)
57 }
58}
59
60impl GraphLoopId {
61 pub fn as_ident(self, span: Span) -> Ident {
63 use slotmap::Key;
64 Ident::new(&format!("loop_{:?}", self.data()), span)
65 }
66}
67
68const CONTEXT: &str = "context";
70const GRAPH: &str = "df";
72
73const HANDOFF_NODE_STR: &str = "handoff";
74const MODULE_BOUNDARY_NODE_STR: &str = "module_boundary";
75
76mod serde_syn {
77 use serde::{Deserialize, Deserializer, Serializer};
78
79 pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
80 where
81 S: Serializer,
82 T: quote::ToTokens,
83 {
84 serializer.serialize_str(&value.to_token_stream().to_string())
85 }
86
87 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
88 where
89 D: Deserializer<'de>,
90 T: syn::parse::Parse,
91 {
92 let s = String::deserialize(deserializer)?;
93 syn::parse_str(&s).map_err(<D::Error as serde::de::Error>::custom)
94 }
95}
96
97#[derive(Clone, Debug, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
98struct Varname(#[serde(with = "serde_syn")] pub Ident);
99
100#[derive(Clone, Serialize, Deserialize)]
102pub enum GraphNode {
103 Operator(#[serde(with = "serde_syn")] Operator),
105 Handoff {
107 #[serde(skip, default = "Span::call_site")]
109 src_span: Span,
110 #[serde(skip, default = "Span::call_site")]
112 dst_span: Span,
113 },
114
115 ModuleBoundary {
117 input: bool,
119
120 #[serde(skip, default = "Span::call_site")]
124 import_expr: Span,
125 },
126}
127impl GraphNode {
128 pub fn to_pretty_string(&self) -> Cow<'static, str> {
130 match self {
131 GraphNode::Operator(op) => op.to_pretty_string().into(),
132 GraphNode::Handoff { .. } => HANDOFF_NODE_STR.into(),
133 GraphNode::ModuleBoundary { .. } => MODULE_BOUNDARY_NODE_STR.into(),
134 }
135 }
136
137 pub fn to_name_string(&self) -> Cow<'static, str> {
139 match self {
140 GraphNode::Operator(op) => op.name_string().into(),
141 GraphNode::Handoff { .. } => HANDOFF_NODE_STR.into(),
142 GraphNode::ModuleBoundary { .. } => MODULE_BOUNDARY_NODE_STR.into(),
143 }
144 }
145
146 pub fn span(&self) -> Span {
148 match self {
149 Self::Operator(op) => op.span(),
150 &Self::Handoff {
151 src_span, dst_span, ..
152 } => src_span.join(dst_span).unwrap_or(src_span),
153 Self::ModuleBoundary { import_expr, .. } => *import_expr,
154 }
155 }
156}
157impl std::fmt::Debug for GraphNode {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 match self {
160 Self::Operator(operator) => {
161 write!(f, "Node::Operator({} span)", PrettySpan(operator.span()))
162 }
163 Self::Handoff { .. } => write!(f, "Node::Handoff"),
164 Self::ModuleBoundary { input, .. } => {
165 write!(f, "Node::ModuleBoundary{{input: {}}}", input)
166 }
167 }
168 }
169}
170
171#[derive(Clone, Debug)]
180pub struct OperatorInstance {
181 pub op_constraints: &'static OperatorConstraints,
183 pub input_ports: Vec<PortIndexValue>,
185 pub output_ports: Vec<PortIndexValue>,
187 pub singletons_referenced: Vec<Ident>,
189
190 pub generics: OpInstGenerics,
192 pub arguments_pre: Punctuated<Expr, Token![,]>,
198 pub arguments_raw: TokenStream,
200}
201
202#[derive(Clone, Debug)]
204pub struct OpInstGenerics {
205 pub generic_args: Option<Punctuated<GenericArgument, Token![,]>>,
207 pub persistence_args: Vec<Persistence>,
209 pub type_args: Vec<Type>,
211}
212
213pub fn get_operator_generics(
218 diagnostics: &mut Vec<Diagnostic>,
219 operator: &Operator,
220) -> OpInstGenerics {
221 let generic_args = operator.type_arguments().cloned();
223 let persistence_args = generic_args.iter().flatten().map_while(|generic_arg| match generic_arg {
224 GenericArgument::Lifetime(lifetime) => {
225 match &*lifetime.ident.to_string() {
226 "none" => Some(Persistence::None),
227 "loop" => Some(Persistence::Loop),
228 "tick" => Some(Persistence::Tick),
229 "static" => Some(Persistence::Static),
230 "mutable" => Some(Persistence::Mutable),
231 _ => {
232 diagnostics.push(Diagnostic::spanned(
233 generic_arg.span(),
234 Level::Error,
235 format!("Unknown lifetime generic argument `'{}`, expected `'none`, `'loop`, `'tick`, `'static`, or `'mutable`.", lifetime.ident),
236 ));
237 None
239 }
240 }
241 },
242 _ => None,
243 }).collect::<Vec<_>>();
244 let type_args = generic_args
245 .iter()
246 .flatten()
247 .skip(persistence_args.len())
248 .map_while(|generic_arg| match generic_arg {
249 GenericArgument::Type(typ) => Some(typ),
250 _ => None,
251 })
252 .cloned()
253 .collect::<Vec<_>>();
254
255 OpInstGenerics {
256 generic_args,
257 persistence_args,
258 type_args,
259 }
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
264pub enum Color {
265 Pull,
267 Push,
269 Comp,
271 Hoff,
273}
274
275#[derive(Clone, Debug, Serialize, Deserialize)]
277pub enum PortIndexValue {
278 Int(#[serde(with = "serde_syn")] IndexInt),
280 Path(#[serde(with = "serde_syn")] ExprPath),
282 Elided(#[serde(skip)] Option<Span>),
285}
286impl PortIndexValue {
287 pub fn from_ported<Inner>(ported: Ported<Inner>) -> (Self, Inner, Self)
290 where
291 Inner: Spanned,
292 {
293 let ported_span = Some(ported.inner.span());
294 let port_inn = ported
295 .inn
296 .map(|idx| idx.index.into())
297 .unwrap_or_else(|| Self::Elided(ported_span));
298 let inner = ported.inner;
299 let port_out = ported
300 .out
301 .map(|idx| idx.index.into())
302 .unwrap_or_else(|| Self::Elided(ported_span));
303 (port_inn, inner, port_out)
304 }
305
306 pub fn is_specified(&self) -> bool {
308 !matches!(self, Self::Elided(_))
309 }
310
311 #[allow(clippy::allow_attributes, reason = "Only triggered on nightly.")]
315 #[allow(
316 clippy::result_large_err,
317 reason = "variants are same size, error isn't to be propagated."
318 )]
319 pub fn combine(self, other: Self) -> Result<Self, Self> {
320 match (self.is_specified(), other.is_specified()) {
321 (false, _other) => Ok(other),
322 (true, false) => Ok(self),
323 (true, true) => Err(self),
324 }
325 }
326
327 pub fn as_error_message_string(&self) -> String {
329 match self {
330 PortIndexValue::Int(n) => format!("`{}`", n.value),
331 PortIndexValue::Path(path) => format!("`{}`", path.to_token_stream()),
332 PortIndexValue::Elided(_) => "<elided>".to_owned(),
333 }
334 }
335
336 pub fn span(&self) -> Span {
338 match self {
339 PortIndexValue::Int(x) => x.span(),
340 PortIndexValue::Path(x) => x.span(),
341 PortIndexValue::Elided(span) => span.unwrap_or_else(Span::call_site),
342 }
343 }
344}
345impl From<PortIndex> for PortIndexValue {
346 fn from(value: PortIndex) -> Self {
347 match value {
348 PortIndex::Int(x) => Self::Int(x),
349 PortIndex::Path(x) => Self::Path(x),
350 }
351 }
352}
353impl PartialEq for PortIndexValue {
354 fn eq(&self, other: &Self) -> bool {
355 match (self, other) {
356 (Self::Int(l0), Self::Int(r0)) => l0 == r0,
357 (Self::Path(l0), Self::Path(r0)) => l0 == r0,
358 (Self::Elided(_), Self::Elided(_)) => true,
359 _else => false,
360 }
361 }
362}
363impl Eq for PortIndexValue {}
364impl PartialOrd for PortIndexValue {
365 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
366 Some(self.cmp(other))
367 }
368}
369impl Ord for PortIndexValue {
370 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
371 match (self, other) {
372 (Self::Int(s), Self::Int(o)) => s.cmp(o),
373 (Self::Path(s), Self::Path(o)) => s
374 .to_token_stream()
375 .to_string()
376 .cmp(&o.to_token_stream().to_string()),
377 (Self::Elided(_), Self::Elided(_)) => std::cmp::Ordering::Equal,
378 (Self::Int(_), Self::Path(_)) => std::cmp::Ordering::Less,
379 (Self::Path(_), Self::Int(_)) => std::cmp::Ordering::Greater,
380 (_, Self::Elided(_)) => std::cmp::Ordering::Less,
381 (Self::Elided(_), _) => std::cmp::Ordering::Greater,
382 }
383 }
384}
385
386impl Display for PortIndexValue {
387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388 match self {
389 PortIndexValue::Int(x) => write!(f, "{}", x.to_token_stream()),
390 PortIndexValue::Path(x) => write!(f, "{}", x.to_token_stream()),
391 PortIndexValue::Elided(_) => write!(f, "[]"),
392 }
393 }
394}
395
396pub fn build_hfcode(
399 hf_code: DfirCode,
400 root: &TokenStream,
401) -> (Option<(DfirGraph, TokenStream)>, Vec<Diagnostic>) {
402 let flat_graph_builder = FlatGraphBuilder::from_dfir(hf_code);
403 let (mut flat_graph, uses, mut diagnostics) = flat_graph_builder.build();
404 if !diagnostics.iter().any(Diagnostic::is_error) {
405 if let Err(diagnostic) = flat_graph.merge_modules() {
406 diagnostics.push(diagnostic);
407 return (None, diagnostics);
408 }
409
410 eliminate_extra_unions_tees(&mut flat_graph);
411 match partition_graph(flat_graph) {
412 Ok(partitioned_graph) => {
413 let code = partitioned_graph.as_code(
414 root,
415 true,
416 quote::quote! { #( #uses )* },
417 &mut diagnostics,
418 );
419 if !diagnostics.iter().any(Diagnostic::is_error) {
420 return (Some((partitioned_graph, code)), diagnostics);
422 }
423 }
424 Err(diagnostic) => diagnostics.push(diagnostic),
425 }
426 }
427 (None, diagnostics)
428}
429
430fn change_spans(tokens: TokenStream, span: Span) -> TokenStream {
432 use proc_macro2::{Group, TokenTree};
433 tokens
434 .into_iter()
435 .map(|token| match token {
436 TokenTree::Group(mut group) => {
437 group.set_span(span);
438 TokenTree::Group(Group::new(
439 group.delimiter(),
440 change_spans(group.stream(), span),
441 ))
442 }
443 TokenTree::Ident(mut ident) => {
444 ident.set_span(span.resolved_at(ident.span()));
445 TokenTree::Ident(ident)
446 }
447 TokenTree::Punct(mut punct) => {
448 punct.set_span(span);
449 TokenTree::Punct(punct)
450 }
451 TokenTree::Literal(mut literal) => {
452 literal.set_span(span);
453 TokenTree::Literal(literal)
454 }
455 })
456 .collect()
457}