Skip to main content

dfir_lang/graph/
mod.rs

1//! Graph representation stages for DFIR graphs.
2
3use std::borrow::Cow;
4use std::hash::Hash;
5
6use proc_macro2::{Ident, Span, TokenStream};
7use quote::ToTokens;
8use serde::{Deserialize, Serialize};
9use syn::punctuated::Punctuated;
10use syn::spanned::Spanned;
11use syn::{Expr, ExprPath, GenericArgument, Token, Type};
12
13use self::ops::{OperatorConstraints, Persistence};
14use crate::diagnostic::{Diagnostic, Diagnostics, Level};
15use crate::parse::{DfirCode, IndexInt, Operator, PortIndex, Ported, SingletonRef};
16use crate::pretty_span::PrettySpan;
17
18mod di_mul_graph;
19mod eliminate_extra_unions_tees;
20mod flat_graph_builder;
21mod flat_to_partitioned;
22mod graph_write;
23mod meta_graph;
24mod meta_graph_debugging;
25
26use std::fmt::Display;
27
28pub use di_mul_graph::DiMulGraph;
29pub use eliminate_extra_unions_tees::eliminate_extra_unions_tees;
30pub use flat_graph_builder::{FlatGraphBuilder, FlatGraphBuilderOutput};
31pub use flat_to_partitioned::{PartitionError, partition_graph};
32pub use meta_graph::{AsCodeOptions, DfirGraph, WriteConfig, WriteGraphType};
33
34pub use crate::graph_ids::{GraphEdgeId, GraphLoopId, GraphNodeId, GraphSubgraphId};
35
36pub mod graph_algorithms;
37pub mod ops;
38
39impl GraphSubgraphId {
40    /// Generate a deterministic `Ident` for the given subgraph ID.
41    pub fn as_ident(self, span: Span) -> Ident {
42        use slotmap::Key;
43        Ident::new(&format!("sgid_{:?}", self.data()), span)
44    }
45}
46
47impl GraphLoopId {
48    /// Generate a deterministic `Ident` for the given loop ID.
49    pub fn as_ident(self, span: Span) -> Ident {
50        use slotmap::Key;
51        Ident::new(&format!("loop_{:?}", self.data()), span)
52    }
53}
54
55/// Context identifier as a string.
56const CONTEXT: &str = "context";
57/// Runnable DFIR graph object identifier as a string.
58const GRAPH: &str = "df";
59
60const HANDOFF_NODE_STR: &str = "handoff";
61const SINGLETON_SLOT_NODE_STR: &str = "singleton";
62const MODULE_BOUNDARY_NODE_STR: &str = "module_boundary";
63
64mod serde_syn {
65    use serde::{Deserialize, Deserializer, Serializer};
66
67    pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
68    where
69        S: Serializer,
70        T: quote::ToTokens,
71    {
72        serializer.serialize_str(&value.to_token_stream().to_string())
73    }
74
75    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
76    where
77        D: Deserializer<'de>,
78        T: syn::parse::Parse,
79    {
80        let s = String::deserialize(deserializer)?;
81        syn::parse_str(&s).map_err(<D::Error as serde::de::Error>::custom)
82    }
83}
84
85/// A variable name assigned to a pipeline in DFIR syntax.
86///
87/// Fundamentally a serializable/deserializable wrapper around [`syn::Ident`].
88#[derive(Clone, Debug, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash)]
89pub struct Varname(#[serde(with = "serde_syn")] pub Ident);
90
91/// The kind of inter-subgraph handoff.
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
93pub enum HandoffKind {
94    /// A `Vec<T>` buffer for streams (zero or more items).
95    Vec,
96    /// An `Option<T>` slot for singletons (exactly one item expected).
97    /// `#varname` gives `&T` (panics if empty).
98    Singleton,
99    /// An `Option<T>` slot for optionals (zero or one item).
100    /// `#varname` gives `&Option<T>`.
101    Optional,
102}
103
104/// A node, corresponding to an operator or a handoff.
105#[derive(Clone, Serialize, Deserialize)]
106pub enum GraphNode {
107    /// An operator.
108    Operator(#[serde(with = "serde_syn")] Operator),
109    /// An inter-subgraph handoff point for buffering data between subgraphs.
110    Handoff {
111        /// What kind of storage this handoff uses.
112        kind: HandoffKind,
113        /// The span of the input into the handoff.
114        #[serde(skip, default = "Span::call_site")]
115        src_span: Span,
116        /// The span of the output out of the handoff.
117        #[serde(skip, default = "Span::call_site")]
118        dst_span: Span,
119    },
120
121    /// Module Boundary, used for importing modules. Only exists prior to partitioning.
122    ModuleBoundary {
123        /// If this module is an input or output boundary.
124        input: bool,
125
126        /// The span of the import!() expression that imported this module.
127        /// The value of this span when the `ModuleBoundary` node is still inside the module is `Span::call_site()`
128        /// TODO: This could one day reference into the module file itself?
129        #[serde(skip, default = "Span::call_site")]
130        import_expr: Span,
131    },
132}
133impl GraphNode {
134    /// Return the node as a human-readable string.
135    pub fn to_pretty_string(&self) -> Cow<'static, str> {
136        match self {
137            GraphNode::Operator(op) => op.to_pretty_string().into(),
138            GraphNode::Handoff {
139                kind: HandoffKind::Vec,
140                ..
141            } => HANDOFF_NODE_STR.into(),
142            GraphNode::Handoff {
143                kind: HandoffKind::Singleton | HandoffKind::Optional,
144                ..
145            } => SINGLETON_SLOT_NODE_STR.into(),
146            GraphNode::ModuleBoundary { .. } => MODULE_BOUNDARY_NODE_STR.into(),
147        }
148    }
149
150    /// Return the name of the node as a string, excluding parenthesis and op source code.
151    pub fn to_name_string(&self) -> Cow<'static, str> {
152        match self {
153            GraphNode::Operator(op) => op.name_string().into(),
154            GraphNode::Handoff {
155                kind: HandoffKind::Vec,
156                ..
157            } => HANDOFF_NODE_STR.into(),
158            GraphNode::Handoff {
159                kind: HandoffKind::Singleton | HandoffKind::Optional,
160                ..
161            } => SINGLETON_SLOT_NODE_STR.into(),
162            GraphNode::ModuleBoundary { .. } => MODULE_BOUNDARY_NODE_STR.into(),
163        }
164    }
165
166    /// Return the source code span of the node.
167    pub fn span(&self) -> Span {
168        match self {
169            Self::Operator(op) => op.span(),
170            &Self::Handoff {
171                src_span, dst_span, ..
172            } => src_span.join(dst_span).unwrap_or(src_span),
173            Self::ModuleBoundary { import_expr, .. } => *import_expr,
174        }
175    }
176}
177impl std::fmt::Debug for GraphNode {
178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179        match self {
180            Self::Operator(operator) => {
181                write!(f, "Node::Operator({} span)", PrettySpan(operator.span()))
182            }
183            Self::Handoff { kind, .. } => write!(f, "Node::Handoff({kind:?})"),
184            Self::ModuleBoundary { input, .. } => {
185                write!(f, "Node::ModuleBoundary{{input: {}}}", input)
186            }
187        }
188    }
189}
190
191/// Meta-data relating to operators which may be useful throughout the compilation process.
192///
193/// This data can be generated from the graph, but it is useful to have it readily available
194/// pre-computed as many algorithms use the same info. Stuff like port names, arguments, and the
195/// [`OperatorConstraints`] for the operator.
196///
197/// Because it is derived from the graph itself, there can be "cache invalidation"-esque issues
198/// if this data is not kept in sync with the graph.
199#[derive(Clone, Debug)]
200pub struct OperatorInstance {
201    /// Name of the operator (will match [`OperatorConstraints::name`]).
202    pub op_constraints: &'static OperatorConstraints,
203    /// Port values used as this operator's input.
204    pub input_ports: Vec<PortIndexValue>,
205    /// Port values used as this operator's output.
206    pub output_ports: Vec<PortIndexValue>,
207    /// Singleton references within the operator arguments.
208    pub singletons_referenced: Vec<SingletonRef>,
209
210    /// Generic arguments.
211    pub generics: OpInstGenerics,
212    /// Arguments provided by the user into the operator as arguments.
213    /// I.e. the `a, b, c` in `-> my_op(a, b, c) -> `.
214    ///
215    /// These arguments do not include singleton postprocessing codegen. Instead use
216    /// [`ops::WriteContextArgs::arguments`].
217    pub arguments_pre: Punctuated<Expr, Token![,]>,
218    /// Unparsed arguments, for singleton parsing.
219    pub arguments_raw: TokenStream,
220}
221
222/// Operator generic arguments, split into specific categories.
223#[derive(Clone, Debug)]
224pub struct OpInstGenerics {
225    /// Operator generic (type or lifetime) arguments.
226    pub generic_args: Option<Punctuated<GenericArgument, Token![,]>>,
227    /// Lifetime persistence arguments. Corresponds to a prefix of [`Self::generic_args`].
228    pub persistence_args: Vec<Persistence>,
229    /// Type persistence arguments. Corersponds to a (suffix) of [`Self::generic_args`].
230    pub type_args: Vec<Type>,
231}
232
233impl OpInstGenerics {
234    /// Helper to join a sequence of spans into a single span, if possible.
235    ///
236    /// Returns `None` if there are no spans or if any `Span::join` call fails
237    /// (for example, when spans are not contiguous).
238    fn join_spans<I>(mut spans: I) -> Option<Span>
239    where
240        I: Iterator<Item = Span>,
241    {
242        let mut span = spans.next()?;
243        for s in spans {
244            span = span.join(s)?;
245        }
246        Some(span)
247    }
248
249    /// Returns a [`Span`] containing all persistence (lifetime) args if possible.
250    pub fn persistence_args_span(&self) -> Option<Span> {
251        self.generic_args.as_ref().and_then(|args| {
252            Self::join_spans(
253                args.iter()
254                    .filter(|a| matches!(a, GenericArgument::Lifetime(_)))
255                    .map(|a| a.span()),
256            )
257        })
258    }
259
260    /// Returns a [`Span`] containing all type args if possible.
261    pub fn type_args_span(&self) -> Option<Span> {
262        self.generic_args.as_ref().and_then(|args| {
263            Self::join_spans(
264                args.iter()
265                    .filter(|a| matches!(a, GenericArgument::Type(_)))
266                    .map(|a| a.span()),
267            )
268        })
269    }
270}
271
272/// Gets the generic arguments for the operator.
273///
274/// This helper method is useful due to the special handling of persistence lifetimes (`'static`,
275/// `'tick`) which must come before other generic parameters.
276pub fn get_operator_generics(diagnostics: &mut Diagnostics, operator: &Operator) -> OpInstGenerics {
277    // Generic arguments.
278    let generic_args = operator.type_arguments().cloned();
279    // Leading lifetimes are the persistence prefix. A non-lifetime ends that prefix.
280    // An unknown lifetime is reported and not stored, but does not end the prefix, so
281    // following type arguments are still collected and checked.
282    let mut persistence_prefix_len = 0usize;
283    let persistence_args = generic_args
284        .iter()
285        .flatten()
286        .map_while(|generic_arg| match generic_arg {
287            GenericArgument::Lifetime(lifetime) => Some((generic_arg, lifetime)),
288            _ => None,
289        })
290        .filter_map(|(generic_arg, lifetime)| {
291            // Every leading lifetime counts, including ones that are not `'tick` or `'static`.
292            persistence_prefix_len += 1;
293            match &*lifetime.ident.to_string() {
294                "tick" => Some(Persistence::Tick),
295                "static" => Some(Persistence::Static),
296                _ => {
297                    diagnostics.push(Diagnostic::spanned(
298                        generic_arg.span(),
299                        Level::Error,
300                        format!(
301                            "Unknown lifetime generic argument `'{}`, expected `'tick` or `'static`.",
302                            lifetime.ident
303                        ),
304                    ));
305                    None
306                }
307            }
308        })
309        .collect::<Vec<_>>();
310
311    // Types are collected only until the first non-type. Anything after that, including a
312    // type that shows up later, is a spanned error instead of being dropped by `map_while`.
313    let unexpected_after_types = |generic_arg: &GenericArgument| {
314        let message = if let GenericArgument::Lifetime(lifetime) = generic_arg {
315            format!(
316                "Unexpected lifetime `'{}` after a type argument. \
317                 Persistence lifetimes (`'tick`, `'static`) must come before type arguments.",
318                lifetime.ident
319            )
320        } else {
321            "Unexpected generic argument. \
322             Persistence lifetimes (`'tick`, `'static`) must come before type arguments."
323                .to_owned()
324        };
325        Diagnostic::spanned(generic_arg.span(), Level::Error, message)
326    };
327    let mut after_prefix = generic_args.iter().flatten().skip(persistence_prefix_len);
328    let type_args = after_prefix
329        .by_ref()
330        .map_while(|generic_arg| {
331            if let GenericArgument::Type(typ) = generic_arg {
332                Some(typ)
333            } else {
334                diagnostics.push(unexpected_after_types(generic_arg));
335                None
336            }
337        })
338        .cloned()
339        .collect::<Vec<_>>();
340    for generic_arg in after_prefix {
341        diagnostics.push(unexpected_after_types(generic_arg));
342    }
343
344    OpInstGenerics {
345        generic_args,
346        persistence_args,
347        type_args,
348    }
349}
350
351/// Push, Pull, Comp, or Hoff polarity.
352#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
353pub enum Color {
354    /// Pull (green)
355    Pull,
356    /// Push (blue)
357    Push,
358    /// Computation (yellow)
359    Comp,
360    /// Handoff (grey) -- not a color for operators, inserted between subgraphs.
361    Hoff,
362}
363
364/// Helper struct for [`PortIndex`] which keeps span information for elided ports.
365#[derive(Clone, Debug, Serialize, Deserialize)]
366pub enum PortIndexValue {
367    /// An integer value: `[0]`, `[1]`, etc. Can be negative although we don't use that (2023-08-16).
368    Int(#[serde(with = "serde_syn")] IndexInt),
369    /// A name or path. `[pos]`, `[neg]`, etc. Can use `::` separators but we don't use that (2023-08-16).
370    Path(#[serde(with = "serde_syn")] ExprPath),
371    /// Elided, unspecified port. We have this variant, rather than wrapping in `Option`, in order
372    /// to preserve the `Span` information.
373    Elided(#[serde(skip)] Option<Span>),
374}
375impl PortIndexValue {
376    /// For a [`Ported`] value like `[port_in]name[port_out]`, get the `port_in` and `port_out` as
377    /// [`PortIndexValue`]s.
378    pub fn from_ported<Inner>(ported: Ported<Inner>) -> (Self, Inner, Self)
379    where
380        Inner: Spanned,
381    {
382        let ported_span = Some(ported.inner.span());
383        let port_inn = ported
384            .inn
385            .map(|idx| idx.index.into())
386            .unwrap_or_else(|| Self::Elided(ported_span));
387        let inner = ported.inner;
388        let port_out = ported
389            .out
390            .map(|idx| idx.index.into())
391            .unwrap_or_else(|| Self::Elided(ported_span));
392        (port_inn, inner, port_out)
393    }
394
395    /// Returns `true` if `self` is not [`PortIndexValue::Elided`].
396    pub fn is_specified(&self) -> bool {
397        !matches!(self, Self::Elided(_))
398    }
399
400    /// Returns whichever of the two ports are specified.
401    /// If both are [`Self::Elided`], returns [`Self::Elided`].
402    /// If both are specified, returns `Err(self)`.
403    #[allow(clippy::allow_attributes, reason = "Only triggered on nightly.")]
404    #[allow(
405        clippy::result_large_err,
406        reason = "variants are same size, error isn't to be propagated."
407    )]
408    pub fn combine(self, other: Self) -> Result<Self, Self> {
409        match (self.is_specified(), other.is_specified()) {
410            (false, _other) => Ok(other),
411            (true, false) => Ok(self),
412            (true, true) => Err(self),
413        }
414    }
415
416    /// Formats self as a human-readable string for error messages.
417    pub fn as_error_message_string(&self) -> String {
418        match self {
419            PortIndexValue::Int(n) => format!("`{}`", n.value),
420            PortIndexValue::Path(path) => format!("`{}`", path.to_token_stream()),
421            PortIndexValue::Elided(_) => "<elided>".to_owned(),
422        }
423    }
424
425    /// Returns the span of this port value.
426    pub fn span(&self) -> Span {
427        match self {
428            PortIndexValue::Int(x) => x.span(),
429            PortIndexValue::Path(x) => x.span(),
430            PortIndexValue::Elided(span) => span.unwrap_or_else(Span::call_site),
431        }
432    }
433}
434impl From<PortIndex> for PortIndexValue {
435    fn from(value: PortIndex) -> Self {
436        match value {
437            PortIndex::Int(x) => Self::Int(x),
438            PortIndex::Path(x) => Self::Path(x),
439        }
440    }
441}
442impl PartialEq for PortIndexValue {
443    fn eq(&self, other: &Self) -> bool {
444        match (self, other) {
445            (Self::Int(l0), Self::Int(r0)) => l0 == r0,
446            (Self::Path(l0), Self::Path(r0)) => l0 == r0,
447            (Self::Elided(_), Self::Elided(_)) => true,
448            _else => false,
449        }
450    }
451}
452impl Eq for PortIndexValue {}
453impl PartialOrd for PortIndexValue {
454    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
455        Some(self.cmp(other))
456    }
457}
458impl Ord for PortIndexValue {
459    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
460        match (self, other) {
461            (Self::Int(s), Self::Int(o)) => s.cmp(o),
462            (Self::Path(s), Self::Path(o)) => s
463                .to_token_stream()
464                .to_string()
465                .cmp(&o.to_token_stream().to_string()),
466            (Self::Elided(_), Self::Elided(_)) => std::cmp::Ordering::Equal,
467            (Self::Int(_), Self::Path(_)) => std::cmp::Ordering::Less,
468            (Self::Path(_), Self::Int(_)) => std::cmp::Ordering::Greater,
469            (_, Self::Elided(_)) => std::cmp::Ordering::Less,
470            (Self::Elided(_), _) => std::cmp::Ordering::Greater,
471        }
472    }
473}
474
475impl Display for PortIndexValue {
476    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477        match self {
478            PortIndexValue::Int(x) => write!(f, "{}", x.to_token_stream()),
479            PortIndexValue::Path(x) => write!(f, "{}", x.to_token_stream()),
480            PortIndexValue::Elided(_) => write!(f, "[]"),
481        }
482    }
483}
484
485/// Output of [`build_dfir_code`].
486pub struct BuildDfirCodeOutput {
487    /// The now-partitioned graph.
488    pub partitioned_graph: DfirGraph,
489    /// The Rust source code tokens for the DFIR.
490    pub code: TokenStream,
491    /// Any (non-error) diagnostics emitted.
492    pub diagnostics: Diagnostics,
493}
494
495/// Compiles a [`DfirCode`] AST into inline source code that runs the dataflow.
496pub fn build_dfir_code(
497    dfir_code: DfirCode,
498    root: &TokenStream,
499) -> Result<BuildDfirCodeOutput, Diagnostics> {
500    let flat_graph_builder = FlatGraphBuilder::from_dfir(dfir_code);
501
502    let FlatGraphBuilderOutput {
503        mut flat_graph,
504        uses,
505        mut diagnostics,
506    } = flat_graph_builder.build()?;
507
508    let () = match flat_graph.merge_modules() {
509        Ok(()) => (),
510        Err(d) => {
511            diagnostics.push(d);
512            return Err(diagnostics);
513        }
514    };
515
516    eliminate_extra_unions_tees(&mut flat_graph);
517
518    // Detect adjacent handoffs (e.g. `handoff() -> handoff()` or `singleton() -> singleton()`),
519    // which can arise after unary tee/union elimination.
520    for (edge_id, (src, dst)) in flat_graph.edges() {
521        let _ = edge_id;
522        if matches!(flat_graph.node(src), GraphNode::Handoff { .. })
523            && matches!(flat_graph.node(dst), GraphNode::Handoff { .. })
524        {
525            let span = flat_graph.node(dst).span();
526            diagnostics.push(Diagnostic::spanned(
527                span,
528                Level::Error,
529                "Adjacent handoff/singleton operators are not allowed. \
530                 Remove one or insert an operator between them.",
531            ));
532        }
533    }
534
535    if diagnostics.has_error() {
536        return Err(diagnostics);
537    }
538
539    let partitioned_graph = match partition_graph(flat_graph) {
540        Ok(partitioned_graph) => partitioned_graph,
541        Err(err) => {
542            diagnostics.push(err.diagnostic);
543            return Err(diagnostics);
544        }
545    };
546
547    let code = partitioned_graph.as_code_with_options(
548        root,
549        &AsCodeOptions {
550            // Macro users (`dfir_syntax!`) have no way to configure codegen options, so keep
551            // runtime metrics tracking enabled for them (`Dfir::metrics()` should always work).
552            include_metrics_tracking: true,
553            ..Default::default()
554        },
555        quote::quote! { #( #uses )* },
556        &mut diagnostics,
557    )?;
558
559    Ok(BuildDfirCodeOutput {
560        partitioned_graph,
561        code,
562        diagnostics,
563    })
564}
565
566/// Changes all of token's spans to `span`, recursing into groups.
567fn change_spans(tokens: TokenStream, span: Span) -> TokenStream {
568    use proc_macro2::{Group, TokenTree};
569    tokens
570        .into_iter()
571        .map(|token| match token {
572            TokenTree::Group(mut group) => {
573                group.set_span(span);
574                TokenTree::Group(Group::new(
575                    group.delimiter(),
576                    change_spans(group.stream(), span),
577                ))
578            }
579            TokenTree::Ident(mut ident) => {
580                ident.set_span(span.resolved_at(ident.span()));
581                TokenTree::Ident(ident)
582            }
583            TokenTree::Punct(mut punct) => {
584                punct.set_span(span);
585                TokenTree::Punct(punct)
586            }
587            TokenTree::Literal(mut literal) => {
588                literal.set_span(span);
589                TokenTree::Literal(literal)
590            }
591        })
592        .collect()
593}