1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! See the [conflagrate](https://docs.rs/conflagrate) documentation for details about the macros
//! contained in this crate.
mod dependency;
mod funcutils;
mod graph;
mod nodetype;

use crate::dependency::dependency_impl;
use crate::graph::graph_impl;
use crate::nodetype::nodetype_impl;
use proc_macro::TokenStream;
use syn::{parse_macro_input, ItemFn};


/// Defines a dependency that can be accessed from any node in the graph.
///
/// Dependencies are resources shared amongst all nodes in a graph.  They can be interfaces to
/// external processes or collections of data shared between disparate parts of the graph.
/// Basically anything a node needs that isn't provided directly by the preceding node should be
/// provided as a dependency.
///
/// # Providers
///
/// Async functions decorated with `#[dependency]` macro construct a dependency that shares the
/// name of the function.  The first time a node that declares that dependency is executed in a
/// graph, the graph will call the provider function and store the returned object in the
/// dependency cache.  The cache is a hash map whose keys are the names of the provider functions
/// and the values are the provided objects.
///
/// # Shared Resources
///
/// Dependencies are only created the first time they are needed.  Every node that names the same
/// dependency gets the same object.  Because multiple nodes can be running simultaneously on
/// separate threads, nodes only receive the dependency as an immutable reference.  If you need
/// mutable access to the dependency, wrap it in a
/// [`tokio::sync::Mutex`](https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html).
///
/// # Examples
/// ```
/// use conflagrate::{dependency, graph, nodetype};
/// use tokio::sync::Mutex;
///
/// #[dependency]
/// async fn messages() -> Mutex<Vec<String>> {
///     Mutex::<Vec<String>>::new(Vec::<String>::new())
/// }
///
/// #[nodetype]
/// pub async fn StoreMessage(messages: &Mutex<Vec<String>>) {
///     messages.lock().await.push(String::from("Hello mutable storage!"));
/// }
///
/// #[nodetype]
/// async fn StoreAnotherMessage(messages: &Mutex<Vec<String>>) {
///     messages.lock().await.push(String::from("Here's another message!"));
/// }
///
/// #[nodetype]
/// pub async fn PrintMessages(messages: &Mutex<Vec<String>>) {
///     for msg in messages.lock().await.iter() {
///         println!("{}", msg);
///     }
/// }
///
/// graph!{
///     digraph MessageGraph {
///         store[type=StoreMessage, start=true];
///         store_another[type=StoreAnotherMessage];
///         print[type=PrintMessages];
///
///         store -> store_another -> print;
///     }
/// }
///
/// fn main() {
///     MessageGraph::run(());
/// }
/// ```
///
/// # See Also
/// * [`nodetype`](macro@nodetype) -- Macro for associating a function with a type of node.
/// Reference types in
/// input arguments are interpreted to be dependencies.
#[proc_macro_attribute]
pub fn dependency(_: TokenStream, func: TokenStream) -> TokenStream {
    TokenStream::from(dependency_impl(parse_macro_input!(func as ItemFn)))
}

/// Defines a block of code to be associated with nodes of a certain type in a graph.
///
/// Each executable node in a graph is given a `type`, which is a non-standard GraphViz attribute
/// that conflagrate associates with a function of the same name passed to the
/// [`nodetype`](macro@nodetype) macro.
///
/// The input of a node is the output of the previous node in the graph (or the graph's input),
/// and the output of the node is the input of the next node in the graph (or the return value of
/// the graph).
///
/// # Blocking Versus Non-Blocking
///
/// Conflagrate applications are built using `tokio`, so `nodetype`s are converted to async
/// functions.  If a regular function is passed into the `nodetype` macro, conflagrate assumes
/// it is blocking and spawns its codeblock in a separate thread.  To avoid spawning extra
/// threads, use `async fn` wherever possible.
///
/// # Visibility (Public Versus Private)
///
/// To facilitate larger projects split into multiple modules, the `run` and `run_graph` methods
/// of [`graph`](macro@graph)s are `pub`.  The arguments to the graph are the input arguments to
/// the first node, and the return value of the graph is the return value of the last possible node,
/// so consequently the `nodetype` functions of those nodes must also be `pub`.
///
/// # Testing
///
/// Under the hood, the `nodetype` function is converted to a struct implementing a trait that
/// provides the function with a uniform call signature so that when it's used with the
/// [`graph`](macro@graph) macro, the graph builder doesn't need to know anything about the shape of
/// your function.  This makes testing more difficult, so your original function is also provided as
/// a `test` method. The `test` method has exactly the same call signature as the original
/// definition.
///
/// ```
/// # use conflagrate::{nodetype};
/// #[nodetype]
/// async fn BusinessLogic(value: u32) -> Result<String, String> {
///     match value {
///         0..=10 => Ok(String::from("good")),
///         _ => Err(String::from("too high!"))
///     }
/// }
///
/// #[cfg(test)]
/// mod tests {
///     # use std::assert_eq;
///     # use super::BusinessLogic;
///     #[test]
///     fn handles_good_values() {
///         assert_eq!(BusinessLogic::test(1), Ok(String::from("good")));
///         assert_eq!(BusinessLogic::test(10), Ok(String::from("good")));
///     }
///
///     #[test]
///     fn bails_on_bad_values() {
///         assert_eq!(BusinessLogic::test(100), Err(String::from("too high!")));
///     }
/// }
/// ```
///
/// # Examples
/// ```no_run
/// # use conflagrate::{graph, nodetype};
/// #[nodetype]
/// pub fn GetName() -> String {
///    let mut name = String::new();
///    println!("Hello, what is your name?");
///    std::io::stdin().read_line(&mut name).unwrap();
///    name.truncate(name.len() - 1);
///    name
/// }
///
/// #[nodetype]
/// pub fn PrintGreeting(name: String) {
///     println!("Hello, {}!", name)
/// }
///
/// graph!{
///     digraph GreetingGraph {
///         get_name[type=GetName, start=true];
///         print_name[type=PrintGreeting];
///
///         get_name -> print_name;
///     }
/// }
///
/// fn main() {
///     GreetingGraph::run(());
/// }
/// ```
///
/// # See Also
/// * [`dependency`](macro@dependency) -- Macro for defining an external resource or data to be used
/// as input by a node in addition to the output of the previous node.
/// * [`graph`](macro@graph) -- Macro for building an executable control flow graph using
/// `nodetype`s.
#[proc_macro_attribute]
pub fn nodetype(_: TokenStream, func: TokenStream) -> TokenStream {
    TokenStream::from(
        nodetype_impl(parse_macro_input!(func as ItemFn))
    )
}

/// Defines the control flow graph of an application.
///
/// The `graph!` macro defines a control flow graph that can be run as a stand-alone application
/// or called as a subgraph from within another graph.  The syntax follows the standard
/// [DOT language](https://graphviz.org) excepting a few new, non-standard attributes that can
/// be applied to nodes and edges that conflagrate uses to construct the executable application
/// logic.
///
/// # Node Attributes
///
/// * `type` -- The [`nodetype`](macro@nodetype) associated with the node the in graph, which is a
/// block of executable code that takes as input the output from the previous node and provides as
/// output the input to the next node.
/// * `start` -- Labels the node to start the graph from.  Only one node may be labeled with the
/// `start` attribute.
/// * `branch` -- Tells conflagrate how to handle a node that has more than one node trailing it in
/// the graph.  May take the following values:
///     * `parallel` (default) -- Conflagrate executes all trailing nodes simultaneously in
/// parallel.  The return value from the node is cloned and passed separately to each tail.  If
/// the `branch` attributed is omitted, this value is assumed.
///     * `matcher` -- Conflagrate executes only one trailing node.  The choice of node depends on
/// the value returned by the `nodetype` function.  Edges tagged with the `value` attribute (see
/// below) are matched against the returned value, and a matching edge determines the following
/// node.  If no matches are found, the edge without a `value` attribute is used as the default.
///
/// # Edge Attributes
///
/// * `value` -- Used with nodes with the `branch=matcher` attribute (see above).  The return value
/// of the matcher node is compared against this (string) value.  If it matches, this edge is
/// followed to determine the next node to be executed in the graph.
///
/// # Examples
///
/// ## Trivial Graph
///
/// A single-node graph that just prints the text `Hello, world!`.
/// ```
/// # use conflagrate::{graph, nodetype};
/// #[nodetype]
/// pub fn HelloWorld() {
///     println!("Hello, world!");
/// }
///
/// graph!{
///     digraph {
///         start[type=HelloWorld, start=true];
///     }
/// }
///
/// fn main() {
///     Graph::run(());
/// }
/// ```
///
/// ## Simple Loop
///
/// A simple loop that asks the user if they wish to exit (type `yes` to exit).
/// ```no_run
/// # use conflagrate::{graph, nodetype};
/// #[nodetype]
/// pub fn AskExit() -> (String, ()) {
///     let mut response = String::new();
///     println!("Exit loop?");
///     std::io::stdin().read_line(&mut response).unwrap();
///     response.truncate(response.len() - 1);
///     (response, ())
/// }
///
/// #[nodetype]
/// pub async fn DoNothing() {}
///
/// graph!{
///     digraph Loop {
///         ask_exit[type=AskExit, branch=matcher, start=true];
///         end[type=DoNothing];
///
///         ask_exit -> end [value=yes];
///         ask_exit -> ask_exit;
///     }
/// }
///
/// fn main() {
///     Loop::run(())
/// }
/// ```
///
/// This graph makes use of the `matcher` branching logic.  The `ask_exit` node has two tails,
/// one that goes to the `end` node with the `value=yes` attribute, and another that goes back to
/// the `ask_exit` node with no attributes.  The matching logic chooses which trailing node to
/// execute next based on the first element in the tuple output from the `AskExit` nodetype
/// function.  The second element of the tuple is then passed as input to the chosen following node.
///
/// # See Also
///
/// * [`nodetype`](macro@nodetype) -- Macro associating functions with nodes.
/// * [`dependency`](macro@nodetype) -- Macro associating a function providing a resource with the
/// name of the function, providing that resource to `nodetype`s that reference them.
#[proc_macro]
pub fn graph(graph: TokenStream) -> TokenStream {
    TokenStream::from(graph_impl(graph.to_string()))
}