Skip to main content

gwr_components/
test_helpers.rs

1// Copyright (c) 2023 Graphcore Ltd. All rights reserved.
2
3use std::cmp::min;
4use std::collections::HashMap;
5use std::rc::Rc;
6
7use futures::channel::oneshot;
8use futures::channel::oneshot::{Receiver, Sender};
9use gwr_engine::engine::Engine;
10use gwr_engine::port::{InPort, PortPut};
11use gwr_engine::time::clock::Clock;
12use gwr_engine::traits::SimObject;
13use gwr_engine::types::SimResult;
14use gwr_track::entity::Entity;
15#[doc(hidden)]
16pub use paste::paste;
17
18use crate::arbiter::Arbiter;
19use crate::arbiter::policy::{Priority, PriorityRoundRobin};
20use crate::flow_controls::limiter::Limiter;
21use crate::source::Source;
22use crate::store::ObjectStore;
23use crate::{connect_port, option_box_repeat, rc_limiter};
24
25#[derive(Clone)]
26pub struct ArbiterInputData {
27    pub val: usize,
28    pub count: usize,
29    pub weight: usize,
30    pub priority: Priority,
31}
32
33pub fn check_round_robin(inputs: &[ArbiterInputData], data: &[usize]) {
34    let total_count: usize = inputs.iter().map(|i| i.count).sum();
35    assert_eq!(data.len(), total_count);
36
37    let mut inputs = inputs.to_vec();
38    let mut offset = 0;
39    loop {
40        // Determine the count for each input value in the next window. Note
41        // that this copes with inputs producing the same value and inputs not
42        // producing their full weight in the window.
43        let mut expected_window_counts: HashMap<usize, usize> = HashMap::new();
44        let mut window_length = 0;
45        let max_priority = inputs
46            .iter()
47            .map(|i| {
48                if i.count > 0 {
49                    i.priority
50                } else {
51                    Priority::default()
52                }
53            })
54            .max()
55            .unwrap();
56        for input in &mut inputs {
57            let value_count = min(input.count, input.weight);
58            if input.priority == max_priority && value_count > 0 {
59                expected_window_counts
60                    .entry(input.val)
61                    .and_modify(|e| *e += value_count)
62                    .or_insert(value_count);
63
64                window_length += value_count;
65                input.count -= value_count;
66            }
67        }
68        if window_length == 0 {
69            return;
70        }
71
72        let mut window_counts = HashMap::new();
73        for value in data.iter().skip(offset).take(window_length) {
74            window_counts
75                .entry(*value)
76                .and_modify(|e| *e += 1)
77                .or_insert(1);
78        }
79        assert_eq!(window_counts, expected_window_counts);
80
81        offset += window_length;
82    }
83}
84
85pub fn priority_policy_test_core(engine: &mut Engine, inputs: &[ArbiterInputData]) {
86    let clock = engine.default_clock();
87    let num_inputs = inputs.len();
88    let total_count = inputs.iter().map(|e| e.count).sum();
89    let mut policy = PriorityRoundRobin::new(num_inputs);
90    for (i, input) in inputs.iter().enumerate() {
91        policy = policy.set_priority(i, input.priority);
92    }
93
94    let arbiter = Arbiter::new_and_register(
95        engine,
96        &clock,
97        engine.top(),
98        "arb",
99        num_inputs,
100        Box::new(policy),
101    );
102    let mut sources = Vec::new();
103    for (i, input) in inputs.iter().enumerate() {
104        sources.push(Source::new_and_register(
105            engine,
106            engine.top(),
107            &("source_".to_owned() + &i.to_string()),
108            option_box_repeat!(input.val; input.count),
109        ));
110    }
111
112    let write_limiter = rc_limiter!(&clock, 1).unwrap();
113    let store_limiter =
114        Limiter::new_and_register(engine, &clock, engine.top(), "limit_wr", write_limiter);
115    let store =
116        ObjectStore::new_and_register(engine, &clock, engine.top(), "store", total_count).unwrap();
117    connect_port!(store_limiter, tx => store, rx).unwrap();
118
119    for (i, source) in sources.iter_mut().enumerate() {
120        connect_port!(source, tx => arbiter, rx, i).unwrap();
121    }
122    connect_port!(arbiter, tx => store_limiter, rx).unwrap();
123
124    let mut port = InPort::new(
125        engine,
126        &clock,
127        &Rc::new(Entity::new(engine.top(), "port")),
128        "test_rx",
129    );
130    store.connect_port_tx(port.state()).unwrap();
131
132    let check_inputs = inputs.to_owned();
133    engine.spawn(async move {
134        let mut store_get = vec![0; total_count];
135        for i in &mut store_get {
136            *i = port.get()?.await;
137        }
138
139        check_round_robin(&check_inputs, &store_get);
140        Ok(())
141    });
142}
143
144pub fn one_shot_channel<T>() -> (Sender<T>, Receiver<T>) {
145    oneshot::channel()
146}
147
148pub trait NoTrafficPort {
149    fn has_traffic(&self) -> bool;
150}
151
152impl<T> NoTrafficPort for InPort<T>
153where
154    T: SimObject,
155{
156    fn has_traffic(&self) -> bool {
157        self.has_value()
158    }
159}
160
161pub async fn expect_no_traffic(
162    location: &str,
163    clock: &Clock,
164    ticks: u64,
165    receivers: Vec<(&'static str, &dyn NoTrafficPort)>,
166) -> SimResult {
167    clock.wait_ticks(ticks)?.await;
168    for (port_name, receiver) in receivers {
169        if receiver.has_traffic() {
170            panic!("{location}: unexpected {port_name} traffic");
171        }
172    }
173
174    Ok(())
175}
176
177pub async fn expect_pending_send<T>(
178    location: impl std::fmt::Display,
179    clock: &Clock,
180    port: impl std::fmt::Debug,
181    mut send: PortPut<T>,
182    ticks: u64,
183) -> SimResult
184where
185    T: SimObject,
186{
187    let mut timeout = clock.wait_ticks(ticks)?;
188
189    futures::select! {
190        _ = send => {
191            panic!("{location}: {port:?}: send completed before {ticks} ticks elapsed");
192        }
193        _ = timeout => {}
194    }
195
196    send.await;
197    Ok(())
198}
199
200pub trait ValueCheck<T> {
201    fn assert_matches(&self, check_id: &str, actual: &T);
202}
203
204impl<T> ValueCheck<T> for T
205where
206    T: PartialEq + std::fmt::Debug,
207{
208    fn assert_matches(&self, check_id: &str, actual: &T) {
209        assert_eq!(actual, self, "{check_id}: value mismatch");
210    }
211}
212
213#[derive(Clone, Copy, Debug)]
214pub struct StepLocation {
215    pub file: &'static str,
216    pub line: u32,
217    pub column: u32,
218}
219
220impl StepLocation {
221    #[must_use]
222    pub const fn new(file: &'static str, line: u32, column: u32) -> Self {
223        Self { file, line, column }
224    }
225}
226
227impl std::fmt::Display for StepLocation {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        write!(f, "{}:{}:{}", self.file, self.line, self.column)
230    }
231}
232
233/// Receive and check a value, retaining the packet for dependent steps.
234#[doc(hidden)]
235pub async fn expect_value<T, E>(
236    receiver: &mut InPort<T>,
237    expected: &E,
238    location: &str,
239) -> Result<T, gwr_engine::types::SimError>
240where
241    T: SimObject,
242    E: ValueCheck<T>,
243{
244    let actual = receiver.get()?.await;
245    expected.assert_matches(location, &actual);
246    Ok(actual)
247}
248
249/// A cloneable script factory. Each execution creates a fresh future and
250/// locals.
251#[doc(hidden)]
252pub struct HarnessScript<P> {
253    run: Rc<dyn Fn(P) -> HarnessScriptFuture<P>>,
254}
255
256#[doc(hidden)]
257pub type HarnessScriptFuture<P> =
258    std::pin::Pin<Box<dyn std::future::Future<Output = Result<P, gwr_engine::types::SimError>>>>;
259
260impl<P> HarnessScript<P> {
261    pub fn new<F, Fut>(run: F) -> Self
262    where
263        F: FnOnce(P) -> Fut + Clone + 'static,
264        Fut: std::future::Future<Output = Result<P, gwr_engine::types::SimError>> + 'static,
265    {
266        Self {
267            run: Rc::new(move |ports| Box::pin(run.clone()(ports))),
268        }
269    }
270
271    pub fn run(&self, ports: P) -> HarnessScriptFuture<P> {
272        (self.run)(ports)
273    }
274}
275
276impl<P> Clone for HarnessScript<P> {
277    fn clone(&self) -> Self {
278        Self {
279            run: self.run.clone(),
280        }
281    }
282}
283
284impl<P> std::fmt::Debug for HarnessScript<P> {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        f.write_str("HarnessScript")
287    }
288}
289
290// Only the capture list is parsed. Rust owns the entire async body.
291#[doc(hidden)]
292#[macro_export]
293macro_rules! __define_harness_script {
294    (($d:tt);
295        [$($scalar_variant:ident => $scalar_field:ident),* $(,)?];
296        [$($array_variant:ident => $array_field:ident),* $(,)?]
297    ) => {
298        #[allow(unused_macros)]
299        macro_rules! script {
300            (ports { $d($d binding:ident = $d variant:ident $d([$d index:expr])?),* $d(,)? }
301                async $d body:block
302            ) => {{
303                let selected_ports: Vec<Port> = vec![
304                    $d(script_port!(@select $d variant $d([$d index])?)),*
305                ];
306                Step::script(
307                    selected_ports.clone(),
308                    step_location!(),
309                    move |mut runner_ports| async move {
310                        #[allow(unused_mut, unused_variables)]
311                        let mut selectors = selected_ports.iter().copied();
312                        $d(
313                            #[allow(unused_mut, unused_variables)]
314                            let mut $d binding = script_port!(
315                                @take runner_ports; $d variant, selectors.next().unwrap()
316                            );
317                        )*
318                        let result: gwr_engine::types::SimResult = (async $d body).await;
319                        #[allow(unused_mut, unused_variables)]
320                        let mut selectors = selected_ports.iter().copied();
321                        $d(script_port!(
322                            @return runner_ports; $d variant, selectors.next().unwrap(), $d binding
323                        );)*
324                        result?;
325                        Ok(runner_ports)
326                    },
327                )
328            }};
329        }
330
331        #[allow(unused_macros)]
332        macro_rules! script_port {
333            $(
334                (@select $scalar_variant) => { Port::$scalar_variant };
335                (@take $d ports:ident; $scalar_variant, $d selector:expr) => {{
336                    let _ = $d selector;
337                    $d ports.$scalar_field.take()
338                        .expect(concat!(stringify!($scalar_variant), " port already taken"))
339                }};
340                (@return $d ports:ident; $scalar_variant, $d selector:expr, $d value:expr) => {{
341                    let _ = $d selector;
342                    $d ports.$scalar_field = Some($d value);
343                }};
344            )*
345            $(
346                (@select $array_variant [$d index:expr]) => { Port::$array_variant($d index) };
347                (@take $d ports:ident; $array_variant, $d selector:expr) => {{
348                    let Port::$array_variant(index) = $d selector else { unreachable!() };
349                    $d ports.$array_field.get_mut(index).and_then(Option::take)
350                        .expect(concat!(stringify!($array_variant), " index out of range or port already taken"))
351                }};
352                (@return $d ports:ident; $array_variant, $d selector:expr, $d value:expr) => {{
353                    let Port::$array_variant(index) = $d selector else { unreachable!() };
354                    $d ports.$array_field[index] = Some($d value);
355                }};
356            )*
357        }
358
359        #[allow(unused_macros)]
360        macro_rules! seq {
361            ($d steps:expr $d(,)?) => {
362                Step::Seq {
363                    location: step_location!(),
364                    steps: $d steps.into_iter().collect(),
365                }
366            };
367            ($d($d step:expr);+ $d(;)?) => {
368                seq!([$d($d step),+])
369            };
370        }
371    };
372}
373
374/// Build a simulation test harness around a component.
375///
376/// This macro generates the harness struct, local `Port`/`Step` enums, helper
377/// macros, fixed step execution, stateful step generators, and recursive
378/// sequence/parallel step driving for a component testbench.
379///
380/// See the crate-level Testing documentation for the intended usage pattern,
381/// generated API, and examples.
382#[macro_export]
383macro_rules! build_component_harness {
384    (
385        $(#[$meta:meta])*
386        $vis:vis harness $harness:ident <$item:ident> {
387            component: $component_field:ident : $component_ty:ty,
388            $($sections:tt)*
389        }
390    ) => {
391        $crate::build_component_harness! {
392            @normalize
393            [$(#[$meta])*]
394            [$vis]
395            [$harness]
396            [$vis struct $harness<$item> where $item: gwr_engine::traits::SimObject]
397            [impl<$item> $harness<$item> where $item: gwr_engine::traits::SimObject]
398            [<$item, Expected>]
399            [Expected]
400            [()]
401            [where $item: gwr_engine::traits::SimObject]
402            [$item]
403            [$component_field: $component_ty]
404            []
405            []
406            []
407            []
408            $($sections)*
409        }
410    };
411
412    (
413        @normalize
414        [$($meta:tt)*]
415        [$vis:vis]
416        [$harness:ident]
417        [$($struct_head:tt)+]
418        [$($impl_head:tt)+]
419        [$($step_generics_decl:tt)*]
420        [$expected_ident:ident]
421        [$expected_ty:ty]
422        [$($step_where:tt)*]
423        [$item_ty:ty]
424        [$component_field:ident : $component_ty:ty]
425        [$($rx_ports:tt)*]
426        [$($tx_ports:tt)*]
427        [$($rx_port_arrays:tt)*]
428        [$($tx_port_arrays:tt)*]
429        rx ports: { $($rx_section:tt)* }, $($rest:tt)*
430    ) => {
431        $crate::build_component_harness! {
432            @normalize
433            [$($meta)*]
434            [$vis]
435            [$harness]
436            [$($struct_head)*]
437            [$($impl_head)*]
438            [$($step_generics_decl)*]
439            [$expected_ident]
440            [$expected_ty]
441            [$($step_where)*]
442            [$item_ty]
443            [$component_field: $component_ty]
444            [$($rx_section)*]
445            [$($tx_ports)*]
446            [$($rx_port_arrays)*]
447            [$($tx_port_arrays)*]
448            $($rest)*
449        }
450    };
451
452    (
453        @normalize
454        [$($meta:tt)*]
455        [$vis:vis]
456        [$harness:ident]
457        [$($struct_head:tt)+]
458        [$($impl_head:tt)+]
459        [$($step_generics_decl:tt)*]
460        [$expected_ident:ident]
461        [$expected_ty:ty]
462        [$($step_where:tt)*]
463        [$item_ty:ty]
464        [$component_field:ident : $component_ty:ty]
465        [$($rx_ports:tt)*]
466        [$($tx_ports:tt)*]
467        [$($rx_port_arrays:tt)*]
468        [$($tx_port_arrays:tt)*]
469        rx ports: { $($rx_section:tt)* }
470    ) => {
471        $crate::build_component_harness! {
472            @normalize
473            [$($meta)*]
474            [$vis]
475            [$harness]
476            [$($struct_head)*]
477            [$($impl_head)*]
478            [$($step_generics_decl)*]
479            [$expected_ident]
480            [$expected_ty]
481            [$($step_where)*]
482            [$item_ty]
483            [$component_field: $component_ty]
484            [$($rx_section)*]
485            [$($tx_ports)*]
486            [$($rx_port_arrays)*]
487            [$($tx_port_arrays)*]
488        }
489    };
490
491    (
492        @normalize
493        [$($meta:tt)*]
494        [$vis:vis]
495        [$harness:ident]
496        [$($struct_head:tt)+]
497        [$($impl_head:tt)+]
498        [$($step_generics_decl:tt)*]
499        [$expected_ident:ident]
500        [$expected_ty:ty]
501        [$($step_where:tt)*]
502        [$item_ty:ty]
503        [$component_field:ident : $component_ty:ty]
504        [$($rx_ports:tt)*]
505        [$($tx_ports:tt)*]
506        [$($rx_port_arrays:tt)*]
507        [$($tx_port_arrays:tt)*]
508        tx ports: { $($tx_section:tt)* }, $($rest:tt)*
509    ) => {
510        $crate::build_component_harness! {
511            @normalize
512            [$($meta)*]
513            [$vis]
514            [$harness]
515            [$($struct_head)*]
516            [$($impl_head)*]
517            [$($step_generics_decl)*]
518            [$expected_ident]
519            [$expected_ty]
520            [$($step_where)*]
521            [$item_ty]
522            [$component_field: $component_ty]
523            [$($rx_ports)*]
524            [$($tx_section)*]
525            [$($rx_port_arrays)*]
526            [$($tx_port_arrays)*]
527            $($rest)*
528        }
529    };
530
531    (
532        @normalize
533        [$($meta:tt)*]
534        [$vis:vis]
535        [$harness:ident]
536        [$($struct_head:tt)+]
537        [$($impl_head:tt)+]
538        [$($step_generics_decl:tt)*]
539        [$expected_ident:ident]
540        [$expected_ty:ty]
541        [$($step_where:tt)*]
542        [$item_ty:ty]
543        [$component_field:ident : $component_ty:ty]
544        [$($rx_ports:tt)*]
545        [$($tx_ports:tt)*]
546        [$($rx_port_arrays:tt)*]
547        [$($tx_port_arrays:tt)*]
548        tx ports: { $($tx_section:tt)* }
549    ) => {
550        $crate::build_component_harness! {
551            @normalize
552            [$($meta)*]
553            [$vis]
554            [$harness]
555            [$($struct_head)*]
556            [$($impl_head)*]
557            [$($step_generics_decl)*]
558            [$expected_ident]
559            [$expected_ty]
560            [$($step_where)*]
561            [$item_ty]
562            [$component_field: $component_ty]
563            [$($rx_ports)*]
564            [$($tx_section)*]
565            [$($rx_port_arrays)*]
566            [$($tx_port_arrays)*]
567        }
568    };
569
570    (
571        @normalize
572        [$($meta:tt)*]
573        [$vis:vis]
574        [$harness:ident]
575        [$($struct_head:tt)+]
576        [$($impl_head:tt)+]
577        [$($step_generics_decl:tt)*]
578        [$expected_ident:ident]
579        [$expected_ty:ty]
580        [$($step_where:tt)*]
581        [$item_ty:ty]
582        [$component_field:ident : $component_ty:ty]
583        [$($rx_ports:tt)*]
584        [$($tx_ports:tt)*]
585        [$($rx_port_arrays:tt)*]
586        [$($tx_port_arrays:tt)*]
587        rx port arrays: { $($rx_array_section:tt)* }, $($rest:tt)*
588    ) => {
589        $crate::build_component_harness! {
590            @normalize
591            [$($meta)*]
592            [$vis]
593            [$harness]
594            [$($struct_head)*]
595            [$($impl_head)*]
596            [$($step_generics_decl)*]
597            [$expected_ident]
598            [$expected_ty]
599            [$($step_where)*]
600            [$item_ty]
601            [$component_field: $component_ty]
602            [$($rx_ports)*]
603            [$($tx_ports)*]
604            [$($rx_array_section)*]
605            [$($tx_port_arrays)*]
606            $($rest)*
607        }
608    };
609
610    (
611        @normalize
612        [$($meta:tt)*]
613        [$vis:vis]
614        [$harness:ident]
615        [$($struct_head:tt)+]
616        [$($impl_head:tt)+]
617        [$($step_generics_decl:tt)*]
618        [$expected_ident:ident]
619        [$expected_ty:ty]
620        [$($step_where:tt)*]
621        [$item_ty:ty]
622        [$component_field:ident : $component_ty:ty]
623        [$($rx_ports:tt)*]
624        [$($tx_ports:tt)*]
625        [$($rx_port_arrays:tt)*]
626        [$($tx_port_arrays:tt)*]
627        rx port arrays: { $($rx_array_section:tt)* }
628    ) => {
629        $crate::build_component_harness! {
630            @normalize
631            [$($meta)*]
632            [$vis]
633            [$harness]
634            [$($struct_head)*]
635            [$($impl_head)*]
636            [$($step_generics_decl)*]
637            [$expected_ident]
638            [$expected_ty]
639            [$($step_where)*]
640            [$item_ty]
641            [$component_field: $component_ty]
642            [$($rx_ports)*]
643            [$($tx_ports)*]
644            [$($rx_array_section)*]
645            [$($tx_port_arrays)*]
646        }
647    };
648
649    (
650        @normalize
651        [$($meta:tt)*]
652        [$vis:vis]
653        [$harness:ident]
654        [$($struct_head:tt)+]
655        [$($impl_head:tt)+]
656        [$($step_generics_decl:tt)*]
657        [$expected_ident:ident]
658        [$expected_ty:ty]
659        [$($step_where:tt)*]
660        [$item_ty:ty]
661        [$component_field:ident : $component_ty:ty]
662        [$($rx_ports:tt)*]
663        [$($tx_ports:tt)*]
664        [$($rx_port_arrays:tt)*]
665        [$($tx_port_arrays:tt)*]
666        tx port arrays: { $($tx_array_section:tt)* }, $($rest:tt)*
667    ) => {
668        $crate::build_component_harness! {
669            @normalize
670            [$($meta)*]
671            [$vis]
672            [$harness]
673            [$($struct_head)*]
674            [$($impl_head)*]
675            [$($step_generics_decl)*]
676            [$expected_ident]
677            [$expected_ty]
678            [$($step_where)*]
679            [$item_ty]
680            [$component_field: $component_ty]
681            [$($rx_ports)*]
682            [$($tx_ports)*]
683            [$($rx_port_arrays)*]
684            [$($tx_array_section)*]
685            $($rest)*
686        }
687    };
688
689    (
690        @normalize
691        [$($meta:tt)*]
692        [$vis:vis]
693        [$harness:ident]
694        [$($struct_head:tt)+]
695        [$($impl_head:tt)+]
696        [$($step_generics_decl:tt)*]
697        [$expected_ident:ident]
698        [$expected_ty:ty]
699        [$($step_where:tt)*]
700        [$item_ty:ty]
701        [$component_field:ident : $component_ty:ty]
702        [$($rx_ports:tt)*]
703        [$($tx_ports:tt)*]
704        [$($rx_port_arrays:tt)*]
705        [$($tx_port_arrays:tt)*]
706        tx port arrays: { $($tx_array_section:tt)* }
707    ) => {
708        $crate::build_component_harness! {
709            @normalize
710            [$($meta)*]
711            [$vis]
712            [$harness]
713            [$($struct_head)*]
714            [$($impl_head)*]
715            [$($step_generics_decl)*]
716            [$expected_ident]
717            [$expected_ty]
718            [$($step_where)*]
719            [$item_ty]
720            [$component_field: $component_ty]
721            [$($rx_ports)*]
722            [$($tx_ports)*]
723            [$($rx_port_arrays)*]
724            [$($tx_array_section)*]
725        }
726    };
727
728    (
729        @normalize
730        [$($meta:tt)*]
731        [$vis:vis]
732        [$harness:ident]
733        [$($struct_head:tt)+]
734        [$($impl_head:tt)+]
735        [$($step_generics_decl:tt)*]
736        [$expected_ident:ident]
737        [$expected_ty:ty]
738        [$($step_where:tt)*]
739        [$item_ty:ty]
740        [$component_field:ident : $component_ty:ty]
741        [$($rx_ports:tt)*]
742        [$($tx_ports:tt)*]
743        [$($rx_port_arrays:tt)*]
744        [$($tx_port_arrays:tt)*]
745    ) => {
746        $crate::build_component_harness! {
747            @impl_inferred
748            [$($meta)*]
749            [$vis]
750            [$harness]
751            [$($struct_head)*]
752            [$($impl_head)*]
753            [$($step_generics_decl)*]
754            [$expected_ident]
755            [$expected_ty]
756            [$($step_where)*]
757            [$item_ty]
758            [$component_field: $component_ty]
759            rx ports: { $($rx_ports)* },
760            tx ports: { $($tx_ports)* },
761            rx port arrays: { $($rx_port_arrays)* },
762            tx port arrays: { $($tx_port_arrays)* },
763        }
764    };
765
766    (
767        @impl_inferred
768        [$($meta:tt)*]
769        [$vis:vis]
770        [$harness:ident]
771        [$($struct_head:tt)+]
772        [$($impl_head:tt)+]
773        [$($step_generics_decl:tt)*]
774        [$expected_ident:ident]
775        [$expected_ty:ty]
776        [$($step_where:tt)*]
777        [$item_ty:ty]
778        [$component_field:ident : $component_ty:ty]
779        rx ports: {
780            $(
781                $rx_variant:ident <$rx_ty:ty> => $rx_field:ident
782            ),* $(,)?
783        },
784        tx ports: {
785            $(
786                $tx_variant:ident <$tx_ty:ty> => $tx_field:ident
787            ),* $(,)?
788        },
789        rx port arrays: {
790            $(
791                $rx_array_variant:ident <$rx_array_ty:ty> => $rx_array_field:ident {
792                    count: $rx_array_count:ident
793                }
794            ),* $(,)?
795        },
796        tx port arrays: {
797            $(
798                $tx_array_variant:ident <$tx_array_ty:ty> => $tx_array_field:ident {
799                    count: $tx_array_count:ident
800                }
801            ),* $(,)?
802        } $(,)?
803    ) => {
804        $crate::build_component_harness! {
805            @impl
806            [$($meta)*]
807            [$vis]
808            [$harness]
809            [$($struct_head)*]
810            [$($impl_head)*]
811            [$($step_generics_decl)*]
812            [$expected_ident]
813            [$expected_ty]
814            [$($step_where)*]
815            [$item_ty]
816            [$component_field: $component_ty]
817            rx ports: {
818                $(
819                    $rx_variant <$rx_ty> => $rx_field {
820                        port: { [<port_ $rx_field>] }
821                    }
822                ),*
823            },
824            tx ports: {
825                $(
826                    $tx_variant <$tx_ty, $tx_ty> => $tx_field {
827                        connect: { [<connect_port_ $tx_field>] }
828                    }
829                ),*
830            },
831            rx port arrays: {
832                $(
833                    $rx_array_variant <$rx_array_ty> => $rx_array_field {
834                        port: { [<port_ $rx_array_field _i>] },
835                        count: $rx_array_count
836                    }
837                ),*
838            },
839            tx port arrays: {
840                $(
841                    $tx_array_variant <$tx_array_ty, $tx_array_ty> => $tx_array_field {
842                        connect: { [<connect_port_ $tx_array_field _i>] },
843                        count: $tx_array_count
844                    }
845                ),*
846            }
847        }
848    };
849
850    (
851        @impl_model
852        [$(#[$meta:meta])*]
853        [$vis:vis]
854        [$harness:ident]
855        [$item:ident]
856        [$default_expected:ty]
857        [$access_memory:path]
858        [$component_field:ident : $component_ty:ty]
859        rx ports: { $($rx_variant:ident <$rx_ty:ty> => $rx_field:ident),* $(,)? },
860        tx ports: { $($tx_variant:ident <$tx_ty:ty> => $tx_field:ident),* $(,)? },
861        rx port arrays: {
862            $($rx_array_variant:ident <$rx_array_ty:ty> => $rx_array_field:ident {
863                count: $rx_array_count:ident
864            }),* $(,)?
865        },
866        tx port arrays: {
867            $($tx_array_variant:ident <$tx_array_ty:ty> => $tx_array_field:ident {
868                count: $tx_array_count:ident
869            }),* $(,)?
870        } $(,)?
871    ) => {
872        $crate::build_component_harness! {
873            @impl
874            [$(#[$meta])*]
875            [$vis]
876            [$harness]
877            [
878                $vis struct $harness<$item>
879                where
880                    $item: $access_memory
881                        + gwr_engine::traits::SimObject
882                        + Clone
883                        + std::fmt::Debug
884                        + 'static
885            ]
886            [
887                impl<$item> $harness<$item>
888                where
889                    $item: $access_memory
890                        + gwr_engine::traits::SimObject
891                        + Clone
892                        + std::fmt::Debug
893                        + 'static
894            ]
895            [<$item, Expected>]
896            [Expected]
897            [$default_expected]
898            [where
899                $item: $access_memory
900                    + gwr_engine::traits::SimObject
901                    + Clone
902                    + std::fmt::Debug
903                    + 'static
904            ]
905            [$item]
906            [$component_field: $component_ty]
907            rx ports: {
908                $(
909                    $rx_variant <$rx_ty> => $rx_field {
910                        port: { [<port_ $rx_field>] }
911                    }
912                ),*
913            },
914            tx ports: {
915                $(
916                    $tx_variant <$tx_ty, $default_expected> => $tx_field {
917                        connect: { [<connect_port_ $tx_field>] }
918                    }
919                ),*
920            },
921            rx port arrays: {
922                $(
923                    $rx_array_variant <$rx_array_ty> => $rx_array_field {
924                        port: { [<port_ $rx_array_field _i>] },
925                        count: $rx_array_count
926                    }
927                ),*
928            },
929            tx port arrays: {
930                $(
931                    $tx_array_variant <$tx_array_ty, $default_expected> => $tx_array_field {
932                        connect: { [<connect_port_ $tx_array_field _i>] },
933                        count: $tx_array_count
934                    }
935                ),*
936            },
937        }
938    };
939
940    (
941        @impl
942        [$(#[$meta:meta])*]
943        [$vis:vis]
944        [$harness:ident]
945        [$($struct_head:tt)+]
946        [$($impl_head:tt)+]
947        [$($step_generics_decl:tt)*]
948        [$expected_ident:ident]
949        [$expected_ty:ty]
950        [$($step_where:tt)*]
951        [$item_ty:ty]
952        [$component_field:ident : $component_ty:ty]
953        rx ports: {
954            $(
955                $rx_variant:ident <$rx_ty:ty> => $rx_field:ident {
956                    port: { $($rx_method:tt)+ }
957                }
958            ),* $(,)?
959        },
960        tx ports: {
961            $(
962                $tx_variant:ident <$tx_ty:ty, $tx_expected_ty:ty> => $tx_field:ident {
963                    connect: { $($tx_method:tt)+ }
964                }
965            ),* $(,)?
966        },
967        rx port arrays: {
968            $(
969                $rx_array_variant:ident <$rx_array_ty:ty> => $rx_array_field:ident {
970                    port: { $($rx_array_method:tt)+ },
971                    count: $rx_array_count:ident
972                }
973            ),* $(,)?
974        },
975        tx port arrays: {
976            $(
977                $tx_array_variant:ident <$tx_array_ty:ty, $tx_array_expected_ty:ty> => $tx_array_field:ident {
978                    connect: { $($tx_array_method:tt)+ },
979                    count: $tx_array_count:ident
980                }
981            ),* $(,)?
982        } $(,)?
983    ) => {
984        $crate::test_helpers::paste! {
985            #[derive(Clone, Copy, Debug, PartialEq, Eq, std::hash::Hash)]
986            $vis enum Port {
987                $($rx_variant,)*
988                $($tx_variant,)*
989                $($rx_array_variant(usize),)*
990                $($tx_array_variant(usize),)*
991            }
992
993            #[derive(Clone, Debug)]
994            #[must_use = "harness steps must be executed with run_steps, seq!, or par!"]
995            $vis enum Step<$item_ty, $expected_ident = ()> $($step_where)* {
996                Script {
997                    location: $crate::test_helpers::StepLocation,
998                    ports: Vec<Port>,
999                    script: $crate::test_helpers::HarnessScript<[<$harness Ports>]<$item_ty>>,
1000                },
1001                Seq {
1002                    location: $crate::test_helpers::StepLocation,
1003                    steps: Vec<Step<$item_ty, $expected_ty>>,
1004                },
1005                Par {
1006                    location: $crate::test_helpers::StepLocation,
1007                    steps: Vec<Step<$item_ty, $expected_ty>>,
1008                },
1009                $([<Send $rx_variant>] {
1010                    location: $crate::test_helpers::StepLocation,
1011                    port: Port,
1012                    value: $rx_ty,
1013                },)*
1014                $([<ExpectPendingSend $rx_variant>] {
1015                    location: $crate::test_helpers::StepLocation,
1016                    port: Port,
1017                    value: $rx_ty,
1018                    ticks: u64,
1019                },)*
1020                $([<Expect $tx_variant>] {
1021                    location: $crate::test_helpers::StepLocation,
1022                    port: Port,
1023                    value: $tx_expected_ty,
1024                },)*
1025                $([<Send $rx_array_variant>] {
1026                    location: $crate::test_helpers::StepLocation,
1027                    port: Port,
1028                    value: $rx_array_ty,
1029                },)*
1030                $([<ExpectPendingSend $rx_array_variant>] {
1031                    location: $crate::test_helpers::StepLocation,
1032                    port: Port,
1033                    value: $rx_array_ty,
1034                    ticks: u64,
1035                },)*
1036                $([<Expect $tx_array_variant>] {
1037                    location: $crate::test_helpers::StepLocation,
1038                    port: Port,
1039                    value: $tx_array_expected_ty,
1040                },)*
1041                ExpectNoTraffic {
1042                    location: $crate::test_helpers::StepLocation,
1043                    ports: Vec<Port>,
1044                    ticks: u64,
1045                },
1046                Delay {
1047                    location: $crate::test_helpers::StepLocation,
1048                    ports: Vec<Port>,
1049                    ticks: u64,
1050                },
1051                #[doc(hidden)]
1052                __Expected(std::marker::PhantomData<fn() -> $expected_ident>),
1053            }
1054
1055            impl<$item_ty, $expected_ident> Step<$item_ty, $expected_ident> $($step_where)* {
1056                fn script<F, Fut>(
1057                    ports: Vec<Port>,
1058                    location: $crate::test_helpers::StepLocation,
1059                    run: F,
1060                ) -> Self
1061                where
1062                    F: FnOnce([<$harness Ports>]<$item_ty>) -> Fut
1063                        + Clone + 'static,
1064                    Fut: std::future::Future<Output = Result<[<$harness Ports>]<$item_ty>, gwr_engine::types::SimError>> + 'static,
1065                {
1066                    let mut unique_ports = std::collections::HashSet::new();
1067                    for port in &ports {
1068                        assert!(unique_ports.insert(*port), "{location}: {port:?} captured more than once");
1069                    }
1070                    Self::Script {
1071                        location,
1072                        ports,
1073                        script: $crate::test_helpers::HarnessScript::new(run),
1074                    }
1075                }
1076
1077                fn location(&self) -> $crate::test_helpers::StepLocation {
1078                    match self {
1079                        Step::Script { location, .. }
1080                        | Step::Seq { location, .. }
1081                        | Step::Par { location, .. }
1082                        $(| Step::[<Send $rx_variant>] { location, .. })*
1083                        $(| Step::[<ExpectPendingSend $rx_variant>] { location, .. })*
1084                        $(| Step::[<Expect $tx_variant>] { location, .. })*
1085                        $(| Step::[<Send $rx_array_variant>] { location, .. })*
1086                        $(| Step::[<ExpectPendingSend $rx_array_variant>] { location, .. })*
1087                        $(| Step::[<Expect $tx_array_variant>] { location, .. })*
1088                        | Step::ExpectNoTraffic { location, .. }
1089                        | Step::Delay { location, .. } => *location,
1090                        Step::__Expected(_) => {
1091                            unreachable!("marker variant is not a harness step");
1092                        }
1093                    }
1094                }
1095            }
1096
1097            #[doc(hidden)]
1098            $vis struct [<$harness Ports>]<$item_ty> $($step_where)* {
1099                $(
1100                    [<$rx_field _driver>]: Option<gwr_engine::port::OutPort<$rx_ty>>,
1101                )*
1102                $(
1103                    [<$tx_field _receiver>]: Option<gwr_engine::port::InPort<$tx_ty>>,
1104                )*
1105                $(
1106                    [<$rx_array_field _drivers>]: Vec<Option<gwr_engine::port::OutPort<$rx_array_ty>>>,
1107                )*
1108                $(
1109                    [<$tx_array_field _receivers>]: Vec<Option<gwr_engine::port::InPort<$tx_array_ty>>>,
1110                )*
1111                _item: std::marker::PhantomData<fn() -> $item_ty>,
1112            }
1113
1114            impl<$item_ty> [<$harness Ports>]<$item_ty> $($step_where)* {
1115                fn new_empty(&self) -> Self {
1116                    Self {
1117                        $(
1118                            [<$rx_field _driver>]: None,
1119                        )*
1120                        $(
1121                            [<$tx_field _receiver>]: None,
1122                        )*
1123                        $(
1124                            [<$rx_array_field _drivers>]: std::iter::repeat_with(|| None)
1125                                .take(self.[<$rx_array_field _drivers>].len())
1126                                .collect(),
1127                        )*
1128                        $(
1129                            [<$tx_array_field _receivers>]: std::iter::repeat_with(|| None)
1130                                .take(self.[<$tx_array_field _receivers>].len())
1131                                .collect(),
1132                        )*
1133                        _item: std::marker::PhantomData,
1134                    }
1135                }
1136
1137                fn take_selected(
1138                    &mut self,
1139                    selected: &std::collections::HashSet<Port>,
1140                    location: &str,
1141                ) -> Self {
1142                    let mut port_collection = self.new_empty();
1143                    for port in selected {
1144                        match *port {
1145                            $(
1146                            Port::$rx_variant => {
1147                                port_collection.[<$rx_field _driver>] = Some(
1148                                    self.[<$rx_field _driver>]
1149                                        .take()
1150                                        .unwrap_or_else(|| panic!("{location}: {} driver already taken", stringify!($rx_field))),
1151                                );
1152                            }
1153                            )*
1154                            $(
1155                            Port::$tx_variant => {
1156                                port_collection.[<$tx_field _receiver>] = Some(
1157                                    self.[<$tx_field _receiver>]
1158                                        .take()
1159                                        .unwrap_or_else(|| panic!("{location}: {} receiver already taken", stringify!($tx_field))),
1160                                );
1161                            }
1162                            )*
1163                            $(
1164                            Port::$rx_array_variant(idx) => {
1165                                port_collection.[<$rx_array_field _drivers>][idx] = Some(
1166                                    self.[<$rx_array_field _drivers>]
1167                                        .get_mut(idx)
1168                                        .and_then(|driver| driver.take())
1169                                        .unwrap_or_else(|| panic!("{location}: {} driver index {idx} out of range or already taken", stringify!($rx_array_field))),
1170                                );
1171                            }
1172                            )*
1173                            $(
1174                            Port::$tx_array_variant(idx) => {
1175                                port_collection.[<$tx_array_field _receivers>][idx] = Some(
1176                                    self.[<$tx_array_field _receivers>]
1177                                        .get_mut(idx)
1178                                        .and_then(|receiver| receiver.take())
1179                                        .unwrap_or_else(|| panic!("{location}: {} receiver index {idx} out of range or already taken", stringify!($tx_array_field))),
1180                                );
1181                            }
1182                            )*
1183                        }
1184                    }
1185                    port_collection
1186                }
1187
1188                fn return_ports(&mut self, mut port_collection: Self, location: &str) {
1189                    $(
1190                    if let Some(driver) = port_collection.[<$rx_field _driver>].take() {
1191                        if self.[<$rx_field _driver>].replace(driver).is_some() {
1192                            panic!("{location}: {} driver returned twice", stringify!($rx_field));
1193                        }
1194                    }
1195                    )*
1196                    $(
1197                    if let Some(receiver) = port_collection.[<$tx_field _receiver>].take() {
1198                        if self.[<$tx_field _receiver>].replace(receiver).is_some() {
1199                            panic!("{location}: {} receiver returned twice", stringify!($tx_field));
1200                        }
1201                    }
1202                    )*
1203                    $(
1204                    for (idx, driver) in port_collection.[<$rx_array_field _drivers>].into_iter().enumerate() {
1205                        if let Some(driver) = driver {
1206                            if self.[<$rx_array_field _drivers>][idx].replace(driver).is_some() {
1207                                panic!("{location}: {} driver index {idx} returned twice", stringify!($rx_array_field));
1208                            }
1209                        }
1210                    }
1211                    )*
1212                    $(
1213                    for (idx, receiver) in port_collection.[<$tx_array_field _receivers>].into_iter().enumerate() {
1214                        if let Some(receiver) = receiver {
1215                            if self.[<$tx_array_field _receivers>][idx].replace(receiver).is_some() {
1216                                panic!("{location}: {} receiver index {idx} returned twice", stringify!($tx_array_field));
1217                            }
1218                        }
1219                    }
1220                    )*
1221                }
1222
1223                fn collect_step_ports(
1224                    step: &Step<$item_ty, $expected_ty>,
1225                    ports: &mut std::collections::HashSet<Port>,
1226                ) {
1227                    match step {
1228                        Step::<$item_ty, $expected_ty>::Seq { steps, .. }
1229                        | Step::<$item_ty, $expected_ty>::Par { steps, .. } => {
1230                            for step in steps {
1231                                Self::collect_step_ports(step, ports);
1232                            }
1233                        }
1234                        $(
1235                        Step::<$item_ty, $expected_ty>::[<Send $rx_variant>] { port, .. } => {
1236                            ports.insert(*port);
1237                        }
1238                        )*
1239                        $(
1240                        Step::<$item_ty, $expected_ty>::[<ExpectPendingSend $rx_variant>] { port, .. } => {
1241                            ports.insert(*port);
1242                        }
1243                        )*
1244                        $(
1245                        Step::<$item_ty, $expected_ty>::[<Expect $tx_variant>] { port, .. } => {
1246                            ports.insert(*port);
1247                        }
1248                        )*
1249                        $(
1250                        Step::<$item_ty, $expected_ty>::[<Send $rx_array_variant>] { port, .. } => {
1251                            ports.insert(*port);
1252                        }
1253                        )*
1254                        $(
1255                        Step::<$item_ty, $expected_ty>::[<ExpectPendingSend $rx_array_variant>] { port, .. } => {
1256                            ports.insert(*port);
1257                        }
1258                        )*
1259                        $(
1260                        Step::<$item_ty, $expected_ty>::[<Expect $tx_array_variant>] { port, .. } => {
1261                            ports.insert(*port);
1262                        }
1263                        )*
1264                        Step::<$item_ty, $expected_ty>::Script { ports: step_ports, .. }
1265                        | Step::<$item_ty, $expected_ty>::ExpectNoTraffic { ports: step_ports, .. } => {
1266                            ports.extend(step_ports.iter().copied());
1267                        }
1268                        Step::<$item_ty, $expected_ty>::Delay { ports: step_ports, .. } => {
1269                            ports.extend(step_ports.iter().copied());
1270                        }
1271                        Step::<$item_ty, $expected_ty>::__Expected(_) => {
1272                            unreachable!("marker variant is not a harness step");
1273                        }
1274                    }
1275                }
1276
1277                fn run_steps(
1278                    mut self,
1279                    steps: Vec<Step<$item_ty, $expected_ty>>,
1280                    clock: gwr_engine::time::clock::Clock,
1281                    spawner: gwr_engine::executor::Spawner,
1282                ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Self, gwr_engine::types::SimError>> + 'static>>
1283                where
1284                    $($rx_ty: Clone + 'static,)*
1285                    $($tx_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_ty> + 'static,)*
1286                    $($rx_array_ty: Clone + 'static,)*
1287                    $($tx_array_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_array_ty> + 'static,)*
1288                    $item_ty: 'static,
1289                    $expected_ty: 'static,
1290                {
1291                    Box::pin(async move {
1292                        for step in steps {
1293                            let location = step.location().to_string();
1294                            match step {
1295                                Step::<$item_ty, $expected_ty>::Script { script, .. } => {
1296                                    self = script.run(self).await?;
1297                                }
1298                                Step::<$item_ty, $expected_ty>::Seq { steps, .. } => {
1299                                    self = self.run_steps(steps, clock.clone(), spawner.clone()).await?;
1300                                }
1301                                Step::<$item_ty, $expected_ty>::Par { steps, .. } => {
1302                                    let mut completions = Vec::with_capacity(steps.len());
1303
1304                                    for step in steps {
1305                                        let branch_location = step.location().to_string();
1306                                        let mut branch_ports = std::collections::HashSet::new();
1307                                        Self::collect_step_ports(&step, &mut branch_ports);
1308                                        let branch_runner_ports = self.take_selected(&branch_ports, &branch_location);
1309                                        let branch_clock = clock.clone();
1310                                        let branch_spawner = spawner.clone();
1311                                        let (complete_tx, complete_rx) = $crate::test_helpers::one_shot_channel();
1312
1313                                        spawner.spawn(async move {
1314                                            let branch_steps = match step {
1315                                                Step::<$item_ty, $expected_ty>::Seq { steps, .. } => steps,
1316                                                step => vec![step],
1317                                            };
1318                                            let result = branch_runner_ports
1319                                                .run_steps(branch_steps, branch_clock, branch_spawner)
1320                                                .await;
1321                                            complete_tx
1322                                                .send((branch_location.clone(), result))
1323                                                .unwrap_or_else(|_| panic!("{branch_location}: parallel step receiver dropped"));
1324                                            Ok::<(), gwr_engine::types::SimError>(())
1325                                        });
1326                                        completions.push(complete_rx);
1327                                    }
1328
1329                                    for completion in completions {
1330                                        let (branch_location, result) = completion
1331                                            .await
1332                                            .unwrap_or_else(|_| panic!("{location}: parallel section dropped"));
1333                                        let returned = result?;
1334                                        self.return_ports(returned, &branch_location);
1335                                    }
1336                                }
1337                                $(
1338                                Step::<$item_ty, $expected_ty>::[<Send $rx_variant>] { port, value, .. } => {
1339                                    let Port::$rx_variant = port else {
1340                                        panic!("{location}: {port:?}: step is for {}", stringify!($rx_variant));
1341                                    };
1342                                    self.[<$rx_field _driver>]
1343                                        .as_mut()
1344                                        .expect(concat!(stringify!($rx_field), " driver already taken"))
1345                                        .put(value.clone())?
1346                                        .await;
1347                                }
1348                                )*
1349                                $(
1350                                Step::<$item_ty, $expected_ty>::[<ExpectPendingSend $rx_variant>] { port, value, ticks, .. } => {
1351                                    let Port::$rx_variant = port else {
1352                                        panic!("{location}: {port:?}: pending send step is for {}", stringify!($rx_variant));
1353                                    };
1354                                    let mut send = self.[<$rx_field _driver>]
1355                                        .as_mut()
1356                                        .expect(concat!(stringify!($rx_field), " driver already taken"))
1357                                        .put(value.clone())?;
1358                                    $crate::test_helpers::expect_pending_send(
1359                                        location,
1360                                        &clock,
1361                                        port,
1362                                        send,
1363                                        ticks,
1364                                    )
1365                                    .await?;
1366                                }
1367                                )*
1368                                $(
1369                                Step::<$item_ty, $expected_ty>::[<Expect $tx_variant>] { port, value, .. } => {
1370                                    let Port::$tx_variant = port else {
1371                                        panic!("{location}: {port:?}: step is for {}", stringify!($tx_variant));
1372                                    };
1373                                    $crate::test_helpers::expect_value(
1374                                        self.[<$tx_field _receiver>]
1375                                        .as_mut()
1376                                        .expect(concat!(stringify!($tx_field), " receiver already taken")),
1377                                        &value,
1378                                        &format!("{location} {port:?}"),
1379                                    ).await?;
1380                                }
1381                                )*
1382                                $(
1383                                Step::<$item_ty, $expected_ty>::[<Send $rx_array_variant>] { port, value, .. } => {
1384                                    let Port::$rx_array_variant(idx) = port else {
1385                                        panic!("{location}: {port:?}: step is for {}", stringify!($rx_array_variant));
1386                                    };
1387                                    self.[<$rx_array_field _drivers>]
1388                                        .get_mut(idx)
1389                                        .and_then(|driver| driver.as_mut())
1390                                        .unwrap_or_else(|| panic!("{location}: {} driver index {idx} out of range or already taken", stringify!($rx_array_field)))
1391                                        .put(value.clone())?
1392                                        .await;
1393                                }
1394                                )*
1395                                $(
1396                                Step::<$item_ty, $expected_ty>::[<ExpectPendingSend $rx_array_variant>] { port, value, ticks, .. } => {
1397                                    let Port::$rx_array_variant(idx) = port else {
1398                                        panic!("{location}: {port:?}: pending send step is for {}", stringify!($rx_array_variant));
1399                                    };
1400                                    let mut send = self.[<$rx_array_field _drivers>]
1401                                        .get_mut(idx)
1402                                        .and_then(|driver| driver.as_mut())
1403                                        .unwrap_or_else(|| panic!("{location}: {} driver index {idx} out of range or already taken", stringify!($rx_array_field)))
1404                                        .put(value.clone())?;
1405                                    $crate::test_helpers::expect_pending_send(
1406                                        location,
1407                                        &clock,
1408                                        port,
1409                                        send,
1410                                        ticks,
1411                                    )
1412                                    .await?;
1413                                }
1414                                )*
1415                                $(
1416                                Step::<$item_ty, $expected_ty>::[<Expect $tx_array_variant>] { port, value, .. } => {
1417                                    let Port::$tx_array_variant(idx) = port else {
1418                                        panic!("{location}: {port:?}: step is for {}", stringify!($tx_array_variant));
1419                                    };
1420                                    $crate::test_helpers::expect_value(
1421                                        self.[<$tx_array_field _receivers>]
1422                                        .get_mut(idx)
1423                                        .and_then(|receiver| receiver.as_mut())
1424                                        .unwrap_or_else(|| panic!("{location}: {} receiver index {idx} out of range or already taken", stringify!($tx_array_field))),
1425                                        &value,
1426                                        &format!("{location} {port:?}"),
1427                                    ).await?;
1428                                }
1429                                )*
1430                                Step::<$item_ty, $expected_ty>::ExpectNoTraffic { ports, ticks, .. } => {
1431                                    let mut receivers = Vec::new();
1432                                    for port in &ports {
1433                                        match port {
1434                                            $(
1435                                            Port::$tx_variant => {
1436                                                let receiver = self.[<$tx_field _receiver>]
1437                                                    .as_ref()
1438                                                    .expect(concat!(stringify!($tx_field), " receiver already taken"));
1439                                                receivers.push((stringify!($tx_field), receiver as &dyn $crate::test_helpers::NoTrafficPort));
1440                                            }
1441                                            )*
1442                                            $(
1443                                            Port::$tx_array_variant(idx) => {
1444                                                let receiver = self.[<$tx_array_field _receivers>]
1445                                                    .get(*idx)
1446                                                    .and_then(|receiver| receiver.as_ref())
1447                                                    .unwrap_or_else(|| panic!("{location}: {} receiver index {idx} out of range or already taken", stringify!($tx_array_field)));
1448                                                receivers.push((stringify!($tx_array_field), receiver as &dyn $crate::test_helpers::NoTrafficPort));
1449                                            }
1450                                            )*
1451                                            _ => {
1452                                                panic!("{location}: {port:?}: expect no traffic requires tx ports");
1453                                            }
1454                                        }
1455                                    }
1456
1457                                    $crate::test_helpers::expect_no_traffic(
1458                                        &location,
1459                                        &clock,
1460                                        ticks,
1461                                        receivers,
1462                                    )
1463                                    .await?;
1464                                }
1465                                Step::<$item_ty, $expected_ty>::Delay { ports, ticks, .. } => {
1466                                    if !ports.is_empty() {
1467                                        panic!("{location}: delay does not take ports");
1468                                    }
1469                                    clock.wait_ticks(ticks)?.await;
1470                                }
1471                                Step::<$item_ty, $expected_ty>::__Expected(_) => {
1472                                    unreachable!("marker variant is not a harness step");
1473                                }
1474                            }
1475                        }
1476                        Ok(self)
1477                    })
1478                }
1479            }
1480
1481            $(#[$meta])*
1482            $($struct_head)* {
1483                pub engine: gwr_engine::engine::Engine,
1484                pub clock: gwr_engine::time::clock::Clock,
1485                pub $component_field: $component_ty,
1486                $(
1487                    [<$rx_field _driver>]: Option<gwr_engine::port::OutPort<$rx_ty>>,
1488                )*
1489                $(
1490                    [<$tx_field _receiver>]: Option<gwr_engine::port::InPort<$tx_ty>>,
1491                )*
1492                $(
1493                    [<$rx_array_field _drivers>]: Vec<gwr_engine::port::OutPort<$rx_array_ty>>,
1494                )*
1495                $(
1496                    [<$tx_array_field _receivers>]: Vec<gwr_engine::port::InPort<$tx_array_ty>>,
1497                )*
1498                _expected: std::marker::PhantomData<$expected_ty>,
1499            }
1500
1501            $($impl_head)* {
1502                pub fn new(
1503                    mut engine: gwr_engine::engine::Engine,
1504                    $component_field: $component_ty,
1505                    $($rx_array_count: usize,)*
1506                    $($tx_array_count: usize,)*
1507                ) -> Self {
1508                    let clock = engine.default_clock();
1509                    let top = engine.top();
1510
1511                    $(
1512                        let mut [<$rx_field _driver>] = gwr_engine::port::OutPort::new(
1513                            top,
1514                            concat!(stringify!($rx_field), "_driver"),
1515                        );
1516                        [<$rx_field _driver>]
1517                            .connect($component_field.$($rx_method)+())
1518                            .unwrap();
1519                    )*
1520
1521                    $(
1522                        let [<$tx_field _receiver>] = gwr_engine::port::InPort::new(
1523                            &engine,
1524                            &clock,
1525                            top,
1526                            concat!(stringify!($tx_field), "_receiver"),
1527                        );
1528                        $component_field
1529                            .$($tx_method)+([<$tx_field _receiver>].state())
1530                            .unwrap();
1531                    )*
1532
1533                    $(
1534                        let mut [<$rx_array_field _drivers>] = Vec::with_capacity($rx_array_count);
1535                        for idx in 0..$rx_array_count {
1536                            let mut driver = gwr_engine::port::OutPort::new(
1537                                top,
1538                                &format!("{}_{}_driver", stringify!($rx_array_field), idx),
1539                            );
1540                            driver.connect($component_field.$($rx_array_method)+(idx)).unwrap();
1541                            [<$rx_array_field _drivers>].push(driver);
1542                        }
1543                    )*
1544
1545                    $(
1546                        let mut [<$tx_array_field _receivers>] = Vec::with_capacity($tx_array_count);
1547                        for idx in 0..$tx_array_count {
1548                            let receiver = gwr_engine::port::InPort::new(
1549                                &engine,
1550                                &clock,
1551                                top,
1552                                &format!("{}_{}_receiver", stringify!($tx_array_field), idx),
1553                            );
1554                            $component_field
1555                                .$($tx_array_method)+(idx, receiver.state())
1556                                .unwrap();
1557                            [<$tx_array_field _receivers>].push(receiver);
1558                        }
1559                    )*
1560
1561                    Self {
1562                        engine,
1563                        clock,
1564                        $component_field,
1565                        $(
1566                            [<$rx_field _driver>]: Some([<$rx_field _driver>]),
1567                        )*
1568                        $(
1569                            [<$tx_field _receiver>]: Some([<$tx_field _receiver>]),
1570                        )*
1571                        $(
1572                            [<$rx_array_field _drivers>],
1573                        )*
1574                        $(
1575                            [<$tx_array_field _receivers>],
1576                        )*
1577                        _expected: std::marker::PhantomData,
1578                    }
1579                }
1580
1581                $(
1582                    pub fn [<take_ $rx_field _driver>](
1583                        &mut self,
1584                    ) -> gwr_engine::port::OutPort<$rx_ty> {
1585                        self.[<$rx_field _driver>]
1586                            .take()
1587                            .expect(concat!(stringify!($rx_field), " driver already taken"))
1588                    }
1589
1590                )*
1591
1592                $(
1593                    pub fn [<take_ $tx_field _receiver>](
1594                        &mut self,
1595                    ) -> gwr_engine::port::InPort<$tx_ty> {
1596                        self.[<$tx_field _receiver>]
1597                            .take()
1598                            .expect(concat!(stringify!($tx_field), " receiver already taken"))
1599                    }
1600
1601                    pub async fn [<expect_no_ $tx_field _traffic>](
1602                        &mut self,
1603                        ticks: u64,
1604                    ) -> gwr_engine::types::SimResult {
1605                        $crate::test_helpers::expect_no_traffic(
1606                            stringify!($tx_field),
1607                            &self.clock,
1608                            ticks,
1609                            vec![
1610                                (
1611                                    stringify!($tx_field),
1612                                    self.[<$tx_field _receiver>]
1613                                        .as_ref()
1614                                        .expect(concat!(stringify!($tx_field), " receiver already taken")),
1615                                ),
1616                            ],
1617                        )
1618                        .await
1619                    }
1620                )*
1621
1622                $(
1623                    pub fn [<take_ $rx_array_field _drivers>](
1624                        &mut self,
1625                    ) -> Vec<gwr_engine::port::OutPort<$rx_array_ty>> {
1626                        std::mem::take(&mut self.[<$rx_array_field _drivers>])
1627                    }
1628
1629                )*
1630
1631                $(
1632                    pub fn [<take_ $tx_array_field _receivers>](
1633                        &mut self,
1634                    ) -> Vec<gwr_engine::port::InPort<$tx_array_ty>> {
1635                        std::mem::take(&mut self.[<$tx_array_field _receivers>])
1636                    }
1637
1638                )*
1639
1640                #[allow(unreachable_code)]
1641                pub fn run_steps<Steps>(
1642                    &mut self,
1643                    steps: Steps,
1644                )
1645                where
1646                    Steps: IntoIterator<Item = Step<$item_ty, $expected_ty>>,
1647                    Steps::IntoIter: 'static,
1648                    $($rx_ty: Clone + 'static,)*
1649                    $($tx_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_ty> + 'static,)*
1650                    $($rx_array_ty: Clone + 'static,)*
1651                    $($tx_array_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_array_ty> + 'static,)*
1652                    $item_ty: 'static,
1653                    $expected_ty: 'static,
1654                {
1655                    self.run_step_generator(steps.into_iter());
1656                }
1657
1658                #[allow(unreachable_code)]
1659                pub fn run_step_generator<I>(
1660                    &mut self,
1661                    mut steps: I,
1662                )
1663                where
1664                    I: Iterator<Item = Step<$item_ty, $expected_ty>> + 'static,
1665                    $($rx_ty: Clone + 'static,)*
1666                    $($tx_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_ty> + 'static,)*
1667                    $($rx_array_ty: Clone + 'static,)*
1668                    $($tx_array_expected_ty: Clone + $crate::test_helpers::ValueCheck<$tx_array_ty> + 'static,)*
1669                    $item_ty: 'static,
1670                    $expected_ty: 'static,
1671                {
1672                    let clock = self.clock.clone();
1673                    let spawner = self.engine.spawner();
1674                    let runner_ports = [<$harness Ports>]::<$item_ty> {
1675                        $(
1676                            [<$rx_field _driver>]: self.[<$rx_field _driver>].take(),
1677                        )*
1678                        $(
1679                            [<$tx_field _receiver>]: self.[<$tx_field _receiver>].take(),
1680                        )*
1681                        $(
1682                            [<$rx_array_field _drivers>]: self
1683                                .[<take_ $rx_array_field _drivers>]()
1684                                .into_iter()
1685                                .map(Some)
1686                                .collect(),
1687                        )*
1688                        $(
1689                            [<$tx_array_field _receivers>]: self
1690                                .[<take_ $tx_array_field _receivers>]()
1691                                .into_iter()
1692                                .map(Some)
1693                                .collect(),
1694                        )*
1695                        _item: std::marker::PhantomData,
1696                    };
1697
1698                    self.engine.spawn(async move {
1699                        let mut runner_ports = runner_ports;
1700                        for step in steps {
1701                            runner_ports = runner_ports
1702                                .run_steps(vec![step], clock.clone(), spawner.clone())
1703                                .await?;
1704                        }
1705                        gwr_engine::sim_error!("test harness completed")
1706                    });
1707
1708                    match self.engine.run() {
1709                        Ok(()) => panic!("test harness did not complete"),
1710                        Err(error) => assert_eq!(
1711                            error.0,
1712                            "test harness completed",
1713                            "unexpected simulation error"
1714                        ),
1715                    }
1716                }
1717
1718            }
1719
1720            #[allow(unused_macros)]
1721            macro_rules! step_location {
1722                () => {
1723                    $crate::test_helpers::StepLocation::new(file!(), line!(), column!())
1724                };
1725            }
1726
1727            $(
1728                #[allow(unused_macros)]
1729                macro_rules! [<send_ $rx_field>] {
1730
1731
1732                    ($value:expr,) => {
1733                        [<send_ $rx_field>]!($value)
1734                    };
1735                    ($value:expr) => {
1736                        Step::[<Send $rx_variant>] {
1737                            location: step_location!(),
1738                            port: Port::$rx_variant,
1739                            value: $value,
1740                        }
1741                    };
1742                }
1743            )*
1744
1745            $(
1746                #[allow(unused_macros)]
1747                macro_rules! [<expect_pending_send_ $rx_field>] {
1748
1749
1750                    ($value:expr, $ticks:expr,) => {
1751                        [<expect_pending_send_ $rx_field>]!($value, $ticks)
1752                    };
1753                    ($value:expr, $ticks:expr) => {
1754                        Step::[<ExpectPendingSend $rx_variant>] {
1755                            location: step_location!(),
1756                            port: Port::$rx_variant,
1757                            value: $value,
1758                            ticks: $ticks,
1759                        }
1760                    };
1761                }
1762            )*
1763
1764            $(
1765                #[allow(unused_macros)]
1766                macro_rules! [<expect_ $tx_field>] {
1767
1768
1769                    ($value:expr,) => {
1770                        [<expect_ $tx_field>]!($value)
1771                    };
1772                    ($value:expr) => {
1773                        Step::[<Expect $tx_variant>] {
1774                            location: step_location!(),
1775                            port: Port::$tx_variant,
1776                            value: $value,
1777                        }
1778                    };
1779                }
1780            )*
1781
1782            $(
1783                #[allow(unused_macros)]
1784                macro_rules! [<send_ $rx_array_field>] {
1785
1786
1787                    ($idx:expr, $value:expr,) => {
1788                        [<send_ $rx_array_field>]!($idx, $value)
1789                    };
1790                    ($idx:expr, $value:expr) => {
1791                        Step::[<Send $rx_array_variant>] {
1792                            location: step_location!(),
1793                            port: Port::$rx_array_variant($idx),
1794                            value: $value,
1795                        }
1796                    };
1797                }
1798            )*
1799
1800            $(
1801                #[allow(unused_macros)]
1802                macro_rules! [<expect_pending_send_ $rx_array_field>] {
1803
1804
1805                    ($idx:expr, $value:expr, $ticks:expr,) => {
1806                        [<expect_pending_send_ $rx_array_field>]!($idx, $value, $ticks)
1807                    };
1808                    ($idx:expr, $value:expr, $ticks:expr) => {
1809                        Step::[<ExpectPendingSend $rx_array_variant>] {
1810                            location: step_location!(),
1811                            port: Port::$rx_array_variant($idx),
1812                            value: $value,
1813                            ticks: $ticks,
1814                        }
1815                    };
1816                }
1817            )*
1818
1819            $(
1820                #[allow(unused_macros)]
1821                macro_rules! [<expect_ $tx_array_field>] {
1822
1823
1824                    ($idx:expr, $value:expr,) => {
1825                        [<expect_ $tx_array_field>]!($idx, $value)
1826                    };
1827                    ($idx:expr, $value:expr) => {
1828                        Step::[<Expect $tx_array_variant>] {
1829                            location: step_location!(),
1830                            port: Port::$tx_array_variant($idx),
1831                            value: $value,
1832                        }
1833                    };
1834                }
1835            )*
1836
1837            #[allow(unused_macros)]
1838            macro_rules! delay {
1839
1840
1841                ($ticks:expr,) => {
1842                    delay!($ticks)
1843                };
1844                ($ticks:expr) => {
1845                    Step::Delay {
1846                        location: step_location!(),
1847                        ports: Vec::new(),
1848                        ticks: $ticks,
1849                    }
1850                };
1851            }
1852
1853            #[allow(unused_macros)]
1854            macro_rules! expect_no_traffic {
1855
1856
1857                ($ports:expr, $ticks:expr,) => {
1858                    expect_no_traffic!($ports, $ticks)
1859                };
1860                ($ports:expr, $ticks:expr) => {
1861                    Step::ExpectNoTraffic {
1862                        location: step_location!(),
1863                        ports: $ports.to_vec(),
1864                        ticks: $ticks,
1865                    }
1866                };
1867            }
1868
1869            $crate::__define_harness_script!(($);
1870                [
1871                    $($rx_variant => [<$rx_field _driver>],)*
1872                    $($tx_variant => [<$tx_field _receiver>],)*
1873                ];
1874                [
1875                    $($rx_array_variant => [<$rx_array_field _drivers>],)*
1876                    $($tx_array_variant => [<$tx_array_field _receivers>],)*
1877                ]
1878            );
1879
1880            #[allow(unused_macros)]
1881            macro_rules! par {
1882                ($steps:expr,) => {
1883                    par!($steps)
1884                };
1885                ($steps:expr) => {
1886                    Step::Par {
1887                        location: step_location!(),
1888                        steps: $steps.into_iter().collect(),
1889                    }
1890                };
1891            }
1892        }
1893    };
1894}