bgpsim_macros/lib.rs
1// BgpSim: BGP Network Simulator written in Rust
2// Copyright 2022-2023 Tibor Schneider <sctibor@ethz.ch>
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#![doc(html_logo_url = "https://bgpsim.github.io/dark_only.svg")]
17
18use proc_macro::TokenStream;
19
20mod formatter;
21mod ip;
22mod net;
23use ip::PrefixInput;
24use net::Net;
25use syn::parse_macro_input;
26
27/// Create a `Network` using a domain specific language. This proc-macro will check at compile time
28/// that all invariants are satisfied.
29///
30/// # Syntax
31/// The content can contain the following parts:
32///
33/// - `links`: An enumeration of links in the network. Each link is written as `SRC -> DST: WEIGHT`,
34/// where both `SRC` and `DST` are identifiers of a node, and `WEIGHT` is a number defining the
35/// weight. By default, this notation will automatically create the link, and set the link weight
36/// in both directions. However, you can also set the link weight in the opposite direction by
37/// writing `DST -> SRC: WEIGHT`.
38///
39/// - `sessions`: An enumeration of all BGP sessions in the network. Each session is written as `SRC
40/// -> DST[: TYPE]`, where both `SRC` and `DST` are identifiers of a node. The `TYPE` is optiona,
41/// and can be omitted. If the type is omitted, then it will be a `BgpSessionType::IBgpPeer` for
42/// internal sessions, and `BgpSessionType::EBgp` for external sessions. The `TYPE` can be one of
43/// the following identifiers:
44///
45/// - `ebgp`, which maps to `BgpSessionType::EBgp`,
46/// - `peer`, which maps to `BgpSessionType::IBgpPeer`,
47/// - `client`, which maps to `BgpSessionType::IBgpClient`.
48///
49/// This macro will **automatically add links between nodes for external sessions** if they are
50/// not already defined in `links`.
51///
52/// - `default_asn`: The default ASN that is used when no AS number is given otherwise.
53///
54/// - `routes`: An enumeration of all BGP announcements from external routers. Each announcement is
55/// written as `SRC -> PREFIX as {path: P, [med: M], [communities: C]}`. The symbols mean the
56/// following:
57/// - `SRC` is the external router that announces the prefix.
58/// - `PREFIX` is the prefix that should be announced. The prefix can either be a number, a string
59/// containing an IP prefix (see [`prefix!`]), or an identifier of a local variable that was
60/// already defined earlier.
61/// - `P` is the AS path and is required. It can be either a single number (which will be turned
62/// into a path of length 1), an array of numbers representing the path, or any other arbitrary
63/// expression that evaluates to `impl Iterator<Item = I> where I: Into<AsId>`.
64/// - `M` is the MED value but is optional. If omitted, then the MED value will not be set in the
65/// announcement. `M` must be either a number, or an expression that evaluates to `Option<u32>`.
66/// - `C` is the set of communities present in the route, and is optional. Similar to `P`, it can
67/// also either take a single number, an array of numbers, or any other arbitrary expression
68/// that evaluates to `impl Iterator<Item = I> where I: Into<u32>`.
69///
70/// - `Prefix`: The type of the prefix. Choose either `SinglePrefix`, `SimplePrefix`, or
71/// `Ipv4Prefix` here (optional).
72///
73/// - `Queue`: The type of the queue (optional).
74///
75/// - `queue`: The expression to create the empty queue. If no queue is provided, then the expanded
76/// macro will use `Default::default()`.
77///
78/// - `return`: A nested tuple of identifiers that referr to previously defined nodes.
79///
80/// # Defining Routers
81/// Every node identifier can also be written like a function invocation by appending a `(ASN)`,
82/// where `ASN` is a literal number. This must be done for each node at least once in the macro
83/// invocation (must not be the first time) to define the AS number. Alternatively, you can also set
84/// the default ASN by adding `default_asn = ASN` somewhere.
85///
86/// # Example
87/// ```rust
88/// use bgpsim::prelude::*;
89///
90/// let (net, ((b0, b1), (e0, e1))) = net! {
91/// Prefix = Ipv4Prefix;
92/// default_asn: 100;
93/// links = {
94/// b0 -> r0: 1;
95/// r0 -> r1: 1;
96/// r1 -> b1: 1;
97/// };
98/// sessions = {
99/// b1 -> e1(1);
100/// b0 -> e0(2);
101/// r0 -> r1: peer;
102/// r0 -> b0: client;
103/// r1 -> b1: client;
104/// };
105/// routes = {
106/// e0 -> "10.0.0.0/8" as {path: [1, 3, 4], med: 100, community: (0x65535, 666)};
107/// e1 -> "10.0.0.0/8" as {path: [2, 4]};
108/// };
109/// return ((b0, b1), (e0, e1))
110/// };
111/// ```
112///
113/// This example will be expanded into the following code. This code was cleaned-up, so the
114/// different parts can be seen better.
115///
116/// ```rust
117/// use bgpsim::prelude::*;
118/// // these imports are added for compactness
119/// use ipnet::Ipv4Net;
120/// use std::net::Ipv4Addr;
121///
122/// let (net, ((b0, b1), (e0, e1))) = {
123/// let mut _net: Network<Ipv4Prefix, _> = Network::new(BasicEventQueue::default());
124/// let b0 = _net.add_router("b0", 100);
125/// let b1 = _net.add_router("b1", 100);
126/// let r0 = _net.add_router("r0", 100);
127/// let r1 = _net.add_router("r1", 100);
128/// let e0 = _net.add_router("e0", 2u32);
129/// let e1 = _net.add_router("e1", 1u32);
130///
131/// _net.add_link(b0, r0);
132/// _net.add_link(r1, b1);
133/// _net.add_link(r0, r1);
134/// _net.add_link(b1, e1);
135/// _net.add_link(b0, e0);
136///
137/// _net.set_link_weight(b0, r0, 1f64).unwrap();
138/// _net.set_link_weight(r0, b0, 1f64).unwrap();
139/// _net.set_link_weight(r1, b1, 1f64).unwrap();
140/// _net.set_link_weight(b1, r1, 1f64).unwrap();
141/// _net.set_link_weight(r0, r1, 1f64).unwrap();
142/// _net.set_link_weight(r1, r0, 1f64).unwrap();
143///
144/// _net.set_bgp_session(b0, e0, Some(BgpSessionType::EBgp)).unwrap();
145/// _net.set_bgp_session(r1, b1, Some(BgpSessionType::IBgpClient)).unwrap();
146/// _net.set_bgp_session(r0, r1, Some(BgpSessionType::IBgpPeer)).unwrap();
147/// _net.set_bgp_session(b1, e1, Some(BgpSessionType::EBgp)).unwrap();
148/// _net.set_bgp_session(r0, b0, Some(BgpSessionType::IBgpClient)).unwrap();
149///
150/// _net.advertise_external_route(
151/// e0,
152/// Ipv4Net::new(Ipv4Addr::new(10, 0, 0, 0),8).unwrap(),
153/// [1, 3, 4],
154/// Some(100),
155/// [(65535, 666).into()],
156/// ).unwrap();
157/// _net.advertise_external_route(
158/// e1,
159/// Ipv4Net::new(Ipv4Addr::new(10, 0, 0, 0),8).unwrap(),
160/// [2, 4],
161/// None,
162/// [],
163/// ).unwrap();
164/// (_net, ((b0, b1), (e0, e1)))
165/// };
166/// ```
167///
168/// ## Order or assigned Router-IDs
169///
170/// The router-IDs are assigned in order of their first occurrence. The first named router will be
171/// assigned id 0, the second 1, and so on. The first occurrence must not necessarily be in the
172/// `routers` block, but it also includes the mentioning of a router in a link or BGP session. Here
173/// is an example:
174///
175/// ```rust
176/// use bgpsim::prelude::*;
177///
178/// let (net, ((b0, b1), (r0, r1), (e0, e1))) = net! {
179/// Prefix = Ipv4Prefix;
180/// default_asn = 100;
181/// links = {
182/// b0 -> r0: 1;
183/// r0 -> r1: 1;
184/// r1 -> b1: 1;
185/// };
186/// sessions = {
187/// b1 -> e1(1);
188/// b0 -> e0(2);
189/// r0 -> r1: peer;
190/// r0 -> b0: client;
191/// r1 -> b1: client;
192/// };
193/// routes = {
194/// e0 -> "10.0.0.0/8" as {path: [1, 3, 4], med: 100, community: [(65535,666), (65535, 1)]};
195/// e1 -> "10.0.0.0/8" as {path: [2, 4]};
196/// };
197/// return ((b0, b1), (r0, r1), (e0, e1))
198/// };
199///
200/// assert_eq!(b0.index(), 0);
201/// assert_eq!(r0.index(), 1);
202/// assert_eq!(r1.index(), 2);
203/// assert_eq!(b1.index(), 3);
204/// assert_eq!(e1.index(), 4);
205/// assert_eq!(e0.index(), 5);
206/// ```
207#[proc_macro]
208pub fn net(input: TokenStream) -> TokenStream {
209 // 1. Use syn to parse the input tokens into a syntax tree.
210 // 2. Use quote to generate new tokens based on what we parsed.
211 // 3. Return the generated tokens.
212 parse_macro_input!(input as Net).quote()
213}
214
215/// Create a `Prefix` from an [`ipnet::Ipv4Net`] string. If you provide an `as`, you can
216/// specify to which type the resulting `Ipv4Net` will be casted. If you omit the type parameter
217/// after `as`, then the macro will simply invoke `.into()` on the generated `IpvtNet`.
218///
219/// ```
220/// # use bgpsim_macros::*;
221/// # use ipnet::Ipv4Net as P;
222/// // `p` will be an `Ipv4Net`
223/// let p = prefix!("192.168.0.0/24");
224///
225/// // `p` will have type `P`, but `P` must implement `From<Ipv4Net>`.
226/// let p = prefix!("192.168.0.0/24" as P);
227/// let p: P = prefix!("192.168.0.0/24" as);
228/// ```
229#[proc_macro]
230pub fn prefix(input: TokenStream) -> TokenStream {
231 parse_macro_input!(input as PrefixInput).quote()
232}
233
234/// Automatically implement the NetworkFormatter for the given type. The strings are generated
235/// similar to the derived `std::fmt::Debug` implementation.
236///
237/// You can control the way in which individual fields are formatted. To do so, you can use the
238/// `#[formatter(...)]` attribute. You can use the following values:
239///
240/// - `skip` will skip that field entirely.
241/// - `fmt = ...` controls which function to use for the (single-line) formatting. You have the
242/// following options:
243/// - `path::to::fn`: A path to a function that takes a reference to the value and to the network
244/// the same function signature as `NetworkFormatter::fmt`. If you pick a
245/// custom function without specifying a `multiline` attribute, then the same function will be
246/// used when formatting the field for multiple lines.
247/// - `"fmt"`: The default (single-line) formatter (used by default). See `NetworkFormatter::fmt`.
248/// - `"fmt_set`: Format any iterable as a set. See `NetworkFormatterSequence::fmt_set`.
249/// - `"fmt_list`: Format any iterable as a list. See `NetworkFormatterSequence::fmt_list`.
250/// - `"fmt_path`: Format any iterable as a path, in the form of `a -> b -> c`. See
251/// `NetworkFormatterSequence::fmt_path`.
252/// - `"fmt_map`: Format the content as a mapping. See `NetworkFormatterMap::fmt_map`.
253/// - `"fmt_map`: Format the content as a mapping. See `NetworkFormatterMap::fmt_map`.
254/// - `"fmt_path_options`: Format a nested iterator as a path option set, in the form of `a -> b |
255/// a -> b -> c`. See `NetworkFormatterNestedSequence::fmt_path_options`.
256/// - `"fmt_path_set`: Format a nested iterator as a path option set, in the form of `{a -> b,
257/// a -> b -> c}`. See `NetworkFormatterNestedSequence::fmt_path_set`.
258/// - `"fmt_ext`: Format any iterable using the extension formatter, see
259/// `NetworkFormatterExt::fmt_ext`.
260/// - `multiline = ...` controls which function to use for the multiline formatting. By default, it
261/// will pick the multi-line variant of the `fmt` option (for instance, setting `fmt = "fmt_set"`
262/// will automatically configure `multiline = "fmt_set_multiline"`). In addition to those, you
263/// have the following options:
264/// - `path::to::fn`: A path to a function that takes a reference to the value, to the network,
265/// and an usize counting the current indentation level. It must have the same function
266/// signature as `NetworkFormatter::fmt_multiline_indent`.
267/// - `"fmt_multiline"`: The default multi-line formatter (used by default). See
268/// `NetworkFormatter::fmt_multiline_indent`.
269/// - `"fmt_set_multiline`: Format any iterable as a set. See
270/// `NetworkFormatterSequence::fmt_set_multiline`.
271/// - `"fmt_list_multiline`: Format any iterable as a list. See
272/// `NetworkFormatterSequence::fmt_list_multiline`.
273/// - `"fmt_map_multiline`: Format the content as a mapping. See
274/// `NetworkFormatterMap::fmt_map_multiline`.
275/// - `"fmt_path_multiline`: Format the content as a set of paths. See
276/// `NetworkFormatterNestedSequence::fmt_path_multiline`.
277///
278/// ```
279/// use bgpsim::prelude::*;
280/// # use std::collections::HashSet;
281///
282/// #[derive(NetworkFormatter)]
283/// struct Foo {
284/// /// Will be printed regularly
285/// counter: usize,
286/// // Will be hidden
287/// #[formatter(skip)]
288/// internal_counter: usize,
289/// /// This will print a path instead of a list
290/// #[formatter(fmt = "fmt_path")]
291/// path: Vec<RouterId>,
292/// /// Do not print this field with multiple lines
293/// #[formatter(multiline = "fmt")]
294/// visited: HashSet<RouterId>,
295/// }
296/// ```
297#[proc_macro_derive(NetworkFormatter, attributes(formatter))]
298pub fn network_formatter_derive(input: TokenStream) -> TokenStream {
299 formatter::derive(input)
300}