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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use proc_macro2::TokenStream as TokenStream2;
use std::path::PathBuf;

use cxx_gen::GeneratedCode;
use indoc::indoc;
use quote::ToTokens;
use syn::parse::{Parse, ParseStream, Result as ParseResult};
use syn::{ItemMod, Macro};

use log::{debug, info, warn};
use osstrtools::OsStrTools;

mod bridge_converter;

#[derive(Debug)]
pub enum Error {
    Io(std::io::Error),
    Bindgen(()),
    CxxGen(cxx_gen::Error),
    Parsing(syn::Error),
    NoAutoCxxInc,
    CouldNotCanoncalizeIncludeDir(PathBuf),
    Conversion(bridge_converter::ConvertError),
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

pub enum CppInclusion {
    Define(String),
    Header(String),
}

/// Core of the autocxx engine.
/// TODO - consider whether this 'engine' crate should actually be a
/// directory of source symlinked from all the other sub-crates, so that
/// we avoid exposing an external interface from this code.
pub struct IncludeCpp {
    inclusions: Vec<CppInclusion>,
    allowlist: Vec<String>,
    preconfigured_inc_dirs: Option<std::ffi::OsString>,
    parse_only: bool,
}

impl Parse for IncludeCpp {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        Self::new_from_parse_stream(input)
    }
}

/// Prelude of C++ for squirting into bindgen. This configures
/// bindgen to output simpler types to replace some STL types
/// that bindgen just can't cope with. Although we then replace
/// those types with cxx types (e.g. UniquePtr), this intermediate
/// step is still necessary because bindgen can't otherwise
/// give us the templated types (e.g. when faced with the STL
/// unique_ptr, bindgen would normally give us std_unique_ptr
/// as opposed to std_unique_ptr<T>.)
static PRELUDE: &str = indoc! {"
    /**
    * <div rustbindgen=\"true\" replaces=\"std::unique_ptr\">
    */
    template<typename T> class UniquePtr {
        T* ptr;
    };

    /**
    * <div rustbindgen=\"true\" replaces=\"std::string\">
    */
    class CxxString {
        char* str_data;
    };
    \n"};

impl IncludeCpp {
    fn new_from_parse_stream(input: ParseStream) -> syn::Result<Self> {
        // Takes as inputs:
        // 1. List of headers to include
        // 2. List of #defines to include
        // 3. Allowlist

        let mut inclusions = Vec::new();
        let mut allowlist = Vec::new();
        let mut parse_only = false;

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            if ident == "Header" {
                let args;
                syn::parenthesized!(args in input);
                let hdr: syn::LitStr = args.parse()?;
                inclusions.push(CppInclusion::Header(hdr.value()));
            } else if ident == "Allow" {
                let args;
                syn::parenthesized!(args in input);
                let allow: syn::LitStr = args.parse()?;
                allowlist.push(allow.value());
            } else if ident == "ParseOnly" {
                parse_only = true;
            } else {
                return Err(syn::Error::new(ident.span(), "expected Header or Allow"));
            }
            if input.is_empty() {
                break;
            }
            input.parse::<syn::Token![,]>()?;
        }

        Ok(IncludeCpp {
            inclusions,
            allowlist,
            preconfigured_inc_dirs: None,
            parse_only,
        })
    }

    pub fn new_from_syn(mac: Macro) -> Result<Self> {
        mac.parse_body::<IncludeCpp>().map_err(Error::Parsing)
    }

    pub fn set_include_dirs<P: AsRef<std::ffi::OsStr>>(&mut self, include_dirs: P) {
        self.preconfigured_inc_dirs = Some(include_dirs.as_ref().into());
    }

    fn build_header(&self) -> String {
        let mut s = PRELUDE.to_string();
        for incl in &self.inclusions {
            let text = match incl {
                CppInclusion::Define(symbol) => format!("#define {}\n", symbol),
                CppInclusion::Header(path) => format!("#include \"{}\"\n", path),
            };
            s.push_str(&text);
        }
        s
    }

    fn determine_incdirs(&self) -> Result<Vec<PathBuf>> {
        let inc_dirs = match &self.preconfigured_inc_dirs {
            Some(d) => d.clone(),
            None => std::env::var_os("AUTOCXX_INC").ok_or(Error::NoAutoCxxInc)?,
        };
        // TODO consider if we can or should look up the include path automatically
        // instead of requiring callers always to set AUTOCXX_INC.
        let multi_path_separator = if std::path::MAIN_SEPARATOR == '/' {
            b':'
        } else {
            b';'
        }; // there's probably a crate for this
        let splitter = [multi_path_separator];
        let inc_dirs = inc_dirs.split(&splitter[0..1]);
        let mut inc_dir_paths = Vec::new();
        for inc_dir in inc_dirs {
            let p: PathBuf = inc_dir.into();
            let p = p
                .canonicalize()
                .map_err(|_| Error::CouldNotCanoncalizeIncludeDir(p))?;
            inc_dir_paths.push(p);
        }
        Ok(inc_dir_paths)
    }

    fn make_bindgen_builder(&self) -> Result<bindgen::Builder> {
        let inc_dirs = self.determine_incdirs()?;

        let full_header = self.build_header();
        debug!("Full header: {}", full_header);
        debug!("Inc dir: {:?}", inc_dirs);

        // TODO - pass headers in &self.inclusions into
        // bindgen such that it can include them in the generated
        // extern "C" section as include!
        // TODO work with OsStrs here to avoid the .display()
        // TODO get rid of this huge blocklist. It exists because
        // even if we replace a given STL type (per the PRELUDE, above)
        // bindgen still recurses into all the other definitions it needs.
        // It's probably desirable to fix this in bindgen, though I expect
        // the current behavior is there for a reason. Meanwhile, make
        // this list less hard-coded and nasty as best we can - TODO.
        let mut builder = bindgen::builder()
            .clang_args(&["-x", "c++", "-std=c++14"])
            .blacklist_item(".*default.*")
            .blacklist_item(".*unique_ptr.*")
            .blacklist_item(".*string.*")
            .blacklist_item(".*std_.*")
            .blacklist_item("std_.*")
            .blacklist_item("std.*")
            .blacklist_item(".*compressed_pair.*")
            .blacklist_item(".*allocator.*")
            .blacklist_item(".*wrap_iter.*")
            .blacklist_item(".*reverse_iterator.*")
            .blacklist_item(".*propagate_on_container.*")
            .blacklist_item(".*char_traits.*")
            .blacklist_item(".*size_t.*")
            .blacklist_item(".*mbstate_t.*")
            .derive_copy(false)
            .derive_debug(false)
            .default_enum_style(bindgen::EnumVariation::Rust {
                non_exhaustive: false,
            })
            .layout_tests(false); // TODO revisit later

        for inc_dir in inc_dirs {
            builder = builder.clang_arg(format!("-I{}", inc_dir.display()));
        }
        builder = builder.header_contents("example.hpp", &full_header);
        // 3. Passes allowlist and other options to the bindgen::Builder equivalent
        //    to --output-style=cxx --allowlist=<as passed in>
        for a in &self.allowlist {
            // TODO - allowlist type/functions/separately
            builder = builder.whitelist_type(a);
            builder = builder.whitelist_function(a);
        }
        Ok(builder)
    }

    pub fn generate_rs(self) -> Result<TokenStream2> {
        self.do_generation(true)
    }

    fn do_generation(self, old_rust: bool) -> Result<TokenStream2> {
        // If we are in parse only mode, do nothing. This is used for
        // doc tests to ensure the parsing is valid, but we can't expect
        // valid C++ header files or linkers to allow a complete build.
        if self.parse_only {
            return Ok(TokenStream2::new());
        }
        // 4. (also respects environment variables to pick up more headers,
        //     include paths and #defines)
        // Then:
        // 1. Builds an overall C++ header with all those #defines and #includes
        // 2. Passes it to bindgen::Builder::header
        let bindings = self
            .make_bindgen_builder()?
            .generate()
            .map_err(Error::Bindgen)?;
        let bindings = bindings.to_string();
        // Manually add the mod ffi {} so that we can ask syn to parse
        // into a single construct.
        let bindings = format!("#[cxx::bridge] mod ffi {{ {} }}", bindings);
        info!("Bindings: {}", bindings);
        let bindings = syn::parse_str::<ItemMod>(&bindings).map_err(Error::Parsing)?;

        let mut include_list = Vec::new();
        for incl in &self.inclusions {
            match incl {
                CppInclusion::Header(ref hdr) => {
                    include_list.push(hdr.clone());
                }
                CppInclusion::Define(_) => warn!("Currently no way to define! within cxx"),
            }
        }

        let mut converter = bridge_converter::BridgeConverter::new(include_list, old_rust);
        let new_bindings = converter.convert(bindings).map_err(Error::Conversion)?;
        let new_bindings = new_bindings.to_token_stream();
        info!("New bindings: {}", new_bindings.to_string());
        Ok(new_bindings)
    }

    pub fn generate_h_and_cxx(self) -> Result<GeneratedCode> {
        let rs = self.do_generation(false)?;
        let opt = cxx_gen::Opt::default();
        let results = cxx_gen::generate_header_and_cc(rs, &opt).map_err(Error::CxxGen);
        if let Ok(ref gen) = results {
            info!(
                "CXX: {}",
                String::from_utf8(gen.implementation.clone()).unwrap()
            );
            info!("header: {}", String::from_utf8(gen.header.clone()).unwrap());
        }
        results
    }

    pub fn include_dirs(&self) -> Result<Vec<PathBuf>> {
        self.determine_incdirs()
    }
}

/// This outermost crate currently just contains integration tests
/// for all the other crates. That's a bit of an odd arrangement, and
/// maybe needs revisiting.
#[cfg(test)]
mod tests {

    use indoc::indoc;
    use log::info;
    use proc_macro2::TokenStream;
    use quote::quote;
    use std::fs::File;
    use std::io::Write;
    use std::path::{Path, PathBuf};
    use std::sync::Mutex;
    use tempfile::{tempdir, TempDir};
    use test_env_log::test;

    lazy_static::lazy_static! {
        static ref BUILDER: Mutex<LinkableTryBuilder> = Mutex::new(LinkableTryBuilder::new());
    }

    /// TryBuild which maintains a directory of libraries to link.
    /// This is desirable because otherwise, if we alter the RUSTFLAGS
    /// then trybuild rebuilds *everything* including all the dev-dependencies.
    /// This object exists purely so that we use the same RUSTFLAGS for every
    /// test case.
    struct LinkableTryBuilder {
        /// Directory in which we'll keep any linkable libraries
        temp_dir: TempDir,
        test_cases: trybuild::TestCases,
    }

    impl LinkableTryBuilder {
        fn new() -> Self {
            LinkableTryBuilder {
                temp_dir: tempdir().unwrap(),
                test_cases: trybuild::TestCases::new(),
            }
        }

        fn copy_libraries_into_temp_dir<P1: AsRef<Path>>(
            &self,
            library_path: &P1,
            library_name: &str,
        ) {
            for item in std::fs::read_dir(library_path).unwrap() {
                let item = item.unwrap();
                if item
                    .file_name()
                    .into_string()
                    .unwrap()
                    .contains(library_name)
                {
                    let dest_lib = self.temp_dir.path().join(item.file_name());
                    std::fs::copy(item.path(), dest_lib).unwrap();
                }
            }
        }

        fn build<P1: AsRef<Path>, P2: AsRef<Path>>(
            &self,
            library_path: &P1,
            library_name: &str,
            rs_path: &P2,
        ) {
            // Copy all items from the source dir into our temporary dir if their name matches
            // the pattern given in `library_name`.
            self.copy_libraries_into_temp_dir(library_path, library_name);
            std::env::set_var(
                "RUSTFLAGS",
                format!("-L {}", self.temp_dir.path().to_str().unwrap()),
            );
            self.test_cases.pass(rs_path)
        }
    }

    fn write_to_file(tdir: &TempDir, filename: &str, content: &str) -> PathBuf {
        let path = tdir.path().join(filename);
        let mut f = File::create(&path).unwrap();
        info!("Writing to {:?}: {}", path, content);
        f.write_all(content.as_bytes()).unwrap();
        path
    }

    fn run_test(cxx_code: &str, header_code: &str, rust_code: TokenStream, allowed_funcs: &[&str]) {
        // Step 1: Write the C++ header snippet to a temp file
        let tdir = tempdir().unwrap();
        write_to_file(&tdir, "input.h", header_code);
        // Step 2: Expand the snippet of Rust code into an entire
        //         program including include_cxx!
        // TODO - we're not quoting #s below (in the "" sense), and it's not entirely
        // clear how we're getting away with it, but quoting it doesn't work.
        let allowed_funcs = allowed_funcs.iter().map(|s| {
            quote! {
                Allow(#s)
            }
        });
        let expanded_rust = quote! {
            use autocxx_macro::include_cxx;

            include_cxx!(
                Header("input.h"),
                #(#allowed_funcs),*
            );

            fn main() {
                #rust_code
            }

            #[link(name="autocxx-demo")]
            extern {}
        };
        // Step 3: Write the Rust code to a temp file
        let rs_code = format!("{}", expanded_rust);
        let rs_path = write_to_file(&tdir, "input.rs", &rs_code);

        // Step 4: Write the C++ code snippet to a .cc file, along with a #include
        //         of the header emitted in step 5.
        let cxx_code = format!("#include \"{}\"\n{}", "input.h", cxx_code);
        let cxx_path = write_to_file(&tdir, "input.cxx", &cxx_code);

        info!("Path is {:?}", tdir.path());
        let target_dir = tdir.path().join("target");
        std::fs::create_dir(&target_dir).unwrap();
        let target = rust_info::get().target_triple.unwrap();
        let mut b = autocxx_build::Builder::new(&rs_path, tdir.path().to_str().unwrap()).unwrap();
        b.builder()
            .file(cxx_path)
            .out_dir(&target_dir)
            .host(&target)
            .target(&target)
            .opt_level(1)
            .flag("-std=c++14")
            .include(tdir.path())
            .try_compile("autocxx-demo")
            .unwrap();
        // Step 8: use the trybuild crate to build the Rust file.
        BUILDER
            .lock()
            .unwrap()
            .build(&target_dir, "autocxx-demo", &rs_path);
    }

    #[test]
    fn test_return_void() {
        let cxx = indoc! {"
            void do_nothing() {
            }
        "};
        let hdr = indoc! {"
            void do_nothing();
        "};
        let rs = quote! {
            ffi::do_nothing();
        };
        run_test(cxx, hdr, rs, &["do_nothing"]);
    }

    #[test]
    fn test_return_i32() {
        let cxx = indoc! {"
            uint32_t give_int() {
                return 4;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            uint32_t give_int();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_int(), 4);
        };
        run_test(cxx, hdr, rs, &["give_int"]);
    }

    #[test]
    fn test_take_i32() {
        let cxx = indoc! {"
            uint32_t take_int(uint32_t a) {
                return a + 3;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            uint32_t take_int(uint32_t a);
        "};
        let rs = quote! {
            assert_eq!(ffi::take_int(3), 6);
        };
        run_test(cxx, hdr, rs, &["take_int"]);
    }

    #[test]
    #[ignore] // because cxx doesn't support unique_ptrs to primitives.
    fn test_give_up_int() {
        let cxx = indoc! {"
            std::unique_ptr<uint32_t> give_up() {
                return std::make_unique<uint32_t>(12);
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            #include <memory>
            std::unique_ptr<uint32_t> give_up();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_up().as_ref().unwrap(), 12);
        };
        run_test(cxx, hdr, rs, &["give_up"]);
    }

    #[test]
    fn test_give_string_up() {
        let cxx = indoc! {"
            std::unique_ptr<std::string> give_str_up() {
                return std::make_unique<std::string>(\"Bob\");
            }
        "};
        let hdr = indoc! {"
            #include <memory>
            #include <string>
            std::unique_ptr<std::string> give_str_up();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_str_up().as_ref().unwrap().to_str().unwrap(), "Bob");
        };
        run_test(cxx, hdr, rs, &["give_str_up"]);
    }

    #[test]
    #[ignore] // because we don't yet support std::string by value
    fn test_give_string_plain() {
        let cxx = indoc! {"
            std::string give_str() {
                return std::string(\"Bob\");
            }
        "};
        let hdr = indoc! {"
            #include <string>
            std::string give_str();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_str_up().to_str().unwrap(), "Bob");
        };
        run_test(cxx, hdr, rs, &["give_str"]);
    }

    #[test]
    fn test_cycle_string_up() {
        let cxx = indoc! {"
            std::unique_ptr<std::string> give_str_up() {
                return std::make_unique<std::string>(\"Bob\");
            }
            uint32_t take_str_up(std::unique_ptr<std::string> a) {
                return a->length();
            }
        "};
        let hdr = indoc! {"
            #include <memory>
            #include <string>
            #include <cstdint>
            std::unique_ptr<std::string> give_str_up();
            uint32_t take_str_up(std::unique_ptr<std::string> a);
        "};
        let rs = quote! {
            let s = ffi::give_str();
            assert_eq!(ffi::take_str(s), 3);
        };
        run_test(cxx, hdr, rs, &["give_str_up", "take_str_up"]);
    }

    #[test]
    #[ignore] // because we don't yet support std::string by value
    fn test_cycle_string() {
        let cxx = indoc! {"
            std::string give_str() {
                return std::string(\"Bob\");
            }
            uint32_t take_str(std::string a) {
                return a.length();
            }
        "};
        let hdr = indoc! {"
            #include <string>
            #include <cstdint>
            std::string give_str();
            uint32_t take_str(std::string a);
        "};
        let rs = quote! {
            let s = ffi::give_str();
            assert_eq!(ffi::take_str(s), 3);
        };
        let allowed_funcs = &["give_str", "take_str"];
        run_test(cxx, hdr, rs, allowed_funcs);
    }

    #[test]
    fn test_cycle_string_by_ref() {
        let cxx = indoc! {"
            std::unique_ptr<std::string> give_str() {
                return std::make_unique<std::string>(\"Bob\");
            }
            uint32_t take_str(const std::string& a) {
                return a.length();
            }
        "};
        let hdr = indoc! {"
            #include <string>
            #include <cstdint>
            std::unique_ptr<std::string> give_str();
            uint32_t take_str(const std::string& a);
        "};
        let rs = quote! {
            let s = ffi::give_str();
            assert_eq!(ffi::take_str(s.as_ref()), 3);
        };
        let allowed_funcs = &["give_str", "take_str"];
        run_test(cxx, hdr, rs, allowed_funcs);
    }

    #[test]
    fn test_cycle_string_by_mut_ref() {
        let cxx = indoc! {"
            std::unique_ptr<std::string> give_str() {
                return std::make_unique<std::string>(\"Bob\");
            }
            uint32_t take_str(std::string& a) {
                return a.length();
            }
        "};
        let hdr = indoc! {"
            #include <string>
            #include <cstdint>
            std::unique_ptr<std::string> give_str();
            uint32_t take_str(std::string& a);
        "};
        let rs = quote! {
            let s = ffi::give_str();
            assert_eq!(ffi::take_str(s.as_ref()), 3);
        };
        let allowed_funcs = &["give_str", "take_str"];
        run_test(cxx, hdr, rs, allowed_funcs);
    }

    #[test]
    fn test_give_pod_by_value() {
        let cxx = indoc! {"
            Bob give_bob() {
                Bob a;
                a.a = 3;
                a.b = 4;
                return a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
                uint32_t a;
                uint32_t b;
            };
            Bob give_bob();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_bob().b, 4);
        };
        run_test(cxx, hdr, rs, &["give_bob", "Bob"]);
    }

    #[test]
    #[ignore] // works, but gives compile warnings
    fn test_give_pod_class_by_value() {
        let cxx = indoc! {"
            Bob give_bob() {
                Bob a;
                a.a = 3;
                a.b = 4;
                return a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            class Bob {
            public:
                uint32_t a;
                uint32_t b;
            };
            Bob give_bob();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_bob().b, 4);
        };
        run_test(cxx, hdr, rs, &["give_bob", "Bob"]);
    }

    #[test]
    fn test_give_pod_by_up() {
        let cxx = indoc! {"
            std::unique_ptr<Bob> give_bob() {
                auto a = std::make_unique<Bob>();
                a->a = 3;
                a->b = 4;
                return a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            #include <memory>
            struct Bob {
                uint32_t a;
                uint32_t b;
            };
            std::unique_ptr<Bob> give_bob();
        "};
        let rs = quote! {
            assert_eq!(ffi::give_bob().as_ref().unwrap().b, 4);
        };
        run_test(cxx, hdr, rs, &["give_bob", "Bob"]);
    }

    #[test]
    fn test_take_pod_by_value() {
        let cxx = indoc! {"
            uint32_t take_bob(Bob a) {
                return a.a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
                uint32_t a;
                uint32_t b;
            };
            uint32_t take_bob(Bob a);
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(ffi::take_bob(a), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob"]);
    }

    #[test]
    fn test_take_pod_by_ref() {
        let cxx = indoc! {"
            uint32_t take_bob(const Bob& a) {
                return a.a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
                uint32_t a;
                uint32_t b;
            };
            uint32_t take_bob(const Bob& a);
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(ffi::take_bob(&a), 12);
        };
        let allowed_funcs = &["take_bob", "Bob"];
        run_test(cxx, hdr, rs, allowed_funcs);
    }

    #[test]
    fn test_take_pod_by_mut_ref() {
        let cxx = indoc! {"
            uint32_t take_bob(Bob& a) {
                a.b = 14;
                return a.a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
                uint32_t a;
                uint32_t b;
            };
            uint32_t take_bob(const Bob& a);
        "};
        let rs = quote! {
            let mut a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(ffi::take_bob(&mut a), 12);
            assert_eq!(a.b, 14);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob"]);
    }

    #[test]
    fn test_take_nested_pod_by_value() {
        let cxx = indoc! {"
            uint32_t take_bob(Bob a) {
                return a.a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Phil {
                uint32_t d;
            };
            struct Bob {
                uint32_t a;
                uint32_t b;
                Phil c;
            };
            uint32_t take_bob(Bob a);
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13, c: ffi::Phil { d: 4 } };
            assert_eq!(ffi::take_bob(a), 12);
        };
        // Should be no need to allowlist Phil below
        let allowed_funcs = &["take_bob", "Bob"];
        run_test(cxx, hdr, rs, allowed_funcs);
    }

    #[test]
    #[ignore] // because we don't yet support strings in PODs.
    fn test_cycle_pod_with_str_by_value() {
        let cxx = indoc! {"
            uint32_t take_bob(Bob a) {
                return a.a;
            }
            std::string get_str() {
                return \"hello\";
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            #include <string>
            struct Bob {
                uint32_t a;
                std::string b;
            };
            uint32_t take_bob(Bob a);
            std::string get_str();
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: ffi::get_str() };
            assert_eq!(ffi::take_bob(a), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob", "get_str"]);
    }

    #[test]
    #[ignore] // because we don't yet support strings in PODs.
    fn test_cycle_pod_with_str_by_ref() {
        let cxx = indoc! {"
            uint32_t take_bob(const Bob& a) {
                return a.a;
            }
            std::string get_str() {
                return \"hello\";
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            #include <string>
            struct Bob {
                uint32_t a;
                std::string b;
            };
            uint32_t take_bob(const Bob& a);
            std::string get_str();
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: ffi::get_str() };
            assert_eq!(ffi::take_bob(&a), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob", "get_str"]);
    }

    #[test]
    #[ignore] // because we have yet to implement make_unique
    fn test_make_up() {
        let cxx = indoc! {"
            Bob::Bob() : a(3) {
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            class Bob {
            public:
                Bob();
                uint32_t a;
            };
        "};
        let rs = quote! {
            let a = ffi::Bob::make_unique();
            assert_eq!(a.as_ref().unwrap().a, 3);
        };
        run_test(cxx, hdr, rs, &["Bob"]);
    }

    #[test]
    #[ignore] // because we have yet to implement make_unique
    fn test_make_up_int() {
        let cxx = indoc! {"
            Bob::Bob(uint32_t a) : b(a) {
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            class Bob {
            public:
                Bob(uint32_t a);
                uint32_t b;
            };
        "};
        let rs = quote! {
            let a = ffi::Bob::make_unique(3);
            assert_eq!(a.as_ref().unwrap().b, 3);
        };
        run_test(cxx, hdr, rs, &["Bob"]);
    }

    #[test]
    #[ignore] // because enums are the wrong size
    fn test_enum() {
        let cxx = indoc! {"
            Bob give_bob() {
                return Bob::BOB_VALUE_2;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            enum Bob {
                BOB_VALUE_1,
                BOB_VALUE_2,
            };
            Bob give_bob();
        "};
        let rs = quote! {
            let a = ffi::Bob::BOB_VALUE_2;
            let b = ffi::give_bob();
            assert_eq!(a, b);
        };
        run_test(cxx, hdr, rs, &["Bob", "give_bob"]);
    }

    #[test]
    #[ignore] // because currently we do not !include the header unless there are functions
    fn test_enum_no_funcs() {
        let cxx = indoc! {"
        "};
        let hdr = indoc! {"
            enum Bob {
                BOB_VALUE_1,
                BOB_VALUE_2,
            };
        "};
        let rs = quote! {
            let a = ffi::Bob::BOB_VALUE_1;
            let b = ffi::Bob::BOB_VALUE_2;
            assert_ne!(a, b);
        };
        run_test(cxx, hdr, rs, &["Bob"]);
    }

    #[test]
    #[ignore] // works, but causes compile warnings
    fn test_take_pod_class_by_value() {
        let cxx = indoc! {"
            uint32_t take_bob(Bob a) {
                return a.a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            class Bob {
            public:
                uint32_t a;
                uint32_t b;
            };
            uint32_t take_bob(Bob a);
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(ffi::take_bob(a), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob"]);
    }

    #[test]
    fn test_pod_method() {
        let cxx = indoc! {"
            uint32_t Bob::get_bob() const {
                return a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
            public:
                uint32_t a;
                uint32_t b;
                uint32_t get_bob() const;
            };
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(a.get_bob(), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob"]);
    }

    #[test]
    fn test_pod_mut_method() {
        let cxx = indoc! {"
            uint32_t Bob::get_bob() {
                return a;
            }
        "};
        let hdr = indoc! {"
            #include <cstdint>
            struct Bob {
            public:
                uint32_t a;
                uint32_t b;
                uint32_t get_bob();
            };
        "};
        let rs = quote! {
            let a = ffi::Bob { a: 12, b: 13 };
            assert_eq!(a.get_bob(), 12);
        };
        run_test(cxx, hdr, rs, &["take_bob", "Bob"]);
    }
    // Yet to test:
    // 1. Make UniquePtr<CxxStrings> in Rust
    // 2. Enums
    // 3. Constants
    // 4. Call methods
    // 5. Templated stuff
    // 6. Preprocessor directives
    // 7. Out params
    // 8. Opaque type handling
    // 9. Multiple functions in one header
    // Stuff which requires much more thought:
    // 1. Shared pointers
    // Negative tests:
    // 1. Private methods
    // 2. Private fields
}