Skip to main content

vpp_plugin_macros/
lib.rs

1#![warn(
2    missing_docs,
3    missing_copy_implementations,
4    missing_debug_implementations
5)]
6
7//! Macros for writing VPP plugins in Rust
8//!
9//! This crate provides procedural macros to assist in writing VPP plugins in Rust.
10
11use std::collections::HashSet;
12
13use proc_macro::TokenStream;
14use quote::quote;
15use syn::spanned::Spanned;
16
17#[derive(Default)]
18struct PluginRegister {
19    version: Option<String>,
20    description: Option<String>,
21    version_required: Option<syn::Expr>,
22}
23
24impl syn::parse::Parse for PluginRegister {
25    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
26        const EXPECTED_KEYS: &[&str] = &["version", "description", "version_required"];
27
28        let mut info = PluginRegister::default();
29        let mut seen_keys = HashSet::new();
30        loop {
31            if input.is_empty() {
32                break;
33            }
34            let key = syn::Ident::parse(input)?.to_string();
35
36            if seen_keys.contains(&key) {
37                panic!("Duplicated key \"{key}\". Keys can only be specified once.");
38            }
39
40            input.parse::<syn::Token![:]>()?;
41
42            match key.as_str() {
43                "version" => {
44                    info.version = Some(<syn::LitStr as syn::parse::Parse>::parse(input)?.value())
45                }
46                "description" => {
47                    info.description =
48                        Some(<syn::LitStr as syn::parse::Parse>::parse(input)?.value())
49                }
50                // An expression rather than a literal: the useful value is the VPP build being
51                // compiled against (`vpp_plugin::VPP_BUILD_VER`), known only at build time.
52                "version_required" => {
53                    info.version_required = Some(<syn::Expr as syn::parse::Parse>::parse(input)?)
54                }
55                _ => {
56                    return Err(syn::Error::new(
57                        key.span(),
58                        format!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
59                    ));
60                }
61            }
62
63            input.parse::<syn::Token![,]>()?;
64
65            seen_keys.insert(key);
66        }
67        Ok(info)
68    }
69}
70
71/// Register the plugin so that it can be loaded by VPP
72///
73/// Must only be done once per shared object, or linker errors will result.
74///
75/// # Attributes
76///
77/// - `version`: (required, string literal) The version string of the plugin. Must be at most 63 characters.
78/// - `description`: (optional, string literal) A description of the plugin.
79/// - `version_required`: (optional, `&'static str` constant expression) VPP refuses to load the
80///   plugin unless its own build version starts with this string (a prefix match, not
81///   equality); typically `vpp_plugin::VPP_BUILD_VER`, the build it was compiled against. At
82///   most 63 characters, checked at compile time.
83///
84/// # Examples
85///
86/// ```
87/// # use vpp_plugin::vlib_plugin_register;
88/// vlib_plugin_register! {
89///     version: "1.0",
90///     description: "Example",
91/// }
92/// ```
93#[proc_macro]
94pub fn vlib_plugin_register(ts: TokenStream) -> TokenStream {
95    let PluginRegister {
96        version,
97        description,
98        version_required,
99    } = syn::parse_macro_input!(ts as PluginRegister);
100    let version_required = version_required
101        .map(|e| quote!(version_required: ::vpp_plugin::macro_support::c_char_array::<64>(#e),));
102
103    let mut version_elems = version
104        .expect("Missing required attribute \"version\"")
105        .into_bytes();
106    if version_elems.len() > 63 {
107        panic!("Version string exceeds limit of 63 characters");
108    }
109    // Pad with zeroes to 64 bytes
110    version_elems.extend(std::iter::repeat_n(0, (version_elems.len()..64).count()));
111    let description = if let Some(description) = description {
112        let description = format!("{}\0", description);
113        quote!(#description.as_ptr() as *const ::std::os::raw::c_char)
114    } else {
115        quote!(std::ptr::null_mut())
116    };
117
118    let output = quote!(
119        #[doc(hidden)]
120        #[unsafe(link_section = ".vlib_plugin_registration")]
121        #[unsafe(no_mangle)]
122        #[allow(non_upper_case_globals, non_snake_case)]
123        #[used]
124        pub static mut vlib_plugin_registration: ::vpp_plugin::bindings::vlib_plugin_registration_t = ::vpp_plugin::bindings::vlib_plugin_registration_t {
125            version: [#(#version_elems as ::std::os::raw::c_char),*],
126            description: #description,
127            #version_required
128            ..::vpp_plugin::bindings::vlib_plugin_registration_t::new()
129        };
130    );
131
132    // eprintln!("{}", output);
133
134    output.into()
135}
136
137/// Marks a function as an VPP plugin init function.
138///
139/// Multiple init functions are supported, but the invocation order is not guaranteed.
140///
141/// # Examples
142///
143/// ```
144/// # use vpp_plugin::{vlib::BarrierHeldMainRef, vlib_init_function, vppinfra::error::ErrorStack};
145///
146/// #[vlib_init_function]
147/// fn foo(_vm: &mut BarrierHeldMainRef) -> Result<(), ErrorStack> {
148///   println!("Hello, world!");
149///   Ok(())
150/// }
151/// ```
152#[proc_macro_attribute]
153pub fn vlib_init_function(_attribute: TokenStream, function: TokenStream) -> TokenStream {
154    let item: syn::Item = syn::parse_macro_input!(function);
155    if let syn::Item::Fn(function) = item {
156        let syn::ItemFn {
157            attrs,
158            block,
159            vis,
160            sig:
161                syn::Signature {
162                    ident,
163                    unsafety,
164                    constness,
165                    abi,
166                    inputs,
167                    output,
168                    ..
169                },
170            ..
171        } = function;
172
173        // Ensure that visibility modifier is not present
174        match vis {
175            syn::Visibility::Inherited => {}
176            _ => panic!("#[vlib_init_function] methods must not have visibility modifiers"),
177        }
178
179        let init_fn_ident = syn::parse_str::<syn::Ident>(format!("__{}", ident).as_ref())
180            .expect("Unable to create identifier");
181        let ctor_fn_ident = syn::parse_str::<syn::Ident>(
182            format!("__vlib_add_init_function_init_{}", ident).as_ref(),
183        )
184        .expect("Unable to create identifier");
185        let dtor_fn_ident =
186            syn::parse_str::<syn::Ident>(format!("__vlib_rm_init_function_{}", ident).as_ref())
187                .expect("Unable to create identifier");
188        let init_list_elt_ident =
189            syn::parse_str::<syn::Ident>(format!("_VLIB_INIT_FUNCTION_INIT_{}", ident).as_ref())
190                .expect("Unable to create identifier");
191        let ident_lit = format!("{}\0", ident);
192
193        let output = quote!(
194            #(#attrs)*
195            #vis #unsafety #abi #constness fn #ident(#inputs) #output #block
196
197            unsafe extern "C" fn #init_fn_ident(vm: *mut ::vpp_plugin::bindings::vlib_main_t) -> *mut ::vpp_plugin::bindings::clib_error_t
198            {
199                if let Err(e) = #ident(::vpp_plugin::vlib::BarrierHeldMainRef::from_ptr_mut(vm)) {
200                    e.into_raw()
201                } else {
202                    std::ptr::null_mut()
203                }
204            }
205
206            static mut #init_list_elt_ident: ::vpp_plugin::bindings::_vlib_init_function_list_elt_t = ::vpp_plugin::bindings::_vlib_init_function_list_elt_t {
207                f: None,
208                name: std::ptr::null_mut(),
209                next_init_function: std::ptr::null_mut(),
210                runs_before: std::ptr::null_mut(),
211                runs_after: std::ptr::null_mut(),
212                init_order: std::ptr::null_mut(),
213            };
214
215            #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
216            unsafe fn #ctor_fn_ident () {
217                unsafe {
218                    let vgm = ::vpp_plugin::bindings::vlib_helper_get_global_main();
219                    #init_list_elt_ident.next_init_function = (*vgm).init_function_registrations;
220                    (*vgm).init_function_registrations = std::ptr::addr_of_mut!(#init_list_elt_ident);
221                    #init_list_elt_ident.f = Some(#init_fn_ident);
222                    #init_list_elt_ident.name = #ident_lit.as_ptr() as *mut ::std::os::raw::c_char;
223                }
224            }
225
226            #[::vpp_plugin::macro_support::ctor::dtor(crate_path = ::vpp_plugin::macro_support::ctor)]
227            unsafe fn #dtor_fn_ident() {
228                let vgm = ::vpp_plugin::bindings::vlib_helper_get_global_main();
229
230                let mut this = (*vgm).init_function_registrations;
231                if this.is_null() {
232                    return;
233                }
234                if this == std::ptr::addr_of_mut!(#init_list_elt_ident) {
235                    (*vgm).init_function_registrations = (*this).next_init_function;
236                    return;
237                }
238
239                let mut prev = this;
240                this = (*this).next_init_function;
241                while !this.is_null() {
242                    if this == std::ptr::addr_of_mut!(#init_list_elt_ident) {
243                        (*prev).next_init_function = (*this).next_init_function;
244                        return;
245                    }
246                    prev = this;
247                    this = (*this).next_init_function;
248                }
249            }
250        );
251
252        // eprintln!("{}", output);
253
254        output.into()
255    } else {
256        panic!("#[vlib_init_function] items must be functions");
257    }
258}
259
260/// Derives the NextNodes trait for a VPP next node enum
261///
262/// Only unit variants are allowed and they must not have explicit values.
263///
264/// # Attributes
265///
266/// - Each variant must have a `#[next_node = "<node-name>"]` attribute, where `<node-name>` is
267///   the name of a VPP node.
268///
269/// # Examples
270///
271/// ```
272/// # use vpp_plugin::NextNodes;
273/// #[derive(NextNodes)]
274/// enum ExampleNextNode {
275///     #[next_node = "drop"]
276///    Drop,
277/// }
278/// ```
279#[proc_macro_derive(NextNodes, attributes(next_node))]
280pub fn derive_next_nodes(input: TokenStream) -> TokenStream {
281    let input = syn::parse_macro_input!(input as syn::DeriveInput);
282    let syn::DeriveInput { ident, data, .. } = input;
283    if let syn::Data::Enum(data) = data {
284        let mut next_nodes = vec![];
285        for variant in &data.variants {
286            if let Some((_, exp_discriminant)) = &variant.discriminant {
287                return syn::Error::new_spanned(
288                    exp_discriminant,
289                    "Use of explicit discriminants not allowed",
290                )
291                .into_compile_error()
292                .into();
293            }
294            if !matches!(variant.fields, syn::Fields::Unit) {
295                return syn::Error::new_spanned(&variant.fields, "Only unit variants can be used")
296                    .into_compile_error()
297                    .into();
298            }
299            let next_node_attr = variant
300                .attrs
301                .iter()
302                .find(|x| x.path().is_ident("next_node"))
303                .expect("Missing attribute \"next_node\"");
304            let syn::Meta::NameValue(next_node_name_value) = &next_node_attr.meta else {
305                return syn::Error::new_spanned(next_node_attr, "Unsupported \"next_node\" attribute syntax. Should be #[next_node = \"<node-name>\".").into_compile_error().into();
306            };
307            let syn::Expr::Lit(next_node) = &next_node_name_value.value else {
308                return syn::Error::new_spanned(next_node_name_value, "Unsupported \"next_node\" attribute syntax. Should be #[next_node = \"<node-name>\".").into_compile_error().into();
309            };
310            let syn::Lit::Str(next_node) = &next_node.lit else {
311                return syn::Error::new_spanned(next_node, "Unsupported \"next_node\" attribute syntax. Should be #[next_node = \"<node-name>\".").into_compile_error().into();
312            };
313            next_nodes.push(format!("{}\0", next_node.value()));
314        }
315        let n_next_nodes = data.variants.len();
316
317        let output = quote!(
318            #[automatically_derived]
319            unsafe impl ::vpp_plugin::vlib::node::NextNodes for #ident {
320                type CNamesArray = [*mut ::std::os::raw::c_char; #n_next_nodes];
321                const C_NAMES: Self::CNamesArray = [#(#next_nodes.as_ptr() as *mut ::std::os::raw::c_char),*];
322
323                fn into_u16(self) -> u16 {
324                    self as u16
325                }
326            }
327        );
328
329        // eprintln!("{}", output);
330
331        output.into()
332    } else {
333        panic!("#[derive(NextNodes)] can only be used on enums");
334    }
335}
336
337struct ErrorCounterAttribute {
338    name: Option<String>,
339    description: String,
340    severity: syn::Ident,
341}
342
343impl syn::parse::Parse for ErrorCounterAttribute {
344    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
345        const VALID_SEVERITIES: &[&str] = &["INFO", "WARNING", "ERROR", "CRITICAL"];
346
347        let mut name_or_description_kw = syn::Ident::parse(input)?;
348
349        let name = if name_or_description_kw == "name" {
350            input.parse::<syn::Token![=]>()?;
351            let name = <syn::LitStr as syn::parse::Parse>::parse(input)?.value();
352            input.parse::<syn::Token![,]>()?;
353            name_or_description_kw = syn::Ident::parse(input)?;
354            Some(name)
355        } else {
356            None
357        };
358
359        if name_or_description_kw != "description" {
360            return Err(syn::Error::new(
361                name_or_description_kw.span(),
362                "Expected: description = \"<...>\", severity = <severity>".to_string(),
363            ));
364        }
365
366        input.parse::<syn::Token![=]>()?;
367        let description = <syn::LitStr as syn::parse::Parse>::parse(input)?.value();
368
369        input.parse::<syn::Token![,]>()?;
370
371        let severity_kw = syn::Ident::parse(input)?;
372
373        if severity_kw != "severity" {
374            return Err(syn::Error::new(
375                severity_kw.span(),
376                "Expected: description = \"<...>\", severity = <severity>".to_string(),
377            ));
378        }
379
380        input.parse::<syn::Token![=]>()?;
381        let severity = syn::Ident::parse(input)?;
382        if !VALID_SEVERITIES.contains(&severity.to_string().as_str()) {
383            return Err(syn::Error::new(
384                severity.span(),
385                format!(
386                    "Invalid severity \"{}\". Valid severities are: {:?}.",
387                    severity, VALID_SEVERITIES
388                ),
389            ));
390        }
391
392        Ok(Self {
393            name,
394            description,
395            severity,
396        })
397    }
398}
399
400/// Derives the ErrorCounters trait for a VPP error counter enum
401///
402/// Only unit variants are allowed and they must not have explicit values.
403///
404/// # Attributes
405///
406/// Each variant must have a `#[error_counter(...)]` attribute, with the following key-value pairs:
407/// - `name = "<name>"`: (optional) The name of the error counter. If not provided, the variant name will be used.
408/// - `description = "<description>"`: (required) A description of the error counter
409/// - `severity = <severity>`: (required) The severity of the error counter. Must be one of
410///   `INFO`, `WARNING`, `ERROR`, or `CRITICAL`.
411///
412/// # Examples
413///
414/// ```
415/// # use vpp_plugin::ErrorCounters;
416/// #[derive(ErrorCounters)]
417/// enum ExampleErrors {
418///     #[error_counter(name = "drop", description = "Example drop", severity = ERROR)]
419///     Drop,
420/// }
421/// ```
422#[proc_macro_derive(ErrorCounters, attributes(error_counter))]
423pub fn derive_error_counters(input: TokenStream) -> TokenStream {
424    let input = syn::parse_macro_input!(input as syn::DeriveInput);
425    let syn::DeriveInput { ident, data, .. } = input;
426    if let syn::Data::Enum(data) = data {
427        let mut error_counter_desc = vec![];
428        for variant in &data.variants {
429            if let Some((_, exp_discriminant)) = &variant.discriminant {
430                return syn::Error::new_spanned(
431                    exp_discriminant,
432                    "Use of explicit discriminants not allowed",
433                )
434                .into_compile_error()
435                .into();
436            }
437            if !matches!(variant.fields, syn::Fields::Unit) {
438                return syn::Error::new_spanned(&variant.fields, "Only unit variants can be used")
439                    .into_compile_error()
440                    .into();
441            }
442            let error_counter_attr = variant
443                .attrs
444                .iter()
445                .find(|x| x.path().is_ident("error_counter"))
446                .expect("Missing attribute \"error_counter\"");
447            let syn::Meta::List(error_counter_list) = &error_counter_attr.meta else {
448                return syn::Error::new_spanned(error_counter_attr, "Unsupported \"error_counter\" attribute syntax. Should be #[error_counter(description = \"...\")]").into_compile_error().into();
449            };
450            let ErrorCounterAttribute {
451                name,
452                description,
453                severity,
454            } = match syn::parse2::<ErrorCounterAttribute>(error_counter_list.tokens.clone()) {
455                Ok(v) => v,
456                Err(e) => return proc_macro::TokenStream::from(e.to_compile_error()),
457            };
458            let name = if let Some(name) = name {
459                format!("{}\0", name)
460            } else {
461                format!("{}\0", variant.ident)
462            };
463            let description = format!("{}\0", description);
464            let severity = syn::parse_str::<syn::Ident>(&format!(
465                "vl_counter_severity_e_VL_COUNTER_SEVERITY_{}",
466                severity
467            ))
468            .expect("Unable to create identifier");
469
470            error_counter_desc.push(quote!(
471                ::vpp_plugin::bindings::vlib_error_desc_t {
472                    name: #name.as_ptr() as *mut std::ffi::c_char,
473                    desc: #description.as_ptr() as *mut std::ffi::c_char,
474                    severity: ::vpp_plugin::bindings::#severity,
475                    stats_entry_index: 0,
476                },
477            ));
478        }
479        let n_error_counters = data.variants.len();
480
481        let output = quote!(
482            #[automatically_derived]
483            unsafe impl ::vpp_plugin::vlib::node::ErrorCounters for #ident {
484                type CDescriptionsArray = [::vpp_plugin::bindings::vlib_error_desc_t; #n_error_counters];
485                const C_DESCRIPTIONS: Self::CDescriptionsArray = [
486                    #(#error_counter_desc)*
487                ];
488
489                fn into_u16(self) -> u16 {
490                    self as u16
491                }
492            }
493        );
494
495        // eprintln!("{}", output);
496
497        output.into()
498    } else {
499        panic!("#[derive(ErrorCounters)] can only be used on enums");
500    }
501}
502
503const CPU_MARCH_TO_CPU_AND_TARGET_FEATURE: &[(&str, Option<&str>, Option<&str>)] = &[
504    // VPP's baseline variant (`CLIB_MARCH_VARIANT_TYPE`, priority 0), built for the crate's
505    // target baseline on every architecture. VPP picks the highest-priority registered variant
506    // the running CPU supports, starting from -1; without this entry a CPU matching none of the
507    // variants below (any aarch64 core not listed, e.g. Apple silicon or Neoverse V1) leaves
508    // the node with a NULL function and the first dispatch jumps to address 0.
509    ("default", None, None),
510    ("scalar", Some("x86_64"), None),
511    (
512        "x86_64_v3",
513        Some("x86_64"),
514        Some("avx2,bmi1,bmi2,f16c,fma,movbe,lzcnt,xsave"),
515    ),
516    (
517        "x86_64_v4",
518        Some("x86_64"),
519        Some("bmi1,bmi2,f16c,fma,movbe,lzcnt,avx512f,avx512bw,avx512dq,avx512vl,avx512cd"),
520    ),
521    // Features equivalent to "v8.2a,sha2,aes", but avoiding use of unstable v8.2a feature
522    (
523        "octeontx2",
524        Some("aarch64"),
525        Some("crc,lse,rdm,pan,lor,vh,ras,dpb,sha2,aes"),
526    ),
527    // Features equivalent to "v8.1a,sha2,aes", but avoiding use of unstable v8.1a feature
528    (
529        "thunderx2t99",
530        Some("aarch64"),
531        Some("crc,lse,rdm,pan,lor,vh,sha2,aes"),
532    ),
533    ("cortexa72", Some("aarch64"), Some("crc,sha2,aes")),
534    // Features equivalent to "v8.2a,sha2,aes", but avoiding use of unstable v8.2a feature
535    (
536        "neoversen1",
537        Some("aarch64"),
538        Some("crc,lse,rdm,pan,lor,vh,ras,dpb,sha2,aes"),
539    ),
540    // Features equivalent to "v9a,sha2,aes", but avoiding use of unstable v9a feature
541    (
542        "neoversen2",
543        Some("aarch64"),
544        Some(
545            "crc,lse,rdm,pan,lor,vh,ras,dpb,rcpc,paca,pacg,jsconv,dotprod,dit,flagm,ssbs,sb,dpb2,bti,sve2",
546        ),
547    ),
548];
549
550#[derive(Default)]
551struct Node {
552    name: Option<syn::LitStr>,
553    instance: Option<syn::Ident>,
554    runtime_data_default: Option<syn::Ident>,
555    format_trace: Option<syn::Ident>,
556}
557
558impl Node {
559    fn parse(&mut self, meta: syn::meta::ParseNestedMeta) -> Result<(), syn::Error> {
560        const EXPECTED_KEYS: &[&str] =
561            &["name", "instance", "runtime_data_default", "format_trace"];
562
563        if meta.path.is_ident("name") {
564            self.name = Some(meta.value()?.parse()?);
565            Ok(())
566        } else if meta.path.is_ident("instance") {
567            self.instance = Some(meta.value()?.parse()?);
568            Ok(())
569        } else if meta.path.is_ident("runtime_data_default") {
570            self.runtime_data_default = Some(meta.value()?.parse()?);
571            Ok(())
572        } else if meta.path.is_ident("format_trace") {
573            self.format_trace = Some(meta.value()?.parse()?);
574            Ok(())
575        } else {
576            Err(syn::Error::new(
577                meta.path.span(),
578                format!(
579                    "Unknown attribute \"{:?}\". Valid keys are: {EXPECTED_KEYS:?}.",
580                    meta.path.get_ident()
581                ),
582            ))
583        }
584    }
585}
586
587/// Registers a VPP node and associated function
588///
589/// This registers an internal VPP node, which is the most common type of node (as opposed to
590/// processing or input nodes).
591///
592/// In addition, node functions are also registered, compiled for multiple CPU architectures and
593/// target features to allow VPP to select the optimal implementation for the current CPU. This
594/// only has an effect for code inlined into the node functions. In other words, `Node::function`
595/// should be marked as `#[inline(always)]` and any other functions directly or indirectly called
596/// in performance-critical paths should be similarly marked.
597///
598/// # Attributes
599///
600/// The macro takes key-value attributes as follows:
601/// - `name`: (required, string literal) The name of the VPP node.
602/// - `instance`: (required, ident) The instance of the node.
603/// - `runtime_data_default`: (optional, ident) An identifier for a constant value of type
604///   `Node::RuntimeData` to use as the default runtime data for this node.
605/// - `format_trace`: (optional, ident) An identifier for a function with the signature
606///   `fn(&mut MainRef, &mut NodeRef<...>, &TraceData) -> String` to format trace
607///   data for this node.
608///
609/// # Examples
610///
611/// ```
612/// # use std::fmt;
613/// # use vpp_plugin::{vlib::{self, node::Node}, vlib_node, ErrorCounters, NextNodes};
614/// #[derive(Copy, Clone)]
615/// struct ExampleTrace;
616///
617/// impl fmt::Display for ExampleTrace {
618///     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
619///         Ok(())
620///     }
621/// }
622///
623/// fn format_example_trace(
624///     _vm: &mut vlib::MainRef,
625///     _node: &mut vlib::NodeRef<ExampleNode>,
626///     t: &ExampleTrace,
627/// ) -> String {
628///     t.to_string()
629/// }
630/// # #[derive(NextNodes)]
631/// # enum ExampleNextNode {
632/// #     #[next_node = "drop"]
633/// #    _Drop,
634/// # }
635/// # #[derive(ErrorCounters)]
636/// # enum ExampleErrorCounter {
637/// #     #[error_counter(description = "Drops", severity = ERROR)]
638/// #     _Drop,
639/// # }
640///
641/// static EXAMPLE_NODE: ExampleNode = ExampleNode::new();
642///
643/// #[vlib_node(
644///     name = "example",
645///     instance = EXAMPLE_NODE,
646///     format_trace = format_example_trace,
647/// )]
648/// struct ExampleNode;
649///
650/// impl ExampleNode {
651///     const fn new() -> Self {
652///         Self
653///     }
654/// }
655///
656/// impl vlib::node::Node for ExampleNode {
657///     type Vector = ();
658///     type Scalar = ();
659///     type Aux = ();
660///
661///     type NextNodes = ExampleNextNode;
662///     type RuntimeData = ();
663///     type TraceData = ExampleTrace;
664///     type Errors = ExampleErrorCounter;
665///     type FeatureData = ();
666///
667///     #[inline(always)]
668///     unsafe fn function(
669///         &self,
670///         _vm: &mut vlib::MainRef,
671///         _node: &mut vlib::NodeRuntimeRef<ExampleNode>,
672///         _frame: &mut vlib::FrameRef<Self>,
673///     ) -> u16 {
674///         todo!()
675///     }
676/// }
677/// ```
678#[proc_macro_attribute]
679pub fn vlib_node(attributes: TokenStream, s: TokenStream) -> TokenStream {
680    let mut attrs = Node::default();
681    let node_parser = syn::meta::parser(|meta| attrs.parse(meta));
682    syn::parse_macro_input!(attributes with node_parser);
683    let Node {
684        name,
685        instance,
686        runtime_data_default,
687        format_trace,
688    } = attrs;
689    let item: syn::Item = syn::parse_macro_input!(s);
690    if let syn::Item::Struct(syn::ItemStruct {
691        attrs,
692        vis,
693        struct_token,
694        ident,
695        generics,
696        fields,
697        semi_token,
698    }) = item
699    {
700        let name = name.expect("Missing attribute \"name\". This is required.");
701        let name_lit = format!("{}\0", name.value());
702        let instance = instance.expect("Missing attribute \"instance\". This is required.");
703        let reg_ident =
704            syn::parse_str::<syn::Ident>(format!("{}_NODE_REGISTRATION", ident).as_ref())
705                .expect("Unable to create identifier");
706        let add_node_fn_ident = syn::parse_str::<syn::Ident>(
707            format!("__vlib_add_node_registration_{}", ident).as_ref(),
708        )
709        .expect("Unable to create identifier");
710        let rm_node_fn_ident =
711            syn::parse_str::<syn::Ident>(format!("__vlib_rm_node_registration_{}", ident).as_ref())
712                .expect("Unable to create identifier");
713        let (format_trace_output, format_trace) = match format_trace {
714            Some(format_trace) => {
715                let thunk_format_trace =
716                    syn::parse_str::<syn::Ident>(format!("__{}", format_trace).as_ref())
717                        .expect("Unable to create identifier");
718                (
719                    quote!(
720                        unsafe extern "C" fn #thunk_format_trace(s: *mut u8, args: *mut ::vpp_plugin::bindings::va_list) -> *mut u8 {
721                            unsafe {
722                                let mut args = std::mem::transmute::<_, ::vpp_plugin::macro_support::va_list::VaList<'_>>(args);
723                                let vm = args.get::<*const ::vpp_plugin::bindings::vlib_main_t>().cast_mut();
724                                let node = args.get::<*const ::vpp_plugin::bindings::vlib_node_t>().cast_mut();
725                                let t = args.get::<*const <#ident as ::vpp_plugin::vlib::node::Node>::TraceData>();
726                                let str = #format_trace(&mut ::vpp_plugin::vlib::MainRef::from_ptr_mut(vm), &mut #reg_ident.node_from_ptr(node), &*t);
727                                let mut s = ::vpp_plugin::vppinfra::vec::Vec::from_raw(s);
728                                s.extend(str.as_bytes());
729                                s.into_raw()
730                            }
731                        }
732                    ),
733                    quote!(Some(#thunk_format_trace)),
734                )
735            }
736            None => (quote!(), quote!(None)),
737        };
738        let runtime_data = match runtime_data_default {
739            Some(runtime_data_default) => {
740                // It would be ideal to use #runtime_data::default() here, but we cannot call that in a const context and we need to here
741                quote!(::std::ptr::addr_of!(#runtime_data_default) as *mut ::std::os::raw::c_void)
742            }
743            None => quote!({
744                ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::RuntimeData>() == 0);
745                std::ptr::null_mut()
746            }),
747        };
748
749        let mut march_outputs = vec![];
750
751        for (cpu_march, cpu, target_feature) in CPU_MARCH_TO_CPU_AND_TARGET_FEATURE {
752            let raw_node_fn_ident =
753                syn::parse_str::<syn::Ident>(format!("__{}_{}", ident, cpu_march).as_ref())
754                    .expect("Unable to create identifier");
755            let registration_ident = syn::parse_str::<syn::Ident>(
756                format!("{}_FN_REGISTRATION_{}", ident, cpu_march).as_ref(),
757            )
758            .expect("Unable to create identifier");
759            let reg_fn_ident = syn::parse_str::<syn::Ident>(
760                format!("{}_multiarch_register_{}", ident, cpu_march).as_ref(),
761            )
762            .expect("Unable to create identifier");
763            let march_variant_ident = syn::parse_str::<syn::Ident>(
764                if *cpu_march == "default" {
765                    "clib_march_variant_type_t_CLIB_MARCH_VARIANT_TYPE".to_owned()
766                } else {
767                    format!(
768                        "clib_march_variant_type_t_CLIB_MARCH_VARIANT_TYPE_{}",
769                        cpu_march
770                    )
771                }
772                .as_ref(),
773            )
774            .expect("Unable to create identifier");
775            let cpu_condition = if let Some(cpu) = cpu {
776                quote!(#[cfg(target_arch = #cpu)])
777            } else {
778                quote!()
779            };
780            let target_feature = if let Some(target_feature) = target_feature {
781                quote!(#[target_feature(enable = #target_feature)])
782            } else {
783                quote!()
784            };
785
786            let output = quote!(
787                #cpu_condition
788                #target_feature
789                #[doc(hidden)]
790                unsafe extern "C" fn #raw_node_fn_ident(
791                    vm: *mut ::vpp_plugin::bindings::vlib_main_t,
792                    node: *mut ::vpp_plugin::bindings::vlib_node_runtime_t,
793                    frame: *mut ::vpp_plugin::bindings::vlib_frame_t,
794                ) -> ::vpp_plugin::bindings::uword {
795                    unsafe {
796                        <#ident as ::vpp_plugin::vlib::node::Node>::function(
797                            &#instance,
798                            ::vpp_plugin::vlib::MainRef::from_ptr_mut(vm),
799                            #reg_ident.node_runtime_from_ptr(node),
800                            #reg_ident.frame_from_ptr(frame),
801                        )
802                    }.into()
803                }
804
805                #cpu_condition
806                #[doc(hidden)]
807                static mut #registration_ident: ::vpp_plugin::bindings::vlib_node_fn_registration_t = ::vpp_plugin::bindings::vlib_node_fn_registration_t{
808                    function: Some(#raw_node_fn_ident),
809                    march_variant: ::vpp_plugin::bindings::#march_variant_ident,
810                    next_registration: std::ptr::null_mut(),
811                };
812
813                #cpu_condition
814                #[doc(hidden)]
815                #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
816                fn #reg_fn_ident() {
817                    unsafe {
818                        #reg_ident.register_node_fn(std::ptr::addr_of!(#registration_ident).cast_mut());
819                    }
820                }
821            );
822            march_outputs.push(output);
823        }
824
825        let output = quote!(
826            #(#attrs)*
827            #vis #struct_token #ident #generics #fields #semi_token
828
829            #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
830            fn #add_node_fn_ident() {
831                unsafe {
832                    #reg_ident.register();
833                }
834            }
835
836            #[::vpp_plugin::macro_support::ctor::dtor(crate_path = ::vpp_plugin::macro_support::ctor)]
837            fn #rm_node_fn_ident() {
838                unsafe {
839                    #reg_ident.unregister();
840                }
841            }
842
843            #format_trace_output
844
845            static #reg_ident: ::vpp_plugin::vlib::node::NodeRegistration<#ident, { <<#ident as ::vpp_plugin::vlib::node::Node>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES.len() } > = ::vpp_plugin::vlib::node::NodeRegistration::new(
846                ::vpp_plugin::bindings::_vlib_node_registration {
847                    function: None,
848                    name: #name_lit.as_ptr() as *mut ::std::os::raw::c_char,
849                    type_: ::vpp_plugin::bindings::vlib_node_type_t_VLIB_NODE_TYPE_INTERNAL,
850                    error_counters: <<#ident as ::vpp_plugin::vlib::node::Node>::Errors as ::vpp_plugin::vlib::node::ErrorCounters>::C_DESCRIPTIONS.as_ptr().cast_mut(),
851                    format_trace: #format_trace,
852                    runtime_data: #runtime_data,
853                    runtime_data_bytes: {
854                        ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::RuntimeData>() <= u8::MAX as usize);
855                        ::vpp_plugin::const_assert!(::std::mem::align_of::<<#ident as ::vpp_plugin::vlib::node::Node>::RuntimeData>() <= ::vpp_plugin::vlib::node::RUNTIME_DATA_ALIGN);
856                        ::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::RuntimeData>() as u8
857                    },
858                    vector_size: {
859                        ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Vector>() <= u8::MAX as usize);
860                        ::vpp_plugin::const_assert!(::std::mem::align_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Vector>() <= ::vpp_plugin::vlib::node::FRAME_DATA_ALIGN);
861                        ::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Vector>() as u8
862                    },
863                    aux_size: {
864                        ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Aux>() <= u8::MAX as usize);
865                        ::vpp_plugin::const_assert!(::std::mem::align_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Aux>() <= ::vpp_plugin::vlib::node::FRAME_DATA_ALIGN);
866                        ::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Aux>() as u8
867                    },
868                    scalar_size: {
869                        ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Scalar>() <= u16::MAX as usize);
870                        ::vpp_plugin::const_assert!(::std::mem::align_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Scalar>() <= ::vpp_plugin::vlib::node::FRAME_DATA_ALIGN);
871                        ::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::node::Node>::Scalar>() as u16
872                    },
873                    n_errors: <<#ident as ::vpp_plugin::vlib::node::Node>::Errors as ::vpp_plugin::vlib::node::ErrorCounters>::C_DESCRIPTIONS.len()
874                        as u16,
875                    n_next_nodes: <<#ident as ::vpp_plugin::vlib::node::Node>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES.len()
876                        as u16,
877                    next_nodes: <<#ident as ::vpp_plugin::vlib::node::Node>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES,
878                    ..::vpp_plugin::bindings::_vlib_node_registration::new()
879                });
880
881            #(#march_outputs)*
882        );
883
884        // eprintln!("{}", output);
885
886        output.into()
887    } else {
888        panic!("#[vlib_node] items must be structs");
889    }
890}
891
892struct FeatureInit {
893    identifier: Option<syn::Ident>,
894    arc_name: Option<String>,
895    node: Option<syn::Ident>,
896    runs_before: Vec<String>,
897    runs_after: Vec<String>,
898    feature_data_type: Option<syn::Type>,
899}
900
901impl syn::parse::Parse for FeatureInit {
902    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
903        const EXPECTED_KEYS: &[&str] = &[
904            "identifier",
905            "arc_name",
906            "node",
907            "runs_before",
908            "runs_after",
909            "feature_data_type",
910        ];
911
912        let mut info = FeatureInit {
913            identifier: None,
914            arc_name: None,
915            node: None,
916            runs_before: Vec::new(),
917            runs_after: Vec::new(),
918            feature_data_type: None,
919        };
920        let mut seen_keys = HashSet::new();
921        loop {
922            if input.is_empty() {
923                break;
924            }
925            let key = syn::Ident::parse(input)?.to_string();
926
927            if seen_keys.contains(&key) {
928                panic!("Duplicated key \"{key}\". Keys can only be specified once.");
929            }
930
931            input.parse::<syn::Token![:]>()?;
932
933            match key.as_str() {
934                "identifier" => info.identifier = Some(syn::Ident::parse(input)?),
935                "arc_name" => {
936                    info.arc_name = Some(<syn::LitStr as syn::parse::Parse>::parse(input)?.value())
937                }
938                "node" => info.node = Some(syn::Ident::parse(input)?),
939                "runs_before" => {
940                    let runs_before_input;
941                    syn::bracketed!(runs_before_input in input);
942                    let runs_before = syn::punctuated::Punctuated::<syn::LitStr, syn::Token![,]>::parse_terminated(&runs_before_input)?;
943                    info.runs_before = runs_before.into_iter().map(|s| s.value()).collect();
944                }
945                "runs_after" => {
946                    let runs_after_input;
947                    syn::bracketed!(runs_after_input in input);
948                    let runs_after = syn::punctuated::Punctuated::<syn::LitStr, syn::Token![,]>::parse_terminated(&runs_after_input)?;
949                    info.runs_after = runs_after.into_iter().map(|s| s.value()).collect();
950                }
951                "feature_data_type" => info.feature_data_type = Some(syn::Type::parse(input)?),
952                _ => {
953                    return Err(syn::Error::new(
954                        key.span(),
955                        format!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
956                    ));
957                }
958            }
959
960            input.parse::<syn::Token![,]>()?;
961
962            seen_keys.insert(key);
963        }
964        Ok(info)
965    }
966}
967
968/// Registers a VPP feature
969///
970/// Allowing the VPP node to be executed in a feature arc. Note that the feature won't be
971/// executed until enabled.
972///
973/// # Attributes
974///
975/// Each variant must have a `#[error_counter(...)]` attribute, with the following key-value pairs:
976/// - `identifier = <ident>`: (required) An identifier of a static of type
977///   `vpp_plugin::vnet::feature::FeatureRegistration` that will be declared and registered by
978///   the macro.
979/// - `arc_name = "<name>"`: (required, string literal) The name of the feature arc the node will
980///   be registered to.
981/// - `node = <ident>`: (required, string literal) The name of a node type registered using
982///   [`vlib_node`].
983/// - `runs_before = [("<feature-name>")*]`: (optional, string literal) A list of features that
984///   should be executed in the feature arc before this feature is executed.
985/// - `runs_after = [("<feature-name>")*]`: (optional, string literal) A list of features that
986///   should be executed in the feature arc after this feature is executed.
987///
988/// # Examples
989///
990/// ```
991/// # use vpp_plugin::{vlib::{self, node::Node}, vlib_node, vnet_feature_init, ErrorCounters, NextNodes};
992/// # #[derive(NextNodes)]
993/// # enum ExampleNextNode {
994/// #     #[next_node = "drop"]
995/// #    _Drop,
996/// # }
997/// # #[derive(ErrorCounters)]
998/// # enum ExampleErrorCounter {}
999/// #
1000/// # static EXAMPLE_NODE: ExampleNode = ExampleNode::new();
1001/// #
1002/// #[vlib_node(
1003///     name = "example",
1004///     instance = EXAMPLE_NODE,
1005/// )]
1006/// struct ExampleNode;
1007///
1008/// // ...
1009///
1010/// # impl ExampleNode {
1011/// #     const fn new() -> Self {
1012/// #         Self
1013/// #     }
1014/// # }
1015/// # impl vlib::node::Node for ExampleNode {
1016/// #     type Vector = ();
1017/// #     type Scalar = ();
1018/// #     type Aux = ();
1019/// #
1020/// #     type NextNodes = ExampleNextNode;
1021/// #     type RuntimeData = ();
1022/// #     type TraceData = ();
1023/// #     type Errors = ExampleErrorCounter;
1024/// #     type FeatureData = ();
1025/// #
1026/// #     #[inline(always)]
1027/// #     unsafe fn function(
1028/// #         &self,
1029/// #         _vm: &mut vlib::MainRef,
1030/// #         _node: &mut vlib::NodeRuntimeRef<Self>,
1031/// #         _frame: &mut vlib::FrameRef<Self>,
1032/// #     ) -> u16 {
1033/// #         todo!()
1034/// #     }
1035/// # }
1036/// vnet_feature_init! {
1037///     identifier: EXAMPLE_FEAT,
1038///     arc_name: "ip4-unicast",
1039///     node: ExampleNode,
1040///     runs_before: ["ip4-flow-classify"],
1041///     runs_after: ["ip4-sv-reassembly-feature"],
1042/// }
1043/// ```
1044#[proc_macro]
1045pub fn vnet_feature_init(ts: TokenStream) -> TokenStream {
1046    let FeatureInit {
1047        identifier,
1048        arc_name,
1049        node,
1050        runs_before,
1051        runs_after,
1052        feature_data_type,
1053    } = syn::parse_macro_input!(ts as FeatureInit);
1054
1055    let ident = identifier.expect("Missing key \"identifier\". This is required.");
1056    let ctor_fn_ident =
1057        syn::parse_str::<syn::Ident>(format!("__vnet_add_feature_registration_{}", ident).as_ref())
1058            .expect("Unable to create identifier");
1059    let dtor_fn_ident =
1060        syn::parse_str::<syn::Ident>(format!("__vnet_rm_feature_registration_{}", ident).as_ref())
1061            .expect("Unable to create identifier");
1062    let arc_name = arc_name.expect("Missing key \"arc_name\". This is required.");
1063    let node = node.expect("Missing key \"node\". This is required.");
1064    let reg_ident = syn::parse_str::<syn::Ident>(format!("{}_NODE_REGISTRATION", node).as_ref())
1065        .expect("Unable to create identifier");
1066    let arc_name_lit = format!("{arc_name}\0");
1067    let runs_before_output = if runs_before.is_empty() {
1068        quote!(std::ptr::null_mut())
1069    } else {
1070        let runs_before = runs_before.iter().map(|s| {
1071            let s = format!("{s}\0");
1072            quote!(#s.as_ptr() as *mut ::std::os::raw::c_char)
1073        });
1074        quote!(&[#(#runs_before),*, std::ptr::null_mut()] as *const *mut ::std::os::raw::c_char as *mut *mut ::std::os::raw::c_char)
1075    };
1076    let runs_after_output = if runs_after.is_empty() {
1077        quote!(std::ptr::null_mut())
1078    } else {
1079        let runs_after = runs_after.iter().map(|s| {
1080            let s = format!("{s}\0");
1081            quote!(#s.as_ptr() as *mut ::std::os::raw::c_char)
1082        });
1083        quote!(&[#(#runs_after),*, std::ptr::null_mut()] as *const *mut ::std::os::raw::c_char as *mut *mut ::std::os::raw::c_char)
1084    };
1085    let feature_data_type = feature_data_type
1086        .unwrap_or_else(|| syn::parse_str::<syn::Type>("()").expect("Unable to create identifier"));
1087
1088    let output = quote!(
1089        #[doc(hidden)]
1090        #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
1091        fn #ctor_fn_ident() {
1092            unsafe { #ident.register(); }
1093        }
1094
1095        #[doc(hidden)]
1096        #[::vpp_plugin::macro_support::ctor::dtor(crate_path = ::vpp_plugin::macro_support::ctor)]
1097        fn #dtor_fn_ident() {
1098            unsafe { #ident.unregister(); }
1099        }
1100
1101        static #ident: ::vpp_plugin::vnet::feature::FeatureRegistration<#feature_data_type> = unsafe {
1102            ::vpp_plugin::vnet::feature::FeatureRegistration::new(
1103                ::vpp_plugin::bindings::vnet_feature_registration_t {
1104                    arc_name: #arc_name_lit.as_ptr() as *mut ::std::os::raw::c_char,
1105                    runs_before: #runs_before_output,
1106                    runs_after: #runs_after_output,
1107                    enable_disable_cb: None,
1108                    ..::vpp_plugin::bindings::vnet_feature_registration_t::new()
1109                },
1110                &#reg_ident,
1111            )
1112        };
1113    );
1114
1115    // eprintln!("{}", output);
1116
1117    output.into()
1118}
1119
1120/// Creates a CLI command function
1121///
1122/// # Attributes
1123///
1124/// - `path`: (required, string literal) The CLI command path.
1125/// - `short_help`: (optional, string literal) A short help string for the CLI command.
1126///
1127/// # Examples
1128///
1129/// ```
1130/// # use vpp_plugin::{vlib_cli_command, vlib, vppinfra::error::ErrorStack};
1131/// #[vlib_cli_command(
1132///     path = "rust-example",
1133///     short_help = "rust-example <interface-name> [disable]",
1134/// )]
1135/// fn enable_disable_command(_vm: &mut vlib::BarrierHeldMainRef, _input: &str) -> Result<(), ErrorStack> {
1136///     Ok(())
1137/// }
1138/// ```
1139#[proc_macro_attribute]
1140pub fn vlib_cli_command(attributes: TokenStream, function: TokenStream) -> TokenStream {
1141    let mut path: Option<syn::LitStr> = None;
1142    let mut short_help: Option<syn::LitStr> = None;
1143    let attr_parser = syn::meta::parser(|meta| {
1144        if meta.path.is_ident("path") {
1145            path = Some(meta.value()?.parse()?);
1146            Ok(())
1147        } else if meta.path.is_ident("short_help") {
1148            short_help = Some(meta.value()?.parse()?);
1149            Ok(())
1150        } else {
1151            Err(meta.error("unsupported vlib_cli_command property"))
1152        }
1153    });
1154
1155    syn::parse_macro_input!(attributes with attr_parser);
1156
1157    let item: syn::Item = syn::parse_macro_input!(function);
1158    if let syn::Item::Fn(function) = item {
1159        let syn::ItemFn {
1160            attrs,
1161            block,
1162            vis,
1163            sig:
1164                syn::Signature {
1165                    ident,
1166                    unsafety,
1167                    constness,
1168                    abi,
1169                    inputs,
1170                    output,
1171                    ..
1172                },
1173            ..
1174        } = function;
1175
1176        let path = path.expect(
1177            "Missing attribute 'path'. Example: #[vlib_cli_command(path = \"rust-example\")]",
1178        );
1179        let path = format!("{}\0", path.value());
1180        let short_help = if let Some(short_help) = short_help {
1181            let short_help = format!("{}\0", short_help.value());
1182            quote!(#short_help.as_ptr() as *mut ::std::os::raw::c_char)
1183        } else {
1184            quote!(std::ptr::null_mut())
1185        };
1186        let raw_fn_ident = syn::parse_str::<syn::Ident>(format!("__{}", ident).as_ref())
1187            .expect("Unable to create identifier");
1188        let ctor_fn_ident = syn::parse_str::<syn::Ident>(
1189            format!("__vlib_cli_command_registration_{}", ident).as_ref(),
1190        )
1191        .expect("Unable to create identifier");
1192        let dtor_fn_ident = syn::parse_str::<syn::Ident>(
1193            format!("__vlib_cli_command_unregistration_{}", ident).as_ref(),
1194        )
1195        .expect("Unable to create identifier");
1196        let cli_command_ident =
1197            syn::parse_str::<syn::Ident>(format!("_VLIB_CLI_COMMAND_{}", ident).as_ref())
1198                .expect("Unable to create identifier");
1199
1200        let output = quote!(
1201            #(#attrs)*
1202            #vis #unsafety #abi #constness fn #ident(#inputs) #output #block
1203
1204            #[doc(hidden)]
1205            unsafe extern "C" fn #raw_fn_ident(
1206                vm: *mut ::vpp_plugin::bindings::vlib_main_t,
1207                input: *mut ::vpp_plugin::bindings::unformat_input_t,
1208                _cmd: *mut ::vpp_plugin::bindings::vlib_cli_command_t,
1209            ) -> *mut ::vpp_plugin::bindings::clib_error_t
1210            {
1211                let s = ::vpp_plugin::vppinfra::unformat::raw_unformat_line_input_to_string(input);
1212                if let Err(e) = #ident(::vpp_plugin::vlib::BarrierHeldMainRef::from_ptr_mut(vm), s.as_str()) {
1213                    e.into_raw()
1214                } else {
1215                    std::ptr::null_mut()
1216                }
1217            }
1218
1219            static #cli_command_ident: ::vpp_plugin::vlib::cli::CommandRegistration = ::vpp_plugin::vlib::cli::CommandRegistration::new(::vpp_plugin::bindings::vlib_cli_command_t {
1220                path: #path.as_ptr() as *mut ::std::os::raw::c_char,
1221                short_help: #short_help,
1222                long_help: std::ptr::null_mut(), // TODO
1223                function: Some(#raw_fn_ident),
1224                is_mp_safe: 0,
1225                ..::vpp_plugin::bindings::vlib_cli_command_t::new()
1226            });
1227
1228            #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
1229            unsafe fn #ctor_fn_ident () {
1230                unsafe {
1231                    #cli_command_ident.register();
1232                }
1233            }
1234
1235            #[::vpp_plugin::macro_support::ctor::dtor(crate_path = ::vpp_plugin::macro_support::ctor)]
1236            unsafe fn #dtor_fn_ident() {
1237                unsafe {
1238                    #cli_command_ident.unregister();
1239                }
1240            }
1241        );
1242
1243        // eprintln!("{}", output);
1244
1245        output.into()
1246    } else {
1247        panic!("#[vlib_cli_command] items must be functions");
1248    }
1249}
1250
1251/// Registers a VPP async process node
1252///
1253/// Creates a process node that runs an async coroutine, integrated with VPP's
1254/// event-driven processing model.
1255///
1256/// # Attributes
1257///
1258/// - `name`: (required, string literal) The name of the process node
1259/// - `instance`: (required, ident) The instance of the node.
1260/// - `runtime_data_default`: (optional, ident) An identifier for a constant value of type
1261///   `Node::RuntimeData` to use as the default runtime data for this node.
1262/// - `log2_stack_bytes`: (optional, integer literal) Log2 of process stack size in bytes.
1263///   Defaults to 0. The value will be set to a minimum value by VPP if smaller.
1264///
1265/// # Examples
1266///
1267/// ```
1268/// # use std::fmt;
1269/// # use vpp_plugin::{vlib::{self, node::Node}, vlib_process_node, ErrorCounters, NextNodes};
1270/// # #[derive(NextNodes)]
1271/// # enum ExampleProcessNextNode {}
1272/// # #[derive(ErrorCounters)]
1273/// # enum ExampleProcessErrorCounter {}
1274/// static EXAMPLE_PROCESS_NODE: ExampleProcessNode = ExampleProcessNode::new();
1275///
1276/// #[vlib_process_node(
1277///     name = "example-process",
1278///     instance = EXAMPLE_PROCESS_NODE,
1279/// )]
1280/// struct ExampleProcessNode;
1281///
1282/// impl ExampleProcessNode {
1283///     const fn new() -> Self {
1284///         Self
1285///     }
1286/// }
1287///
1288/// impl vlib::ProcessNode for ExampleProcessNode {
1289///     type NextNodes = ExampleProcessNextNode;
1290///     type RuntimeData = ();
1291///     type Errors = ExampleProcessErrorCounter;
1292///
1293///     async fn function(&self, vm: &mut vlib::MainRef, node: &mut vlib::NodeRuntimeRef<Self>) {
1294///         todo!()
1295///     }
1296/// }
1297/// ```
1298#[proc_macro_attribute]
1299pub fn vlib_process_node(attributes: TokenStream, item: TokenStream) -> TokenStream {
1300    #[derive(Default)]
1301    struct ProcessNodeAttrs {
1302        name: Option<String>,
1303        instance: Option<syn::Ident>,
1304        runtime_data_default: Option<syn::Ident>,
1305        log2_stack_bytes: Option<u16>,
1306    }
1307
1308    impl ProcessNodeAttrs {
1309        fn parse(&mut self, meta: syn::meta::ParseNestedMeta) -> syn::Result<()> {
1310            if meta.path.is_ident("name") {
1311                self.name = Some(meta.value()?.parse::<syn::LitStr>()?.value());
1312                Ok(())
1313            } else if meta.path.is_ident("log2_stack_bytes") {
1314                self.log2_stack_bytes = Some(meta.value()?.parse::<syn::LitInt>()?.base10_parse()?);
1315                Ok(())
1316            } else if meta.path.is_ident("instance") {
1317                self.instance = Some(meta.value()?.parse()?);
1318                Ok(())
1319            } else if meta.path.is_ident("runtime_data_default") {
1320                self.runtime_data_default = Some(meta.value()?.parse()?);
1321                Ok(())
1322            } else {
1323                Err(syn::Error::new(
1324                    meta.path.span(),
1325                    "Unknown attribute. Valid attributes are: name, instance, log2_stack_bytes and runtime_data_default",
1326                ))
1327            }
1328        }
1329    }
1330
1331    let mut attrs = ProcessNodeAttrs::default();
1332    let attr_parser = syn::meta::parser(|meta| attrs.parse(meta));
1333    syn::parse_macro_input!(attributes with attr_parser);
1334    let ProcessNodeAttrs {
1335        name,
1336        instance,
1337        log2_stack_bytes,
1338        runtime_data_default,
1339    } = attrs;
1340
1341    let item: syn::Item = syn::parse_macro_input!(item);
1342    if let syn::Item::Struct(syn::ItemStruct {
1343        attrs,
1344        vis,
1345        struct_token,
1346        ident,
1347        generics,
1348        fields,
1349        semi_token,
1350    }) = item
1351    {
1352        let name = name.expect("Missing attribute \"name\". This is required.");
1353        let name_lit = format!("{}\0", name);
1354        let instance = instance.expect("Missing attribute \"instance\". This is required.");
1355        let reg_ident =
1356            syn::parse_str::<syn::Ident>(format!("{}_NODE_REGISTRATION", ident).as_ref())
1357                .expect("Unable to create identifier");
1358        let add_node_fn_ident = syn::parse_str::<syn::Ident>(
1359            format!("__vlib_add_node_registration_{}", ident).as_ref(),
1360        )
1361        .expect("Unable to create identifier");
1362        let rm_node_fn_ident =
1363            syn::parse_str::<syn::Ident>(format!("__vlib_rm_node_registration_{}", ident).as_ref())
1364                .expect("Unable to create identifier");
1365        let raw_node_fn_ident = syn::parse_str::<syn::Ident>(format!("__fn_{}", ident).as_ref())
1366            .expect("Unable to create identifier");
1367        let runtime_data = match runtime_data_default {
1368            Some(runtime_data_default) => {
1369                // It would be ideal to use #runtime_data::default() here, but we cannot call that in a const context and we need to here
1370                quote!(::std::ptr::addr_of!(#runtime_data_default) as *mut ::std::os::raw::c_void)
1371            }
1372            None => quote!({
1373                ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::ProcessNode>::RuntimeData>() == 0);
1374                std::ptr::null_mut()
1375            }),
1376        };
1377        let log2_stack_bytes = log2_stack_bytes.unwrap_or_default();
1378
1379        let output = quote!(
1380            #(#attrs)*
1381            #vis #struct_token #ident #generics #fields #semi_token
1382
1383            #[::vpp_plugin::macro_support::ctor::ctor(crate_path = ::vpp_plugin::macro_support::ctor)]
1384            fn #add_node_fn_ident() {
1385                unsafe {
1386                    #reg_ident.register();
1387                }
1388            }
1389
1390            #[::vpp_plugin::macro_support::ctor::dtor(crate_path = ::vpp_plugin::macro_support::ctor)]
1391            fn #rm_node_fn_ident() {
1392                unsafe {
1393                    #reg_ident.unregister();
1394                }
1395            }
1396
1397            #[doc(hidden)]
1398            unsafe extern "C" fn #raw_node_fn_ident(
1399                vm: *mut ::vpp_plugin::bindings::vlib_main_t,
1400                node: *mut ::vpp_plugin::bindings::vlib_node_runtime_t,
1401                frame: *mut ::vpp_plugin::bindings::vlib_frame_t,
1402            ) -> ::vpp_plugin::bindings::uword {
1403                let fut = <#ident as ::vpp_plugin::vlib::ProcessNode>::function(
1404                    &#instance,
1405                    ::vpp_plugin::vlib::MainRef::from_ptr_mut(vm),
1406                    #reg_ident.node_runtime_from_ptr(node),
1407                );
1408                let pinned_fut = ::std::pin::pin!(fut);
1409                let context = ::vpp_plugin::vlib::process_node::ProcessAsyncContext::new(
1410                    ::vpp_plugin::vlib::MainRef::from_ptr_mut(vm),
1411                    #reg_ident.node_runtime_from_ptr(node),
1412                    ::vpp_plugin::vlib::process_node::LocalFutureObj::new(pinned_fut)
1413                );
1414                context.run();
1415            }
1416
1417            static #reg_ident: ::vpp_plugin::vlib::process_node::ProcessNodeRegistration<#ident, { <<#ident as ::vpp_plugin::vlib::ProcessNode>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES.len() }> = ::vpp_plugin::vlib::process_node::ProcessNodeRegistration::new(
1418                ::vpp_plugin::bindings::_vlib_node_registration {
1419                    function: Some(#raw_node_fn_ident),
1420                    name: #name_lit.as_ptr() as *mut ::std::os::raw::c_char,
1421                    type_: ::vpp_plugin::bindings::vlib_node_type_t_VLIB_NODE_TYPE_PROCESS,
1422                    error_counters: <<#ident as ::vpp_plugin::vlib::ProcessNode>::Errors as ::vpp_plugin::vlib::node::ErrorCounters>::C_DESCRIPTIONS.as_ptr().cast_mut(),
1423                    runtime_data: #runtime_data,
1424                    runtime_data_bytes: {
1425                        ::vpp_plugin::const_assert!(::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::ProcessNode>::RuntimeData>() <= u8::MAX as usize);
1426                        ::vpp_plugin::const_assert!(::std::mem::align_of::<<#ident as ::vpp_plugin::vlib::ProcessNode>::RuntimeData>() <= ::vpp_plugin::vlib::node::RUNTIME_DATA_ALIGN);
1427                        ::std::mem::size_of::<<#ident as ::vpp_plugin::vlib::ProcessNode>::RuntimeData>() as u8
1428                    },
1429                    n_errors: <<#ident as ::vpp_plugin::vlib::ProcessNode>::Errors as ::vpp_plugin::vlib::node::ErrorCounters>::C_DESCRIPTIONS.len()
1430                        as u16,
1431                    n_next_nodes: <<#ident as ::vpp_plugin::vlib::ProcessNode>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES.len()
1432                        as u16,
1433                    process_log2_n_stack_bytes: #log2_stack_bytes,
1434                    next_nodes: <<#ident as ::vpp_plugin::vlib::ProcessNode>::NextNodes as ::vpp_plugin::vlib::node::NextNodes>::C_NAMES,
1435                    ..::vpp_plugin::bindings::_vlib_node_registration::new()
1436                });
1437        );
1438
1439        // eprintln!("{}", output);
1440
1441        output.into()
1442    } else {
1443        panic!("#[vlib_process_node] items must be structs");
1444    }
1445}