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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Copyright (c) 2017, 2018 Frank Fischer <frank-fischer@shadow-soft.de>
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>
 */

#![recursion_limit = "256"]

//! This crate provides automatic graph derivations.
//!
//! In order to automatically implement graph traits for
//! a struct that contains the actual graph data structure in a field,
//! add #[derive(Graph)] to the struct. The field containing the graph
//! must either be named `graph` or be attributed with `#[graph]`.
//! All graph traits (`Graph`, `Digraph`, `Network`, `IndexGraph` and
//! `IndexNetwork`) that are implemented for the nested graph, are
//! implemented for the annotated struct, too.
//!
//! # Example
//!
//! ```
//! use rs_graph_derive::Graph;
//! use rs_graph::traits::*;
//! use rs_graph::linkedlistgraph::*;
//! use rs_graph::classes;
//!
//! #[derive(Graph)]
//! struct MyGraph {
//!     #[graph] graph: LinkedListGraph, // #[graph] not need for fields named `graph`.
//!     balances: Vec<f64>,
//!     bounds: Vec<f64>,
//! }
//!
//! impl From<LinkedListGraph> for MyGraph {
//!     fn from(g: LinkedListGraph) -> MyGraph {
//!         let n = g.num_nodes();
//!         let m = g.num_edges();
//!         MyGraph {
//!             graph: g,
//!             balances: vec![0.0; n],
//!             bounds: vec![0.0; m],
//!         }
//!     }
//! }
//!
//! impl MyGraph {
//!     fn balance_mut(&mut self, u: Node) -> &mut f64 {
//!         &mut self.balances[self.graph.node_id(u)]
//!     }
//!
//!     fn bound_mut(&mut self, e: Edge) -> &mut f64 {
//!         &mut self.bounds[self.graph.edge_id(e)]
//!     }
//! }
//!
//! # fn main() {
//! let mut g: MyGraph = classes::path::<LinkedListGraph>(5).into();
//! let (s, t) = (g.id2node(0), g.id2node(4));
//! *g.balance_mut(s) = 1.0;
//! *g.balance_mut(t) = -1.0;
//! for e in g.edges() { *g.bound_mut(e) = g.edge_id(e) as f64; }
//! # }
//! ```

extern crate proc_macro;
use proc_macro2;
use quote::quote;
use syn::{self, parse_quote};

use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;

#[proc_macro_derive(Graph, attributes(graph))]
pub fn graph(input: TokenStream) -> TokenStream {
    let input: TokenStream2 = input.into();
    let mut ast: syn::DeriveInput = syn::parse2(input).unwrap();
    let name = &ast.ident;
    let generics = &mut ast.generics;

    let mut var = None;
    let mut typ = None;

    // Collect all fields with attribute #[graph] or named `graph`.
    #[allow(clippy::block_in_if_condition_stmt)]
    let fields = match ast.data {
        syn::Data::Struct(syn::DataStruct { ref fields, .. }) => fields.iter().enumerate().filter_map(|(i, field)| {
            if field
                .ident
                .as_ref()
                .map(|id| id.to_string())
                .unwrap_or_else(String::new)
                == "graph"
            {
                var = Some(syn::Ident::new("graph", Span::call_site()));
                typ = Some(&field.ty);
                None
            } else if field.attrs.iter().any(|attr| {
                attr.path.segments.len() == 1
                    && attr.path.segments.first().unwrap().into_value().ident
                        == syn::Ident::new("graph", Span::call_site())
            }) {
                Some((
                    field
                        .ident
                        .clone()
                        .unwrap_or_else(|| syn::Ident::new(&format!("{}", i), Span::call_site())),
                    &field.ty,
                ))
            } else {
                None
            }
        }),
        _ => panic!("Only structs containing a graph field can be derived."),
    }
    .collect::<Vec<_>>();

    // Ensure there is a single #[graph] field or (if none exists) a
    // field named `graph`.
    if fields.is_empty() && var.is_none() {
        panic!("No field named `graph` or with #[graph] attribute found");
    } else if fields.len() > 1 {
        panic!(
            "Multiple fields with #[graph] attribute found: {}",
            fields
                .iter()
                .map(|&(ref name, _)| name.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        );
    } else if !fields.is_empty() {
        let field = fields.into_iter().next().unwrap();
        var = Some(field.0);
        typ = Some(field.1);
    }

    // Implement all graph traits the nested graph implements.

    let ty_generics = generics.clone();
    generics.params.push(parse_quote!('a));

    let gens = [
        "GraphType",
        "GraphSize",
        "Undirected",
        "Directed",
        "BiDirected",
        "IndexGraph",
        "IndexNetwork",
    ]
    .iter()
    .map(|name| {
        let name = syn::Ident::new(name, Span::call_site());
        let mut g = generics.clone();
        g.make_where_clause()
            .predicates
            .push(parse_quote!(#typ: ::rs_graph::traits::#name<'a>));
        g
    })
    .collect::<Vec<_>>();

    let (basegraph_impl, _, basegraph_where) = gens[0].split_for_impl();
    let (graphsize_impl, _, graphsize_where) = gens[1].split_for_impl();
    let (undirected_impl, _, undirected_where) = gens[2].split_for_impl();
    let (directed_impl, _, directed_where) = gens[3].split_for_impl();
    let (bidirected_impl, _, bidirected_where) = gens[4].split_for_impl();
    let (indexgraph_impl, _, indexgraph_where) = gens[5].split_for_impl();
    let (indexnetwork_impl, _, indexnetwork_where) = gens[6].split_for_impl();

    let expanded = quote! {
        impl #basegraph_impl ::rs_graph::traits::GraphType<'a> for #name #ty_generics #basegraph_where
        {
            type Node = <#typ as ::rs_graph::traits::GraphType<'a>>::Node;

            type Edge = <#typ as ::rs_graph::traits::GraphType<'a>>::Edge;
        }

        impl #graphsize_impl ::rs_graph::traits::GraphSize<'a> for #name #ty_generics #graphsize_where
        {
            type NodeIter = <#typ as ::rs_graph::traits::GraphSize<'a>>::NodeIter;

            type EdgeIter = <#typ as ::rs_graph::traits::GraphSize<'a>>::EdgeIter;

            fn num_nodes(&self) -> usize {
                self.#var.num_nodes()
            }

            fn num_edges(&self) -> usize {
                self.#var.num_edges()
            }

            fn nodes(&'a self) -> Self::NodeIter {
                self.#var.nodes()
            }

            fn edges(&'a self) -> Self::EdgeIter {
                self.#var.edges()
            }
        }

        impl #undirected_impl ::rs_graph::traits::Undirected<'a> for #name #ty_generics #undirected_where
        {
            type NeighIter = <#typ as ::rs_graph::traits::Undirected<'a>>::NeighIter;

            fn enodes(&'a self, e: Self::Edge) -> (Self::Node, Self::Node) {
                self.#var.enodes(e)
            }

            fn neighs(&'a self, u: Self::Node) -> Self::NeighIter {
                self.#var.neighs(u)
            }
        }

        impl #directed_impl ::rs_graph::traits::Directed<'a> for #name #ty_generics #directed_where
        {
            type OutEdgeIter = <#typ as ::rs_graph::traits::Directed<'a>>::OutEdgeIter;

            type InEdgeIter = <#typ as ::rs_graph::traits::Directed<'a>>::InEdgeIter;

            fn src(&'a self, e: Self::Edge) -> Self::Node {
                self.#var.src(e)
            }

            fn snk(&'a self, e: Self::Edge) -> Self::Node {
                self.#var.snk(e)
            }

            fn outedges(&'a self, u: Self::Node) -> Self::OutEdgeIter {
                self.#var.outedges(u)
            }

            fn inedges(&'a self, u: Self::Node) -> Self::InEdgeIter {
                self.#var.inedges(u)
            }
        }

        impl #bidirected_impl ::rs_graph::traits::BiDirected<'a> for #name #ty_generics #bidirected_where
        {
            fn is_reverse(&self, e: Self::Edge, f: Self::Edge) -> bool {
                self.#var.is_reverse(e, f)
            }

            fn reverse(&'a self, e: Self::Edge) -> Self::Edge {
                self.#var.reverse(e)
            }

            fn is_forward(&self, e: Self::Edge) -> bool {
                self.#var.is_forward(e)
            }

            fn forward(&'a self, e: Self::Edge) -> Self::Edge {
                self.#var.forward(e)
            }

            fn is_backward(&self, e: Self::Edge) -> bool {
                self.#var.is_backward(e)
            }

            fn backward(&'a self, e: Self::Edge) -> Self::Edge {
                self.#var.backward(e)
            }

            fn bisrc(&'a self, e: Self::Edge) -> Self::Node {
                self.#var.bisrc(e)
            }

            fn bisnk(&'a self, e: Self::Edge) -> Self::Node {
                self.#var.bisnk(e)
            }
        }

        impl #indexgraph_impl ::rs_graph::traits::IndexGraph<'a> for #name #ty_generics #indexgraph_where
        {
            fn node_id(&self, u: Self::Node) -> usize {
                self.#var.node_id(u)
            }

            fn id2node(&'a self, id: usize) -> Self::Node {
                self.#var.id2node(id)
            }

            fn edge_id(&self, e: Self::Edge) -> usize {
                self.#var.edge_id(e)
            }

            fn id2edge(&'a self, id: usize) -> Self::Edge {
                self.#var.id2edge(id)
            }
        }

        impl #indexnetwork_impl ::rs_graph::traits::IndexNetwork<'a> for #name #ty_generics #indexnetwork_where
        {
            fn biedge_id(&self, e: Self::Edge) -> usize {
                self.#var.biedge_id(e)
            }

            fn id2biedge(&'a self, id: usize) -> Self::Edge {
                self.#var.id2biedge(id)
            }
        }
    };
    expanded.into()
}