iai_callgrind/
macros.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//! Contains macros which together define a benchmark harness that can be used in place of the
//! standard benchmark harness. This allows the user to run Iai benchmarks with `cargo bench`.

/// [low level api](`crate::binary_benchmark_group`) only: Use to add a `#[binary_benchmark]` to a
/// [`crate::BinaryBenchmarkGroup`]
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_attribute, binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
///     iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///         .arg("foo")
///         .build()
/// }
///
/// binary_benchmark_group!(
///     name = my_group;
///     benchmarks = |group: &mut BinaryBenchmarkGroup| {
///         group.binary_benchmark(binary_benchmark_attribute!(bench_binary));
///     }
/// );
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! binary_benchmark_attribute {
    ($name:ident) => {{
        let mut binary_benchmark = $crate::BinaryBenchmark::new(stringify!($name));
        binary_benchmark.config = $name::__get_config();

        for internal_bench in $name::__BENCHES {
            let mut bench = if let Some(id) = internal_bench.id_display {
                $crate::Bench::new(id)
            } else {
                $crate::Bench::new(stringify!($name))
            };
            let mut bench = bench.command((internal_bench.func)());
            if let Some(setup) = internal_bench.setup {
                bench.setup(setup);
            }
            if let Some(teardown) = internal_bench.teardown {
                bench.teardown(teardown);
            }
            if let Some(config) = internal_bench.config {
                bench.config(config());
            }
            binary_benchmark.bench(bench);
        }
        binary_benchmark
    }};
}

/// The `iai_callgrind::main` macro expands to a `main` function which runs all the benchmarks.
///
/// Using Iai-callgrind requires disabling the benchmark harness. This can be done like so in the
/// `Cargo.toml` file:
///
/// ```toml
/// [[bench]]
/// name = "my_bench"
/// harness = false
/// ```
///
/// To be able to run any iai-callgrind benchmarks, you'll also need the `iai-callgrind-runner`
/// installed with the binary somewhere in your `$PATH` for example with
///
/// ```shell
/// cargo install iai-callgrind-runner
/// ```
///
/// `my_bench` has to be a rust file inside the 'benches' directory.
///
/// # Library Benchmarks
///
/// The [`crate::main`] macro has one form to run library benchmarks:
///
/// ```rust
/// # use iai_callgrind::{main, library_benchmark_group, library_benchmark};
/// # #[library_benchmark]
/// # fn bench_fibonacci() { }
/// # library_benchmark_group!(
/// #    name = some_group;
/// #    benchmarks = bench_fibonacci
/// # );
/// # fn main() {
/// main!(library_benchmark_groups = some_group);
/// # }
/// ```
///
/// which accepts the following top-level arguments in this order (separated by a semicolon):
///
/// * __`config`__ (optional): Optionally specify a [`crate::LibraryBenchmarkConfig`] valid for all
///   benchmark groups
/// * __`setup`__ (optional): A setup function or any valid expression which is run before all
///   benchmarks
/// * __`teardown`__ (optional): A setup function or any valid expression which is run after all
///   benchmarks
/// * __`library_benchmark_groups`__ (mandatory): The __name__ of one or more
///   [`library_benchmark_group!`](crate::library_benchmark_group) macros. Multiple __names__ are
///   expected to be a comma separated list
///
/// A library benchmark consists of
/// [`library_benchmark_groups`](crate::library_benchmark_group) and with
/// [`#[library_benchmark]`](crate::library_benchmark) annotated benchmark functions.
///
/// ```rust
/// use iai_callgrind::{main, library_benchmark_group, library_benchmark};
/// use std::hint::black_box;
///
/// fn fibonacci(n: u64) -> u64 {
///     match n {
///         0 => 1,
///         1 => 1,
///         n => fibonacci(n - 1) + fibonacci(n - 2),
///     }
/// }
///
/// #[library_benchmark]
/// #[bench::short(10)]
/// #[bench::long(30)]
/// fn bench_fibonacci(value: u64) -> u64 {
///     black_box(fibonacci(value))
/// }
///
/// library_benchmark_group!(
///     name = bench_fibonacci_group;
///     benchmarks = bench_fibonacci
/// );
///
/// # fn main() {
/// main!(library_benchmark_groups = bench_fibonacci_group);
/// # }
/// ```
///
/// If you need to pass arguments to valgrind's callgrind, you can specify callgrind arguments via
/// [`crate::LibraryBenchmarkConfig::callgrind_args`]:
///
/// ```rust
/// # use iai_callgrind::{main, library_benchmark_group, library_benchmark, LibraryBenchmarkConfig};
/// # #[library_benchmark]
/// # fn bench_fibonacci() { }
/// # library_benchmark_group!(
/// #    name = some_group;
/// #    benchmarks = bench_fibonacci
/// # );
/// # fn main() {
/// main!(
///     config = LibraryBenchmarkConfig::default()
///                 .callgrind_args(
///                     ["--arg-with-flags=yes", "arg-without-flags=is_ok_too"]
///                 );
///     library_benchmark_groups = some_group
/// );
/// # }
/// ```
///
/// See also [Callgrind Command-line
/// options](https://valgrind.org/docs/manual/cl-manual.html#cl-manual.options).
///
/// For an in-depth description of library benchmarks and more examples see the
/// [README#Library
/// Benchmarks](https://github.com/iai-callgrind/iai-callgrind#library-benchmarks) of this
/// crate.
///
/// # Binary Benchmarks
///
/// Setting up binary benchmarks is almost the same as setting up library benchmarks but using the
/// `#[binary_benchmark]` macro. For example, if you're crate's binary is called `my-foo`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{main, binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// #[bench::hello_world("hello world")]
/// #[bench::foo("foo")]
/// fn bench_binary(arg: &str) -> iai_callgrind::Command {
///     iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///         .arg(arg)
///         .build()
/// }
///
/// binary_benchmark_group!(
///     name = my_group;
///     benchmarks = bench_binary
/// );
///
/// # fn main() {
/// main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// See the documentation of [`crate::binary_benchmark_group`] and [`crate::Command`] for more
/// details.
#[macro_export]
macro_rules! main {
    ( $( options = $( $options:literal ),+ $(,)*; )?
      $( before = $before:ident $(, bench = $bench_before:literal )? ; )?
      $( after = $after:ident $(, bench = $bench_after:literal )? ; )?
      $( setup = $setup:ident $(, bench = $bench_setup:literal )? ; )?
      $( teardown = $teardown:ident $(, bench = $bench_teardown:literal )? ; )?
      $( sandbox = $sandbox:literal; )?
      $( fixtures = $fixtures:literal $(, follow_symlinks = $follow_symlinks:literal )? ; )?
      $( run = cmd = $cmd:expr
            $(, envs = [ $( $envs:literal ),* $(,)* ] )?,
            $( id = $id:literal, args = [ $( $args:literal ),* $(,)* ]  ),+ $(,)*
      );+ $(;)*
    ) => {
        compile_error!(
            "You are using a deprecated syntax of the main! macro to set up binary benchmarks. \
            See the README (https://github.com/iai-callgrind/iai-callgrind) and \
            docs (https://docs.rs/iai-callgrind/latest/iai_callgrind/) for further details."
        );
        pub fn main() {}
    };
    (
        $( config = $config:expr; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        binary_benchmark_groups =
    ) => {
        compile_error!("The binary_benchmark_groups argument needs at least one `name` of a `binary_benchmark_group!`");
    };
    (
        $( config = $config:expr; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        binary_benchmark_groups = $( $group:ident ),+ $(,)*
    ) => {
        fn __run() -> Result<(), $crate::error::Errors> {
            let mut this_args = std::env::args();
            let exe = option_env!("IAI_CALLGRIND_RUNNER")
                .unwrap_or_else(|| option_env!("CARGO_BIN_EXE_iai-callgrind-runner").unwrap_or("iai-callgrind-runner"));

            let library_version = "0.14.0";

            let mut cmd = std::process::Command::new(exe);

            cmd.arg(library_version);
            cmd.arg("--bin-bench");
            cmd.arg(env!("CARGO_MANIFEST_DIR"));
            cmd.arg(env!("CARGO_PKG_NAME"));
            cmd.arg(file!());
            cmd.arg(module_path!());
            cmd.arg(this_args.next().unwrap()); // The executable benchmark binary

            let mut config: Option<$crate::internal::InternalBinaryBenchmarkConfig> = None;
            $(
                config = Some($config.into());
            )?

            let mut internal_benchmark_groups = $crate::internal::InternalBinaryBenchmarkGroups {
                config: config.unwrap_or_default(),
                command_line_args: this_args.collect(),
                has_setup: __run_setup(false),
                has_teardown: __run_teardown(false),
                ..Default::default()
            };

            let mut errors = $crate::error::Errors::default();

            $(
                if $group::__IS_ATTRIBUTE {
                    let mut internal_group = $crate::internal::InternalBinaryBenchmarkGroup {
                        id: stringify!($group).to_owned(),
                        config: $group::__get_config(),
                        binary_benchmarks: vec![],
                        has_setup: $group::__run_setup(false),
                        has_teardown: $group::__run_teardown(false),
                        compare_by_id: $group::__compare_by_id()
                    };
                    for (function_name, get_config, macro_bin_benches) in $group::__BENCHES {
                        let mut internal_binary_benchmark =
                            $crate::internal::InternalBinaryBenchmark {
                                benches: vec![],
                                config: get_config()
                        };
                        for macro_bin_bench in macro_bin_benches.iter() {
                            let bench = $crate::internal::InternalBinaryBenchmarkBench {
                                id: macro_bin_bench.id_display.map(|i| i.to_string()),
                                args: macro_bin_bench.args_display.map(|i| i.to_string()),
                                function_name: function_name.to_string(),
                                command: (macro_bin_bench.func)().into(),
                                config: macro_bin_bench.config.map(|f| f()),
                                has_setup: macro_bin_bench.setup.is_some(),
                                has_teardown: macro_bin_bench.teardown.is_some()
                            };
                            internal_binary_benchmark.benches.push(bench);
                        }
                        internal_group.binary_benchmarks.push(internal_binary_benchmark);
                    }

                    internal_benchmark_groups.groups.push(internal_group);
                } else {
                    let mut group = $crate::BinaryBenchmarkGroup::default();
                    $group::$group(&mut group);

                    let module_path = module_path!();

                    let mut internal_group = $crate::internal::InternalBinaryBenchmarkGroup {
                        id: stringify!($group).to_owned(),
                        config: $group::__get_config(),
                        binary_benchmarks: vec![],
                        has_setup: $group::__run_setup(false),
                        has_teardown: $group::__run_teardown(false),
                        compare_by_id: $group::__compare_by_id()
                    };

                    let mut binary_benchmark_ids =
                        std::collections::HashSet::<$crate::BenchmarkId>::new();

                    if group.binary_benchmarks.is_empty() {
                        errors.add(
                            $crate::error::Error::GroupError(
                                module_path.to_owned(),
                                internal_group.id.clone(),
                                "This group needs at least one benchmark".to_owned()
                            )
                        );
                    }

                    for binary_benchmark in group.binary_benchmarks {
                        if let Err(message) = binary_benchmark.id.validate() {
                            errors.add(
                                $crate::error::Error::BinaryBenchmarkError(
                                    module_path.to_owned(),
                                    internal_group.id.clone(),
                                    binary_benchmark.id.to_string(),
                                    message
                                )
                            );
                            continue;
                        }
                        if !binary_benchmark_ids.insert(binary_benchmark.id.clone()) {
                            errors.add(
                                $crate::error::Error::BinaryBenchmarkError(
                                    module_path.to_owned(),
                                    internal_group.id.clone(),
                                    binary_benchmark.id.to_string(),
                                    "Duplicate binary benchmark id".to_owned()
                                )
                            );
                            continue;
                        }

                        let mut internal_binary_benchmark =
                            $crate::internal::InternalBinaryBenchmark {
                                benches: vec![],
                                config: binary_benchmark.config.map(Into::into)
                        };

                        let mut bench_ids =
                            std::collections::HashSet::<$crate::BenchmarkId>::new();

                        if binary_benchmark.benches.is_empty() {
                            errors.add(
                                $crate::error::Error::BinaryBenchmarkError(
                                    module_path.to_owned(),
                                    internal_group.id.clone(),
                                    binary_benchmark.id.to_string(),
                                    "This binary benchmark needs at least one bench".to_owned()
                                )
                            );
                        }

                        for bench in binary_benchmark.benches {
                            match bench.commands.as_slice() {
                                [] => {
                                    errors.add(
                                        $crate::error::Error::BenchError(
                                            module_path.to_owned(),
                                            internal_group.id.clone(),
                                            binary_benchmark.id.to_string(),
                                            bench.id.to_string(),
                                            "Missing command".to_owned()
                                        )
                                    );
                                },
                                [command] => {
                                    if let Err(message) = bench.id.validate() {
                                        errors.add(
                                            $crate::error::Error::BenchError(
                                                module_path.to_owned(),
                                                internal_group.id.clone(),
                                                binary_benchmark.id.to_string(),
                                                bench.id.to_string(),
                                                message
                                            )
                                        );
                                    }
                                    if !bench_ids.insert(bench.id.clone()) {
                                        errors.add(
                                            $crate::error::Error::BenchError(
                                                module_path.to_owned(),
                                                internal_group.id.clone(),
                                                binary_benchmark.id.to_string(),
                                                bench.id.to_string(),
                                                format!("Duplicate id: '{}'", bench.id)
                                            )
                                        );
                                    }
                                    let internal_bench =
                                        $crate::internal::InternalBinaryBenchmarkBench {
                                            id: Some(bench.id.into()),
                                            args: None,
                                            function_name: binary_benchmark.id.clone().into(),
                                            command: command.into(),
                                            config: bench.config.clone(),
                                            has_setup: bench.setup.is_some()
                                                    || binary_benchmark.setup.is_some(),
                                            has_teardown: bench.teardown.is_some()
                                                    || binary_benchmark.teardown.is_some(),
                                    };
                                    internal_binary_benchmark.benches.push(internal_bench);
                                },
                                commands => {
                                    for (index, command) in commands.iter().enumerate() {
                                        let bench_id: $crate::BenchmarkId = format!("{}_{}", bench.id, index).into();
                                        if let Err(message) = bench_id.validate() {
                                            errors.add(
                                                $crate::error::Error::BenchError(
                                                    module_path.to_owned(),
                                                    internal_group.id.clone(),
                                                    binary_benchmark.id.to_string(),
                                                    bench_id.to_string(),
                                                    message
                                                )
                                            );
                                            continue;
                                        }
                                        if !bench_ids.insert(bench_id.clone()) {
                                            errors.add(
                                                $crate::error::Error::BenchError(
                                                    module_path.to_owned(),
                                                    internal_group.id.clone(),
                                                    binary_benchmark.id.to_string(),
                                                    bench.id.to_string(),
                                                    format!("Duplicate id: '{}'", bench_id)
                                                )
                                            );
                                            continue;
                                        }
                                        let internal_bench =
                                            $crate::internal::InternalBinaryBenchmarkBench {
                                                id: Some(bench_id.into()),
                                                args: None,
                                                function_name: binary_benchmark.id.to_string(),
                                                command: command.into(),
                                                config: bench.config.clone(),
                                                has_setup: bench.setup.is_some()
                                                        || binary_benchmark.setup.is_some(),
                                                has_teardown: bench.teardown.is_some()
                                                        || binary_benchmark.teardown.is_some(),
                                        };
                                        internal_binary_benchmark.benches.push(internal_bench);
                                    }
                                }
                            }
                        }
                        internal_group.binary_benchmarks.push(internal_binary_benchmark);
                    }

                    internal_benchmark_groups.groups.push(internal_group);
                }
            )+

            if !errors.is_empty() {
                return Err(errors);
            }

            let encoded = $crate::bincode::serialize(&internal_benchmark_groups).expect("Encoded benchmark");
            let mut child = cmd
                .arg(encoded.len().to_string())
                .stdin(std::process::Stdio::piped())
                .spawn()
                .expect("Failed to run benchmarks. \
                    Is iai-callgrind-runner installed and iai-callgrind-runner in your $PATH?. \
                    You can also set the environment variable IAI_CALLGRIND_RUNNER to the \
                    absolute path of the iai-callgrind-runner executable.");

            let mut stdin = child.stdin.take().expect("Opening stdin to submit encoded benchmark");
            std::thread::spawn(move || {
                use std::io::Write;
                stdin.write_all(&encoded).expect("Writing encoded benchmark to stdin");
            });

            let status = child.wait().expect("Wait for child process to exit");
            if !status.success() {
                std::process::exit(1);
            }

            Ok(())
        }

        fn __run_setup(__run: bool) -> bool {
            let mut __has_setup = false;
            $(
                __has_setup = true;
                if __run {
                    $setup;
                }
            )?
            __has_setup
        }

        fn __run_teardown(__run: bool) -> bool {
            let mut __has_teardown = false;
            $(
                __has_teardown = true;
                if __run {
                    $teardown;
                }
            )?
            __has_teardown
        }

        fn main() {
            let mut args_iter = std::env::args().skip(1);
            if args_iter
                .next()
                .as_ref()
                .map_or(false, |value| value == "--iai-run")
            {
                let mut current = args_iter.next().expect("Expecting a function type");
                let next = args_iter.next();
                match (current.as_str(), next) {
                    ("setup", None) => {
                        __run_setup(true);
                    },
                    ("teardown", None) => {
                        __run_teardown(true);
                    },
                    $(
                        (group @ stringify!($group), Some(next)) => {
                            let current = next;
                            let next = args_iter.next();

                            match (current.as_str(), next) {
                                ("setup", None) => {
                                    $group::__run_setup(true);
                                },
                                ("teardown", None) => {
                                    $group::__run_teardown(true);
                                }
                                (key @ ("setup" | "teardown"), Some(next)) => {
                                    let group_index = next
                                            .parse::<usize>()
                                            .expect("The group index should be a number");
                                    let bench_index = args_iter
                                            .next()
                                            .expect("The bench index should be present")
                                            .parse::<usize>()
                                            .expect("The bench index should be a number");
                                    if key == "setup" {
                                        $group::__run_bench_setup(group_index, bench_index);
                                    } else {
                                        $group::__run_bench_teardown(group_index, bench_index);
                                    }
                                }
                                (name, _) => panic!("Invalid function '{}' in group '{}'", name, group)
                            }
                        }
                    )+
                    (name, _) => panic!("function '{}' not found in this scope", name)
                }
            } else {
                if let Err(errors) = __run() {
                    eprintln!("{errors}");
                    std::process::exit(1);
                }
            };
        }
    };
    (
        $( config = $config:expr; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        library_benchmark_groups =
    ) => {
        compile_error!("The library_benchmark_groups argument needs at least one `name` of a `library_benchmark_group!`");
    };
    (
        $( config = $config:expr ; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        library_benchmark_groups = $( $group:ident ),+ $(,)*
    ) => {
        #[inline(never)]
        fn __run() {
            let mut this_args = std::env::args();
            let exe = option_env!("IAI_CALLGRIND_RUNNER")
                .unwrap_or_else(|| option_env!("CARGO_BIN_EXE_iai-callgrind-runner").unwrap_or("iai-callgrind-runner"));

            let library_version = "0.14.0";

            let mut cmd = std::process::Command::new(exe);

            cmd.arg(library_version);
            cmd.arg("--lib-bench");
            cmd.arg(env!("CARGO_MANIFEST_DIR"));
            cmd.arg(env!("CARGO_PKG_NAME"));
            cmd.arg(file!());
            cmd.arg(module_path!());
            cmd.arg(this_args.next().unwrap()); // The executable benchmark binary

            let mut config: Option<$crate::internal::InternalLibraryBenchmarkConfig> = None;
            $(
                config = Some($config.into());
            )?

            let mut internal_benchmark_groups = $crate::internal::InternalLibraryBenchmarkGroups {
                config: config.unwrap_or_default(),
                command_line_args: this_args.collect(),
                has_setup: __run_setup(false),
                has_teardown: __run_teardown(false),
                ..Default::default()
            };

            $(
                let mut internal_group = $crate::internal::InternalLibraryBenchmarkGroup {
                    id: stringify!($group).to_owned(),
                    config: $group::__get_config(),
                    compare_by_id: $group::__compare_by_id(),
                    library_benchmarks: vec![],
                    has_setup: $group::__run_setup(false),
                    has_teardown: $group::__run_teardown(false),
                };
                for (function_name, get_config, macro_lib_benches) in $group::__BENCHES {
                    let mut benches = $crate::internal::InternalLibraryBenchmarkBenches {
                        benches: vec![],
                        config: get_config()
                    };
                    for macro_lib_bench in macro_lib_benches.iter() {
                        let bench = $crate::internal::InternalLibraryBenchmarkBench {
                            id: macro_lib_bench.id_display.map(|i| i.to_string()),
                            args: macro_lib_bench.args_display.map(|i| i.to_string()),
                            function_name: function_name.to_string(),
                            config: macro_lib_bench.config.map(|f| f()),
                        };
                        benches.benches.push(bench);
                    }
                    internal_group.library_benchmarks.push(benches);
                }

                internal_benchmark_groups.groups.push(internal_group);
            )+

            let encoded = $crate::bincode::serialize(&internal_benchmark_groups).expect("Encoded benchmark");
            let mut child = cmd
                .arg(encoded.len().to_string())
                .stdin(std::process::Stdio::piped())
                .spawn()
                .expect("Failed to run benchmarks. \
                    Is iai-callgrind-runner installed and iai-callgrind-runner in your $PATH?. \
                    You can also set the environment variable IAI_CALLGRIND_RUNNER to the \
                    absolute path of the iai-callgrind-runner executable.");

            let mut stdin = child.stdin.take().expect("Opening stdin to submit encoded benchmark");
            std::thread::spawn(move || {
                use std::io::Write;
                stdin.write_all(&encoded).expect("Writing encoded benchmark to stdin");
            });

            let status = child.wait().expect("Wait for child process to exit");
            if !status.success() {
                std::process::exit(1);
            }
        }

        #[inline(never)]
        fn __run_setup(__run: bool) -> bool {
            let mut __has_setup = false;
            $(
                __has_setup = true;
                if __run {
                    $setup;
                }
            )?
            __has_setup
        }

        #[inline(never)]
        fn __run_teardown(__run: bool) -> bool {
            let mut __has_teardown = false;
            $(
                __has_teardown = true;
                if __run {
                    $teardown;
                }
            )?
            __has_teardown
        }

        fn main() {
            let mut args_iter = std::hint::black_box(std::env::args()).skip(1);
            if args_iter
                .next()
                .as_ref()
                .map_or(false, |value| value == "--iai-run")
            {
                let current = std::hint::black_box(args_iter.next().expect("Expecting a function type"));
                let next = std::hint::black_box(args_iter.next());
                match current.as_str() {
                    "setup" if next.is_none() => {
                        __run_setup(true);
                    },
                    "teardown" if next.is_none() => {
                        __run_teardown(true);
                    },
                    $(
                        stringify!($group) => {
                            match std::hint::black_box(
                                next
                                    .expect("An argument `setup`, `teardown` or an index should be present")
                                    .as_str()
                            ) {
                                "setup" => {
                                    $group::__run_setup(true);
                                },
                                "teardown" => {
                                    $group::__run_teardown(true);
                                }
                                value => {
                                    let group_index = std::hint::black_box(
                                        value
                                            .parse::<usize>()
                                            .expect("Expecting a valid group index")
                                    );
                                    let bench_index = std::hint::black_box(
                                        args_iter
                                            .next()
                                            .expect("A bench index should be present")
                                            .parse::<usize>()
                                            .expect("Expecting a valid bench index")
                                    );
                                    $group::__run(group_index, bench_index);
                                }
                            }
                        }
                    )+
                    name => panic!("function '{}' not found in this scope", name)
                }
            } else {
                std::hint::black_box(__run());
            };
        }
    };
    (
        callgrind_args = $( $args:literal ),* $(,)*; $(;)*
        functions = $( $func_name:ident ),+ $(,)*
    ) => {
        compile_error!(
            "You are using a deprecated syntax of the main! macro to set up library benchmarks. \
            See the README (https://github.com/iai-callgrind/iai-callgrind) and \
            docs (https://docs.rs/iai-callgrind/latest/iai_callgrind/) for further details."
        );
        pub fn main() {}
    };
    ( $( $func_name:ident ),+ $(,)* ) => {
        compile_error!(
            "You are using a deprecated syntax of the main! macro to set up library benchmarks. \
            See the README (https://github.com/iai-callgrind/iai-callgrind) and \
            docs (https://docs.rs/iai-callgrind/latest/iai_callgrind/) for further details."
        );
        pub fn main() {}
    };
}

/// Macro used to define a group of binary benchmarks
///
/// There are two apis to set up binary benchmarks. The recommended way is to [use the
/// `#[binary_benchmark]` attribute](#using-the-high-level-api-with-the-binary-benchmark-attribute).
/// But, if you find yourself in the situation that the attribute isn't enough you can fall back to
/// the [low level api](#the-low-level-api) or even [intermix both
/// styles](#intermixing-both-apis).
///
/// # The macro's arguments in detail:
///
/// The following top-level arguments are accepted (in this order):
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark, binary_benchmark_group, BinaryBenchmarkGroup, BinaryBenchmarkConfig};
/// # fn run_setup() {}
/// # fn run_teardown() {}
/// # #[binary_benchmark]
/// # fn bench_binary() -> iai_callgrind::Command { iai_callgrind::Command::new("some") }
/// binary_benchmark_group!(
///     name = my_group;
///     config = BinaryBenchmarkConfig::default();
///     compare_by_id = false;
///     setup = run_setup();
///     teardown = run_teardown();
///     benchmarks = bench_binary
/// );
/// # fn main() {
/// # my_group::my_group(&mut BinaryBenchmarkGroup::default());
/// # }
/// ```
///
/// * __`name`__ (mandatory): A unique name used to identify the group for the `main!` macro
/// * __`config`__ (optional): A [`crate::BinaryBenchmarkConfig`]
/// * __`compare_by_id`__ (optional): The default is false. If true, all commands from the functions
///   specified in the `benchmarks` argument, are compared with each other as long as the ids (the
///   part after the `::` in `#[bench::id(...)]`) match.
/// * __`setup`__ (optional): A function which is executed before all benchmarks in this group
/// * __`teardown`__ (optional): A function which is executed after all benchmarks in this group
/// * __`benchmarks`__ (mandatory): A `,`-separated list of `#[binary_benchmark]` annotated function
///   names you want to put into this group. Or, if you want to use the low level api
///
///   `|IDENTIFIER: &mut BinaryBenchmarkGroup| EXPRESSION`
///
///   or the shorter `|IDENTIFIER| EXPRESSION`
///
///   where `IDENTIFIER` is the identifier of your choice for the `BinaryBenchmarkGroup` (we use
///   `group` throughout our examples) and `EXPRESSION` is the code where you make use of the
///   `BinaryBenchmarkGroup` to set up the binary benchmarks
///
/// # Using the high-level api with the `#[binary benchmark]` attribute
///
/// A small introductory example which demonstrates the basic setup (assuming a crate's binary is
/// named `my-foo`):
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, BinaryBenchmarkGroup, binary_benchmark};
///
/// #[binary_benchmark]
/// #[bench::hello_world("hello world")]
/// #[bench::foo("foo")]
/// #[benches::multiple("bar", "baz")]
/// fn bench_binary(arg: &str) -> iai_callgrind::Command {
///      iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///          .arg(arg)
///          .build()
/// }
///
/// binary_benchmark_group!(
///     name = my_group;
///     benchmarks = bench_binary
/// );
///
/// # fn main() {
/// iai_callgrind::main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// To be benchmarked a `binary_benchmark_group` has to be added to the `main!` macro by adding its
/// name to the `binary_benchmark_groups` argument of the `main!` macro. See there for further
/// details about the [`crate::main`] macro. See the documentation of [`crate::binary_benchmark`]
/// for more details about the attribute itself and the inner attributes `#[bench]` and
/// `#[benches]`.
///
/// # The low-level api
///
/// Using the low-level api has advantages but when it comes to stability in terms of usability, the
/// low level api might be considered less stable. What does this mean? If we have to make changes
/// to the inner workings of iai-callgrind which not necessarily change the high-level api it is
/// more likely that the low-level api has to be adjusted. This implies you might have to adjust
/// your benchmarks more often with a version update of `iai-callgrind`. Hence, it is recommended to
/// use the high-level api as much as possible and only use the low-level api under special
/// circumstances. You can also [intermix both styles](#intermixing-both-apis)!
///
/// The low-level api mirrors the high-level constructs as close as possible. The
/// [`crate::BinaryBenchmarkGroup`] is a special case, since we use the information from the
/// `binary_benchmark_group!` macro [arguments](#the-macros-arguments-in-detail) (__`name`__,
/// __`config`__, ...) to create the `BinaryBenchmarkGroup` and pass it to the `benchmarks`
/// argument.
///
/// That being said, here's the basic usage:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, BinaryBenchmark, Bench};
///
/// binary_benchmark_group!(
///     // All the other options from the `binary_benchmark_group` are used as usual
///     name = my_group;
///
///     // Note there's also the shorter form `benchmarks = |group|` but in the examples we want
///     // to be more explicit
///     benchmarks = |group: &mut BinaryBenchmarkGroup| {
///
///         // We have chosen `group` to be our identifier but it can be anything
///         group.binary_benchmark(
///
///             // This is the equivalent of the `#[binary_benchmark]` attribute. The `id`
///             // mirrors the function name of the `#[binary_benchmark]` annotated function.
///             BinaryBenchmark::new("some_id")
///                 .bench(
///
///                     // The equivalent of the `#[bench]` attribute.
///                     Bench::new("my_bench_id")
///                         .command(
///
///                             // The `Command` stays the same
///                             iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///                                 .arg("foo").build()
///                         )
///                 )
///         )
///     }
/// );
/// # fn main() {}
/// ```
///
/// Depending on your IDE, it's nicer to work with the code after the `|group: &mut
/// BinaryBenchmarkGroup|` if it resides in a separate function rather than the macro itself as in
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, BinaryBenchmark, Bench, BinaryBenchmarkGroup};
///
/// fn setup_my_group(group: &mut BinaryBenchmarkGroup) {
///     // Enjoy all the features of your IDE ...
/// }
///
/// binary_benchmark_group!(
///     name = my_group;
///     benchmarks = |group: &mut BinaryBenchmarkGroup| setup_my_group(group)
/// );
/// # fn main() {}
/// ```
///
/// The list of all structs and macros used exclusively in the low-level api:
/// * [`crate::BinaryBenchmarkGroup`]
/// * [`crate::BinaryBenchmark`]: Mirrors the `#[binary_benchmark]` attribute
/// * [`crate::Bench`]: Mirrors the `#[bench]` attribute
/// * [`crate::binary_benchmark_attribute`]: Used to add a `#[binary_benchmark]` attributed function
///   in [`crate::BinaryBenchmarkGroup::binary_benchmark`]
/// * [`crate::BenchmarkId`]: The benchmark id is for example used in
///   [`crate::BinaryBenchmark::new`] and [`crate::Bench::new`]
///
/// Note there's no equivalent for the `#[benches]` attribute. The [`crate::Bench`] behaves exactly
/// as the `#[benches]` attribute if more than a single [`crate::Command`] is added.
///
/// # Intermixing both apis
///
/// For example, if you started with the `#[binary_benchmark]` attribute and noticed you are limited
/// by it to set up all the [`crate::Command`]s the way you want, you can intermix both styles:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{
///     binary_benchmark, binary_benchmark_group, BinaryBenchmark, Bench, BinaryBenchmarkGroup,
///     binary_benchmark_attribute
/// };
///
/// #[binary_benchmark]
/// #[bench::foo("foo")]
/// #[benches::multiple("bar", "baz")]
/// fn bench_binary(arg: &str) -> iai_callgrind::Command {
///     iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///         .arg(arg)
///         .build()
/// }
///
/// fn setup_my_group(group: &mut BinaryBenchmarkGroup) {
///     group
///         // Simply add what you already have with the `binary_benchmark_attribute!` macro.
///         // This macro returns a `BinaryBenchmark`, so you could even add more `Bench`es
///         // to it instead of creating a new one as we do below
///         .binary_benchmark(binary_benchmark_attribute!(bench_binary))
///         .binary_benchmark(
///             BinaryBenchmark::new("did_not_work_with_attribute")
///                 .bench(Bench::new("low_level")
///                     .command(
///                         iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
///                             .arg("foo")
///                             .build()
///                     )
///                 )
///         );
/// }
///
/// binary_benchmark_group!(
///     name = my_group;
///     benchmarks = |group: &mut BinaryBenchmarkGroup| setup_my_group(group)
/// );
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! binary_benchmark_group {
    (
        name = $name:ident; $(;)*
        $(before = $before:ident $(,bench = $bench_before:literal)? ; $(;)*)?
        $(after = $after:ident $(,bench = $bench_after:literal)? ; $(;)*)?
        $(setup = $setup:ident $(,bench = $bench_setup:literal)? ; $(;)*)?
        $(teardown = $teardown:ident $(,bench = $bench_teardown:literal)? ; $(;)*)?
        $( config = $config:expr ; $(;)* )?
        benchmark = |$cmd:literal, $group:ident: &mut BinaryBenchmarkGroup| $body:expr
    ) => {
        compile_error!(
            "You are using a deprecated syntax of the binary_benchmark_group! macro to set up binary \
            benchmarks. See the README (https://github.com/iai-callgrind/iai-callgrind), the \
            CHANGELOG on the same page and docs (https://docs.rs/iai-callgrind/latest/iai_callgrind) \
            for further details."
        );
    };
    (
        name = $name:ident; $(;)*
        $( before = $before:ident $(,bench = $bench_before:literal)? ; $(;)* )?
        $( after = $after:ident $(,bench = $bench_after:literal)? ; $(;)* )?
        $( setup = $setup:ident $(,bench = $bench_setup:literal)? ; $(;)* )?
        $( teardown = $teardown:ident $(,bench = $bench_teardown:literal )? ; $(;)* )?
        $( config = $config:expr ; $(;)* )?
        benchmark = |$group:ident: &mut BinaryBenchmarkGroup| $body:expr
    ) => {
        compile_error!(
            "You are using a deprecated syntax of the binary_benchmark_group! macro to set up binary \
            benchmarks. See the README (https://github.com/iai-callgrind/iai-callgrind), the \
            CHANGELOG on the same page and docs (https://docs.rs/iai-callgrind/latest/iai_callgrind) \
            for further details."
        );
    };
    (
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = $( $function:ident ),+ $(,)*
    ) => {
        compile_error!(
            "A binary_benchmark_group! needs a unique name. See the documentation of this macro for \
            further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = some_binary_benchmark);"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks =
    ) => {
        compile_error!(
            "A binary_benchmark_group! needs at least 1 benchmark function which is annotated with \
            #[binary_benchmark] or you can use the low level syntax. See the documentation of this \
            macro for further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = some_binary_benchmark);"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
    ) => {
        compile_error!(
            "A binary_benchmark_group! needs at least 1 benchmark function which is annotated with \
            #[binary_benchmark] or you can use the low level syntax. See the documentation of this \
            macro for further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = some_binary_benchmark);"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = $( $function:ident ),+ $(,)*
    ) => {
        pub mod $name {
            use super::*;

            pub const __IS_ATTRIBUTE: bool = true;

            pub const __BENCHES: &[&(
                &'static str,
                fn() -> Option<$crate::internal::InternalBinaryBenchmarkConfig>,
                &[$crate::internal::InternalMacroBinBench]
            )]= &[
                $(
                    &(
                        stringify!($function),
                        super::$function::__get_config,
                        super::$function::__BENCHES
                    )
                ),+
            ];

            pub fn __run_setup(__run: bool) -> bool {
                let mut __has_setup = false;
                $(
                    __has_setup = true;
                    if __run {
                        $setup;
                    }
                )?
                __has_setup
            }

            pub fn __run_teardown(__run: bool) -> bool {
                let mut __has_teardown = false;
                $(
                    __has_teardown = true;
                    if __run {
                        $teardown;
                    }
                )?
                __has_teardown
            }

            pub fn __compare_by_id() -> Option<bool> {
                let mut comp = None;
                $(
                    comp = Some($compare);
                )?
                comp
            }

            pub fn __get_config() -> Option<$crate::internal::InternalBinaryBenchmarkConfig> {
                let mut config = None;
                $(
                    config = Some($config.into());
                )?
                config
            }

            pub fn __run_bench_setup(group_index: usize, bench_index: usize) {
                if let Some(setup) = __BENCHES[group_index].2[bench_index].setup {
                    setup();
                };
            }

            pub fn __run_bench_teardown(group_index: usize, bench_index: usize) {
                if let Some(teardown) = __BENCHES[group_index].2[bench_index].teardown {
                    teardown();
                };
            }

            pub fn $name(_: &mut $crate::BinaryBenchmarkGroup) {}
        }
    };
    (
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident: &mut BinaryBenchmarkGroup| $body:expr
    ) => {
        compile_error!(
            "A binary_benchmark_group! needs a unique name. See the documentation of this macro for \
            further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = |group: &mut BinaryBenchmarkGroup| ... );"
        );
    };
    (
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident| $body:expr
    ) => {
        compile_error!(
            "A binary_benchmark_group! needs a unique name. See the documentation of this macro for \
            further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = |group| ... );"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident|
    ) => {
        compile_error!(
            "This low level form of the binary_benchmark_group! needs you to use the \
            `BinaryBenchmarkGroup` to setup benchmarks. See the documentation of this macro for \
            further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = |group| { \
                group.binary_benchmark(/* BinaryBenchmark::new */); });"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident: &mut BinaryBenchmarkGroup|
    ) => {
        compile_error!(
            "This low level form of the binary_benchmark_group! needs you to use the \
            `BinaryBenchmarkGroup` to setup benchmarks. See the documentation of this macro for \
            further details.\n\n\
            hint = binary_benchmark_group!(name = some_ident; benchmarks = |group: &mut \
                BinaryBenchmarkGroup| { group.binary_benchmark(/* BinaryBenchmark::new */); });"
        );
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident: &mut BinaryBenchmarkGroup| $body:expr
    ) => {
        pub mod $name {
            use super::*;

            pub const __IS_ATTRIBUTE: bool = false;

            pub const __BENCHES: &[&(
                &'static str,
                fn() -> Option<$crate::internal::InternalBinaryBenchmarkConfig>,
                &[$crate::internal::InternalMacroBinBench]
            )]= &[];

            pub fn __run_setup(__run: bool) -> bool {
                let mut __has_setup = false;
                $(
                    __has_setup = true;
                    if __run {
                        $setup;
                    }
                )?
                __has_setup
            }

            pub fn __run_teardown(__run: bool) -> bool {
                let mut __has_teardown = false;
                $(
                    __has_teardown = true;
                    if __run {
                        $teardown;
                    }
                )?
                __has_teardown
            }

            pub fn __get_config() -> Option<$crate::internal::InternalBinaryBenchmarkConfig> {
                let mut config = None;
                $(
                    config = Some($config.into());
                )?
                config
            }

            pub fn __compare_by_id() -> Option<bool> {
                let mut comp = None;
                $(
                    comp = Some($compare);
                )?
                comp
            }

            pub fn __run_bench_setup(group_index: usize, bench_index: usize) {
                let mut group = $crate::BinaryBenchmarkGroup::default();
                $name(&mut group);

                let bench = group
                    .binary_benchmarks
                    .iter()
                    .nth(group_index)
                    .expect("The group index for setup should be present");
                // In the runner each command is a `BinBench` and it is the index of the command
                // which we're getting back from the runner. So, we have to iterate over the
                // commands of each Bench to extract the correct setup function.
                //
                // commands                           => bench_index => The correct setup function
                // bench.benches[0].commands = [a, b] => 0, 1        => bench.benches[0].setup
                // bench.benches[1].commands = [c]    => 2           => bench.benches[1].setup
                // bench.benches[2].commands = [d, e] => 3, 4        => bench.benches[2].setup
                //
                // We also need to take care of that there can be a global setup function
                // `BinaryBenchmark::setup`, which can be overridden by a `Bench::setup`
                if let Some(setup) = bench
                        .benches
                        .iter()
                        .flat_map(|b| b.commands.iter().map(|c| (b.setup, c)))
                        .nth(bench_index)
                        .map(|(setup, _)| setup)
                        .expect("The bench index for setup should be present") {
                    setup();
                } else if let Some(setup) = bench.setup {
                    setup();
                } else {
                    // This branch should be unreachable so we do nothing
                }
            }

            pub fn __run_bench_teardown(group_index: usize, bench_index: usize) {
                let mut group = $crate::BinaryBenchmarkGroup::default();
                $name(&mut group);

                let bench = group
                    .binary_benchmarks
                    .iter()
                    .nth(group_index)
                    .expect("The group index for teardown should be present");
                if let Some(teardown) = bench
                        .benches
                        .iter()
                        .flat_map(|b| b.commands.iter().map(|c| (b.teardown, c)))
                        .nth(bench_index)
                        .map(|(teardown, _)| teardown)
                        .expect("The bench index for teardown should be present") {
                    teardown();
                } else if let Some(teardown) = bench.teardown {
                    teardown();
                } else {
                    // This branch should be unreachable so we do nothing
                }
            }

            #[inline(never)]
            pub fn $name($group: &mut $crate::BinaryBenchmarkGroup) {
                $body;
            }
        }
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr; $(;)* )?
        $( teardown = $teardown:expr; $(;)* )?
        benchmarks = |$group:ident| $body:expr
    ) => {
        binary_benchmark_group!(
            name = $name;
            $( config = $config; )?
            $( compare_by_id = $compare; )?
            $( setup = $setup; )?
            $( teardown = $teardown; )?
            benchmarks = |$group: &mut BinaryBenchmarkGroup| $body
        );
    };
}

/// Macro used to define a group of library benchmarks
///
/// A small introductory example which shows the basic setup. This macro only accepts benchmarks
/// annotated with `#[library_benchmark]` ([`crate::library_benchmark`]).
///
/// ```rust
/// use iai_callgrind::{library_benchmark_group, library_benchmark};
///
/// #[library_benchmark]
/// fn bench_something() -> u64 {
///     42
/// }
///
/// library_benchmark_group!(
///     name = my_group;
///     benchmarks = bench_something
/// );
///
/// # fn main() {
/// iai_callgrind::main!(library_benchmark_groups = my_group);
/// # }
/// ```
///
/// To be benchmarked a `library_benchmark_group` has to be added to the `main!` macro by adding its
/// name to the `library_benchmark_groups` argument of the `main!` macro. See there for further
/// details about the [`crate::main`] macro.
///
/// The following top-level arguments are accepted in this order:
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig};
/// # #[library_benchmark]
/// # fn some_func() {}
/// fn group_setup() {}
/// fn group_teardown() {}
/// library_benchmark_group!(
///     name = my_group;
///     config = LibraryBenchmarkConfig::default();
///     compare_by_id = false;
///     setup = group_setup();
///     teardown = group_teardown();
///     benchmarks = some_func
/// );
/// # fn main() {
/// # }
/// ```
///
/// * __`name`__ (mandatory): A unique name used to identify the group for the `main!` macro
/// * __`config`__ (optional): A [`crate::LibraryBenchmarkConfig`] which is applied to all
///   benchmarks within the same group.
/// * __`compare_by_id`__ (optional): The default is false. If true, all benches in the benchmark
///   functions specified with the `benchmarks` argument, across any benchmark groups, are compared
///   with each other as long as the ids (the part after the `::` in `#[bench::id(...)]`) match.
/// * __`setup`__ (optional): A setup function or any valid expression which is run before all
///   benchmarks of this group
/// * __`teardown`__ (optional): A teardown function or any valid expression which is run after all
///   benchmarks of this group
/// * __`benchmarks`__ (mandatory): A list of comma separated benchmark functions which must be
///   annotated with `#[library_benchmark]`
#[macro_export]
macro_rules! library_benchmark_group {
    (
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        benchmarks = $( $function:ident ),+
    ) => {
        compile_error!("A library_benchmark_group! needs a name\n\nlibrary_benchmark_group!(name = some_ident; benchmarks = ...);");
    };
    (
        name = $name:ident;
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        benchmarks =
    ) => {
        compile_error!(
            "A library_benchmark_group! needs at least 1 benchmark function \
            annotated with #[library_benchmark]\n\n\
            library_benchmark_group!(name = some_ident; benchmarks = some_library_benchmark);");
    };
    (
        name = $name:ident; $(;)*
        $( config = $config:expr ; $(;)* )?
        $( compare_by_id = $compare:literal ; $(;)* )?
        $( setup = $setup:expr ; $(;)* )?
        $( teardown = $teardown:expr ; $(;)* )?
        benchmarks = $( $function:ident ),+ $(,)*
    ) => {
        pub mod $name {
            use super::*;

            pub const __BENCHES: &[&(
                &'static str,
                fn() -> Option<$crate::internal::InternalLibraryBenchmarkConfig>,
                &[$crate::internal::InternalMacroLibBench]
            )]= &[
                $(
                    &(
                        stringify!($function),
                        super::$function::__get_config,
                        super::$function::__BENCHES
                    )
                ),+
            ];

            #[inline(never)]
            pub fn __get_config() -> Option<$crate::internal::InternalLibraryBenchmarkConfig> {
                let mut config: Option<$crate::internal::InternalLibraryBenchmarkConfig> = None;
                $(
                    config = Some($config.into());
                )?
                config
            }

            #[inline(never)]
            pub fn __compare_by_id() -> Option<bool> {
                let mut comp = None;
                $(
                    comp = Some($compare);
                )?
                comp
            }

            #[inline(never)]
            pub fn __run_setup(__run: bool) -> bool {
                let mut __has_setup = false;
                $(
                    __has_setup = true;
                    if __run {
                        $setup;
                    }
                )?
                __has_setup
            }

            #[inline(never)]
            pub fn __run_teardown(__run: bool) -> bool {
                let mut __has_teardown = false;
                $(
                    __has_teardown = true;
                    if __run {
                        $teardown;
                    }
                )?
                __has_teardown
            }

            #[inline(never)]
            pub fn __run(group_index: usize, bench_index: usize) {
                (__BENCHES[group_index].2[bench_index].func)();
            }
        }
    };
}