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
//! R object handling.
//!
//! See. <https://cran.r-project.org/doc/manuals/R-exts.html>
//!
//! Fundamental principals:
//!
//! * Any function that can break the protection mechanism is unsafe.
//! * Users should be able to do almost everything without using libR_sys.
//! * The interface should be friendly to R users without Rust experience.
//!

use libR_sys::*;
use std::os::raw;

use crate::*;

use crate::scalar::{Rfloat, Rint};
use std::collections::HashMap;
use std::iter::IntoIterator;
use std::ops::{Range, RangeInclusive};

// deprecated
mod from_robj;

mod into_robj;
mod operators;
mod rinternals;
mod try_from_robj;

#[cfg(test)]
mod tests;

pub use from_robj::*;
pub use into_robj::*;
pub use iter::*;
pub use operators::*;
pub use rinternals::*;

/// Wrapper for an R S-expression pointer (SEXP).
///
/// Create R objects from rust types and iterators:
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     // Different ways of making integer scalar 1.
///     let non_na : Option<i32> = Some(1);
///     let a : Robj = vec![1].into();
///     let b = r!(1);
///     let c = r!(vec![1]);
///     let d = r!(non_na);
///     let e = r!([1]);
///     assert_eq!(a, b);
///     assert_eq!(a, c);
///     assert_eq!(a, d);
///     assert_eq!(a, e);
///
///     // Different ways of making boolean scalar TRUE.
///     let a : Robj = true.into();
///     let b = r!(TRUE);
///     assert_eq!(a, b);
///
///     // Create a named list
///     let a = list!(a = 1, b = "x");
///     assert_eq!(a.len(), 2);
///
///     // Use an iterator (like 1:10)
///     let a = r!(1 ..= 10);
///     assert_eq!(a, r!([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
///
///     // Use an iterator (like (1:10)[(1:10) %% 3 == 0])
///     let a = (1 ..= 10).filter(|v| v % 3 == 0).collect_robj();
///     assert_eq!(a, r!([3, 6, 9]));
/// }
/// ```
///
/// Convert to/from Rust vectors.
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     let a : Robj = r!(vec![1., 2., 3., 4.]);
///     let b : Vec<f64> = a.as_real_vector().unwrap();
///     assert_eq!(a.len(), 4);
///     assert_eq!(b, vec![1., 2., 3., 4.]);
/// }
/// ```
///
/// Iterate over names and values.
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     let abc = list!(a = 1, b = "x", c = vec![1, 2]);
///     let names : Vec<_> = abc.names().unwrap().collect();
///     let names_and_values : Vec<_> = abc.as_list().unwrap().iter().collect();
///     assert_eq!(names, vec!["a", "b", "c"]);
///     assert_eq!(names_and_values, vec![("a", r!(1)), ("b", r!("x")), ("c", r!(vec![1, 2]))]);
/// }
/// ```
///
/// NOTE: as much as possible we wish to make this object safe (ie. no segfaults).
///
/// If you avoid using unsafe functions it is more likely that you will avoid
/// panics and segfaults. We will take great trouble to ensure that this
/// is true.
///
pub struct Robj {
    inner: SEXP,
}

impl Clone for Robj {
    fn clone(&self) -> Self {
        unsafe { Robj::from_sexp(self.get()) }
    }
}

impl Default for Robj {
    fn default() -> Self {
        Robj::from(())
    }
}

impl Robj {
    pub fn from_sexp(sexp: SEXP) -> Self {
        single_threaded(|| {
            unsafe { ownership::protect(sexp) };
            Robj { inner: sexp }
        })
    }

    /// Get a copy of the underlying SEXP.
    /// Note: this is unsafe.
    #[doc(hidden)]
    pub unsafe fn get(&self) -> SEXP {
        self.inner
    }

    #[doc(hidden)]
    /// Get the XXXSXP type of the object.
    pub fn sexptype(&self) -> u32 {
        unsafe { TYPEOF(self.get()) as u32 }
    }

    /// Get the type of an R object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     assert_eq!(r!(NULL).rtype(), RType::Null);
    ///     assert_eq!(sym!(xyz).rtype(), RType::Symbol);
    ///     assert_eq!(r!(Pairlist::from_pairs(vec![("a", r!(1))])).rtype(), RType::Pairlist);
    ///     assert_eq!(R!("function() {}")?.rtype(), RType::Function);
    ///     assert_eq!(Environment::new_with_parent(global_env()).rtype(), RType::Environment);
    ///     assert_eq!(lang!("+", 1, 2).rtype(), RType::Language);
    ///     assert_eq!(r!(Primitive::from_string("if")).rtype(), RType::Special);
    ///     assert_eq!(r!(Primitive::from_string("+")).rtype(), RType::Builtin);
    ///     assert_eq!(r!(Rstr::from_string("hello")).rtype(), RType::Rstr);
    ///     assert_eq!(r!(TRUE).rtype(), RType::Logical);
    ///     assert_eq!(r!(1).rtype(), RType::Integer);
    ///     assert_eq!(r!(1.0).rtype(), RType::Real);
    ///     assert_eq!(r!("1").rtype(), RType::String);
    ///     assert_eq!(r!(List::from_values(&[1, 2])).rtype(), RType::List);
    ///     assert_eq!(parse("x + y")?.rtype(), RType::Expression);
    ///     assert_eq!(r!(Raw::from_bytes(&[1_u8, 2, 3])).rtype(), RType::Raw);
    /// }
    /// ```
    pub fn rtype(&self) -> RType {
        match self.sexptype() {
            NILSXP => RType::Null,
            SYMSXP => RType::Symbol,
            LISTSXP => RType::Pairlist,
            CLOSXP => RType::Function,
            ENVSXP => RType::Environment,
            PROMSXP => RType::Promise,
            LANGSXP => RType::Language,
            SPECIALSXP => RType::Special,
            BUILTINSXP => RType::Builtin,
            CHARSXP => RType::Rstr,
            LGLSXP => RType::Logical,
            INTSXP => RType::Integer,
            REALSXP => RType::Real,
            CPLXSXP => RType::Complex,
            STRSXP => RType::String,
            DOTSXP => RType::Dot,
            ANYSXP => RType::Any,
            VECSXP => RType::List,
            EXPRSXP => RType::Expression,
            BCODESXP => RType::Bytecode,
            EXTPTRSXP => RType::ExternalPtr,
            WEAKREFSXP => RType::WeakRef,
            RAWSXP => RType::Raw,
            S4SXP => RType::S4,
            _ => RType::Unknown,
        }
    }

    pub fn as_any(&self) -> Rany {
        unsafe {
            match self.sexptype() {
                NILSXP => Rany::Null(std::mem::transmute(self)),
                SYMSXP => Rany::Symbol(std::mem::transmute(self)),
                LISTSXP => Rany::Pairlist(std::mem::transmute(self)),
                CLOSXP => Rany::Function(std::mem::transmute(self)),
                ENVSXP => Rany::Environment(std::mem::transmute(self)),
                PROMSXP => Rany::Promise(std::mem::transmute(self)),
                LANGSXP => Rany::Language(std::mem::transmute(self)),
                SPECIALSXP => Rany::Special(std::mem::transmute(self)),
                BUILTINSXP => Rany::Builtin(std::mem::transmute(self)),
                CHARSXP => Rany::Rstr(std::mem::transmute(self)),
                LGLSXP => Rany::Logical(std::mem::transmute(self)),
                INTSXP => Rany::Integer(std::mem::transmute(self)),
                REALSXP => Rany::Real(std::mem::transmute(self)),
                CPLXSXP => Rany::Complex(std::mem::transmute(self)),
                STRSXP => Rany::String(std::mem::transmute(self)),
                DOTSXP => Rany::Dot(std::mem::transmute(self)),
                ANYSXP => Rany::Any(std::mem::transmute(self)),
                VECSXP => Rany::List(std::mem::transmute(self)),
                EXPRSXP => Rany::Expression(std::mem::transmute(self)),
                BCODESXP => Rany::Bytecode(std::mem::transmute(self)),
                EXTPTRSXP => Rany::ExternalPtr(std::mem::transmute(self)),
                WEAKREFSXP => Rany::WeakRef(std::mem::transmute(self)),
                RAWSXP => Rany::Raw(std::mem::transmute(self)),
                S4SXP => Rany::S4(std::mem::transmute(self)),
                _ => Rany::Unknown(std::mem::transmute(self)),
            }
        }
    }

    /// Get the extended length of the object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    /// let a : Robj = r!(vec![1., 2., 3., 4.]);
    /// assert_eq!(a.len(), 4);
    /// }
    /// ```
    pub fn len(&self) -> usize {
        unsafe { Rf_xlength(self.get()) as usize }
    }

    /// Returns `true` if the `Robj` contains no elements.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    /// let a : Robj = r!(vec![0.; 0]); // length zero of numeric vector
    /// assert_eq!(a.is_empty(), true);
    /// }
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Is this object is an NA scalar?
    /// Works for character, integer and numeric types.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    /// assert_eq!(r!(NA_INTEGER).is_na(), true);
    /// assert_eq!(r!(NA_REAL).is_na(), true);
    /// assert_eq!(r!(NA_STRING).is_na(), true);
    /// }
    /// ```
    pub fn is_na(&self) -> bool {
        if self.len() != 1 {
            false
        } else {
            unsafe {
                let sexp = self.get();
                match self.sexptype() {
                    STRSXP => STRING_ELT(sexp, 0) == libR_sys::R_NaString,
                    INTSXP => *(INTEGER(sexp)) == libR_sys::R_NaInt,
                    LGLSXP => *(LOGICAL(sexp)) == libR_sys::R_NaInt,
                    REALSXP => R_IsNA(*(REAL(sexp))) != 0,
                    _ => false,
                }
            }
        }
    }

    /// Get a read-only reference to the content of an integer vector.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    /// let robj = r!([1, 2, 3]);
    /// assert_eq!(robj.as_integer_slice().unwrap(), [1, 2, 3]);
    /// }
    /// ```
    pub fn as_integer_slice<'a>(&self) -> Option<&'a [i32]> {
        self.as_typed_slice()
    }

    /// Convert an [`Robj`] into [`Integers`].
    pub fn as_integers(&self) -> Option<Integers> {
        self.clone().try_into().ok()
    }

    /// Get a Vec<i32> copied from the object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    /// let robj = r!([1, 2, 3]);
    /// assert_eq!(robj.as_integer_slice().unwrap(), vec![1, 2, 3]);
    /// }
    /// ```
    pub fn as_integer_vector(&self) -> Option<Vec<i32>> {
        self.as_integer_slice().map(|value| value.to_vec())
    }

    /// Get a read-only reference to the content of a logical vector
    /// using the tri-state [Bool]. Returns None if not a logical vector.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    ///     assert_eq!(robj.as_logical_slice().unwrap(), [TRUE, FALSE, NA_LOGICAL]);
    /// }
    /// ```
    pub fn as_logical_slice(&self) -> Option<&[Bool]> {
        self.as_typed_slice()
    }

    /// Get a Vec<Bool> copied from the object
    /// using the tri-state [Bool].
    /// Returns None if not a logical vector.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    ///     assert_eq!(robj.as_logical_vector().unwrap(), vec![TRUE, FALSE, NA_LOGICAL]);
    /// }
    /// ```
    pub fn as_logical_vector(&self) -> Option<Vec<Bool>> {
        self.as_logical_slice().map(|value| value.to_vec())
    }

    /// Get an iterator over logical elements of this slice.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([TRUE, FALSE, NA_LOGICAL]);
    ///     let (mut nt, mut nf, mut nna) = (0, 0, 0);
    ///     for val in robj.as_logical_iter().unwrap() {
    ///       match *val {
    ///         TRUE => nt += 1,
    ///         FALSE => nf += 1,
    ///         NA_LOGICAL => nna += 1,
    ///         _ => ()
    ///       }
    ///     }
    ///     assert_eq!((nt, nf, nna), (1, 1, 1));
    /// }
    /// ```
    pub fn as_logical_iter(&self) -> Option<impl Iterator<Item = &Bool>> {
        self.as_logical_slice().map(|slice| slice.iter())
    }

    /// Get a read-only reference to the content of a double vector.
    /// Note: the slice may contain NaN or NA values.
    /// We may introduce a "Real" type to handle this like the Bool type.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([Some(1.), None, Some(3.)]);
    ///     let mut tot = 0.;
    ///     for val in robj.as_real_slice().unwrap() {
    ///       if !val.is_na() {
    ///         tot += val;
    ///       }
    ///     }
    ///     assert_eq!(tot, 4.);
    /// }
    /// ```
    pub fn as_real_slice(&self) -> Option<&[f64]> {
        self.as_typed_slice()
    }

    /// Get an iterator over real elements of this slice.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([1., 2., 3.]);
    ///     let mut tot = 0.;
    ///     for val in robj.as_real_iter().unwrap() {
    ///       if !val.is_na() {
    ///         tot += val;
    ///       }
    ///     }
    ///     assert_eq!(tot, 6.);
    /// }
    /// ```
    pub fn as_real_iter(&self) -> Option<impl Iterator<Item = &f64>> {
        self.as_real_slice().map(|slice| slice.iter())
    }

    /// Get a Vec<f64> copied from the object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!([1., 2., 3.]);
    ///     assert_eq!(robj.as_real_vector().unwrap(), vec![1., 2., 3.]);
    /// }
    /// ```
    pub fn as_real_vector(&self) -> Option<Vec<f64>> {
        self.as_real_slice().map(|value| value.to_vec())
    }

    /// Get a read-only reference to the content of an integer or logical vector.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let robj = r!(Raw::from_bytes(&[1, 2, 3]));
    ///     assert_eq!(robj.as_raw_slice().unwrap(), &[1, 2, 3]);
    /// }
    /// ```
    pub fn as_raw_slice(&self) -> Option<&[u8]> {
        self.as_typed_slice()
    }

    /// Get a read-write reference to the content of an integer or logical vector.
    /// Note that rust slices are 0-based so `slice[1]` is the middle value.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let mut robj = r!([1, 2, 3]);
    ///     let slice : & mut [i32] = robj.as_integer_slice_mut().unwrap();
    ///     slice[1] = 100;
    ///     assert_eq!(robj, r!([1, 100, 3]));
    /// }
    /// ```
    pub fn as_integer_slice_mut(&mut self) -> Option<&mut [i32]> {
        self.as_typed_slice_mut()
    }

    /// Get a read-write reference to the content of a double vector.
    /// Note that rust slices are 0-based so `slice[1]` is the middle value.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let mut robj = r!([1.0, 2.0, 3.0]);
    ///     let slice = robj.as_real_slice_mut().unwrap();
    ///     slice[1] = 100.0;
    ///     assert_eq!(robj, r!([1.0, 100.0, 3.0]));
    /// }
    /// ```
    pub fn as_real_slice_mut(&mut self) -> Option<&mut [f64]> {
        self.as_typed_slice_mut()
    }

    /// Get a read-write reference to the content of a raw vector.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let mut robj = r!(Raw::from_bytes(&[1, 2, 3]));
    ///     let slice = robj.as_raw_slice_mut().unwrap();
    ///     slice[1] = 100;
    ///     assert_eq!(robj, r!(Raw::from_bytes(&[1, 100, 3])));
    /// }
    /// ```
    pub fn as_raw_slice_mut(&mut self) -> Option<&mut [u8]> {
        self.as_typed_slice_mut()
    }

    /// Get a vector of owned strings.
    /// Owned strings have long lifetimes, but are much slower than references.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from("xyz");
    ///    assert_eq!(robj1.as_string_vector(), Some(vec!["xyz".to_string()]));
    ///    let robj2 = Robj::from(1);
    ///    assert_eq!(robj2.as_string_vector(), None);
    /// }
    /// ```
    pub fn as_string_vector(&self) -> Option<Vec<String>> {
        self.as_str_iter()
            .map(|iter| iter.map(str::to_string).collect())
    }

    /// Get a vector of string references.
    /// String references (&str) are faster, but have short lifetimes.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from("xyz");
    ///    assert_eq!(robj1.as_str_vector(), Some(vec!["xyz"]));
    ///    let robj2 = Robj::from(1);
    ///    assert_eq!(robj2.as_str_vector(), None);
    /// }
    /// ```
    pub fn as_str_vector(&self) -> Option<Vec<&str>> {
        self.as_str_iter().map(|iter| iter.collect())
    }

    /// Get a read-only reference to a scalar string type.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from("xyz");
    ///    let robj2 = Robj::from(1);
    ///    assert_eq!(robj1.as_str(), Some("xyz"));
    ///    assert_eq!(robj2.as_str(), None);
    /// }
    /// ```
    pub fn as_str<'a>(&self) -> Option<&'a str> {
        unsafe {
            match self.sexptype() {
                STRSXP => {
                    if self.len() != 1 {
                        None
                    } else {
                        Some(to_str(R_CHAR(STRING_ELT(self.get(), 0)) as *const u8))
                    }
                }
                // CHARSXP => Some(to_str(R_CHAR(self.get()) as *const u8)),
                // SYMSXP => Some(to_str(R_CHAR(PRINTNAME(self.get())) as *const u8)),
                _ => None,
            }
        }
    }

    /// Get a scalar integer.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from("xyz");
    ///    let robj2 = Robj::from(1);
    ///    let robj3 = Robj::from(NA_INTEGER);
    ///    assert_eq!(robj1.as_integer(), None);
    ///    assert_eq!(robj2.as_integer(), Some(1));
    ///    assert_eq!(robj3.as_integer(), None);
    /// }
    /// ```
    pub fn as_integer(&self) -> Option<i32> {
        match self.as_integer_slice() {
            Some(slice) if slice.len() == 1 && !slice[0].is_na() => Some(slice[0]),
            _ => None,
        }
    }

    /// Get a scalar real.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from(1);
    ///    let robj2 = Robj::from(1.);
    ///    let robj3 = Robj::from(NA_REAL);
    ///    assert_eq!(robj1.as_real(), None);
    ///    assert_eq!(robj2.as_real(), Some(1.));
    ///    assert_eq!(robj3.as_real(), None);
    /// }
    /// ```
    pub fn as_real(&self) -> Option<f64> {
        match self.as_real_slice() {
            Some(slice) if slice.len() == 1 && !slice[0].is_na() => Some(slice[0]),
            _ => None,
        }
    }

    /// Get a scalar rust boolean.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from(TRUE);
    ///    let robj2 = Robj::from(1.);
    ///    let robj3 = Robj::from(NA_LOGICAL);
    ///    assert_eq!(robj1.as_bool(), Some(true));
    ///    assert_eq!(robj2.as_bool(), None);
    ///    assert_eq!(robj3.as_bool(), None);
    /// }
    /// ```
    pub fn as_bool(&self) -> Option<bool> {
        match self.as_logical_slice() {
            Some(slice) if slice.len() == 1 && !slice[0].is_na() => Some(slice[0].into()),
            _ => None,
        }
    }

    /// Get a scalar boolean as a tri-boolean [Bool] value.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let robj1 = Robj::from(TRUE);
    ///    let robj2 = Robj::from([TRUE, FALSE]);
    ///    let robj3 = Robj::from(NA_LOGICAL);
    ///    assert_eq!(robj1.as_logical(), Some(TRUE));
    ///    assert_eq!(robj2.as_logical(), None);
    ///    assert_eq!(robj3.as_logical(), Some(NA_LOGICAL));
    /// }
    /// ```
    pub fn as_logical(&self) -> Option<Bool> {
        match self.as_logical_slice() {
            Some(slice) if slice.len() == 1 => Some(slice[0]),
            _ => None,
        }
    }

    /// Evaluate the expression in R and return an error or an R object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    ///    let add = lang!("+", 1, 2);
    ///    assert_eq!(add.eval().unwrap(), r!(3));
    /// }
    /// ```
    pub fn eval(&self) -> Result<Robj> {
        self.eval_with_env(&global_env())
    }

    /// Evaluate the expression in R and return an error or an R object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    ///    let add = lang!("+", 1, 2);
    ///    assert_eq!(add.eval_with_env(&global_env()).unwrap(), r!(3));
    /// }
    /// ```
    pub fn eval_with_env(&self, env: &Environment) -> Result<Robj> {
        single_threaded(|| unsafe {
            let mut error: raw::c_int = 0;
            let res = R_tryEval(self.get(), env.get(), &mut error as *mut raw::c_int);
            if error != 0 {
                Err(Error::EvalError(self.clone()))
            } else {
                Ok(Robj::from_sexp(res))
            }
        })
    }

    /// Evaluate the expression and return NULL or an R object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let bad = lang!("imnotavalidfunctioninR", 1, 2);
    ///    assert_eq!(bad.eval_blind(), r!(NULL));
    /// }
    /// ```
    pub fn eval_blind(&self) -> Robj {
        let res = self.eval();
        if let Ok(robj) = res {
            robj
        } else {
            Robj::from(())
        }
    }
}

/// Generic access to typed slices in an Robj.
pub trait AsTypedSlice<'a, T>
where
    Self: 'a,
{
    fn as_typed_slice(&self) -> Option<&'a [T]>
    where
        Self: 'a,
    {
        None
    }

    fn as_typed_slice_mut(&mut self) -> Option<&'a mut [T]>
    where
        Self: 'a,
    {
        None
    }
}

macro_rules! make_typed_slice {
    ($type: ty, $fn: tt, $($sexp: tt),* ) => {
        impl<'a> AsTypedSlice<'a, $type> for Robj
        where
            Self : 'a,
        {
            fn as_typed_slice(&self) -> Option<&'a [$type]> {
                match self.sexptype() {
                    $( $sexp )|* => {
                        unsafe {
                            let ptr = $fn(self.get()) as *const $type;
                            Some(std::slice::from_raw_parts(ptr, self.len()))
                        }
                    }
                    _ => None
                }
            }

            fn as_typed_slice_mut(&mut self) -> Option<&'a mut [$type]> {
                match self.sexptype() {
                    $( $sexp )|* => {
                        unsafe {
                            let ptr = $fn(self.get()) as *mut $type;
                            Some(std::slice::from_raw_parts_mut(ptr, self.len()))
                        }
                    }
                    _ => None
                }
            }
        }
    }
}

make_typed_slice!(Bool, INTEGER, LGLSXP);
make_typed_slice!(i32, INTEGER, INTSXP);
make_typed_slice!(Rint, INTEGER, INTSXP);
make_typed_slice!(f64, REAL, REALSXP);
make_typed_slice!(Rfloat, REAL, REALSXP);
make_typed_slice!(u8, RAW, RAWSXP);

/// These are helper functions which give access to common properties of R objects.
#[allow(non_snake_case)]
impl Robj {
    /// Get a specific attribute as a borrowed robj if it exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    ///    let mut robj = r!("hello");
    ///    robj.set_attrib(sym!(xyz), 1);
    ///    assert_eq!(robj.get_attrib(sym!(xyz)), Some(r!(1)));
    /// }
    /// ```
    pub fn get_attrib<'a, N>(&self, name: N) -> Option<Robj>
    where
        Self: 'a,
        Robj: From<N> + 'a,
    {
        let name = Robj::from(name);
        if self.sexptype() == CHARSXP {
            None
        } else {
            let res = unsafe { Robj::from_sexp(Rf_getAttrib(self.get(), name.get())) };
            if res.is_null() {
                None
            } else {
                Some(res)
            }
        }
    }

    /// Set a specific attribute and return the object.
    ///
    /// Note that some combinations of attributes are illegal and this will
    /// return an error.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    ///    let mut robj = r!("hello").set_attrib(sym!(xyz), 1)?;
    ///    assert_eq!(robj.get_attrib(sym!(xyz)), Some(r!(1)));
    /// }
    /// ```
    pub fn set_attrib<N, V>(&self, name: N, value: V) -> Result<Robj>
    where
        N: Into<Robj>,
        V: Into<Robj>,
    {
        let name = name.into();
        let value = value.into();
        unsafe {
            single_threaded(|| {
                catch_r_error(|| Rf_setAttrib(self.get(), name.get(), value.get()))
                    .map(|_| self.clone())
            })
        }
    }

    /// Get the names attribute as a string iterator if one exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let list = list!(a = 1, b = 2, c = 3);
    ///    let names : Vec<_> = list.names().unwrap().collect();
    ///    assert_eq!(names, vec!["a", "b", "c"]);
    /// }
    /// ```
    pub fn names(&self) -> Option<StrIter> {
        if let Some(names) = self.get_attrib(wrapper::symbol::names_symbol()) {
            names.as_str_iter()
        } else {
            None
        }
    }

    /// Set the names attribute from a string iterator.
    ///
    /// Returns Error::NamesLengthMismatch if the length of the names does
    /// not match the length of the object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let mut obj = r!([1, 2, 3]).set_names(&["a", "b", "c"]).unwrap();
    ///     assert_eq!(obj.names().unwrap().collect::<Vec<_>>(), vec!["a", "b", "c"]);
    ///     assert_eq!(r!([1, 2, 3]).set_names(&["a", "b"]), Err(Error::NamesLengthMismatch(r!(["a", "b"]))));
    /// }
    /// ```
    pub fn set_names<T>(&mut self, names: T) -> Result<Robj>
    where
        T: IntoIterator,
        T::IntoIter: ExactSizeIterator,
        T::Item: ToVectorValue + AsRef<str>,
    {
        let iter = names.into_iter();
        let robj = iter.collect_robj();
        if robj.len() == self.len() {
            self.set_attrib(wrapper::symbol::names_symbol(), robj)
        } else {
            Err(Error::NamesLengthMismatch(robj))
        }
    }

    /// Get the dim attribute as an integer iterator if one exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///
    ///    let array = R!(r#"array(data = c(1, 2, 3, 4), dim = c(2, 2), dimnames = list(c("x", "y"), c("a","b")))"#).unwrap();
    ///    let dim : Vec<_> = array.dim().unwrap().iter().collect();
    ///    assert_eq!(dim, vec![2, 2]);
    /// }
    /// ```
    pub fn dim(&self) -> Option<Integers> {
        if let Some(dim) = self.get_attrib(wrapper::symbol::dim_symbol()) {
            dim.as_integers()
        } else {
            None
        }
    }

    /// Get the dimnames attribute as a list iterator if one exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let array = R!(r#"array(data = c(1, 2, 3, 4), dim = c(2, 2), dimnames = list(c("x", "y"), c("a","b")))"#).unwrap();
    ///    let names : Vec<_> = array.dimnames().unwrap().collect();
    ///    assert_eq!(names, vec![r!(["x", "y"]), r!(["a", "b"])]);
    /// }
    /// ```
    pub fn dimnames(&self) -> Option<ListIter> {
        if let Some(names) = self.get_attrib(wrapper::symbol::dimnames_symbol()) {
            names.as_list().map(|v| v.values())
        } else {
            None
        }
    }

    /// Get the class attribute as a string iterator if one exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let formula = R!("y ~ A * x + b").unwrap();
    ///    let class : Vec<_> = formula.class().unwrap().collect();
    ///    assert_eq!(class, ["formula"]);
    /// }
    /// ```
    pub fn class(&self) -> Option<StrIter> {
        if let Some(class) = self.get_attrib(wrapper::symbol::class_symbol()) {
            class.as_str_iter()
        } else {
            None
        }
    }

    /// Set the class attribute from a string iterator, returning
    /// a new object.
    ///
    /// May return an error for some class names.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let mut obj = r!([1, 2, 3]).set_class(&["a", "b", "c"])?;
    ///     assert_eq!(obj.class().unwrap().collect::<Vec<_>>(), vec!["a", "b", "c"]);
    ///     assert_eq!(obj.inherits("a"), true);
    /// }
    /// ```
    pub fn set_class<T>(&self, class: T) -> Result<Robj>
    where
        T: IntoIterator,
        T::IntoIter: ExactSizeIterator,
        T::Item: ToVectorValue + AsRef<str>,
    {
        let iter = class.into_iter();
        self.set_attrib(wrapper::symbol::class_symbol(), iter.collect_robj())
    }

    /// Return true if this class inherits this class.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let formula = R!("y ~ A * x + b").unwrap();
    ///    assert_eq!(formula.inherits("formula"), true);
    /// }
    /// ```
    pub fn inherits(&self, classname: &str) -> bool {
        if let Some(mut iter) = self.class() {
            iter.any(|n| n == classname)
        } else {
            false
        }
    }

    /// Get the levels attribute as a string iterator if one exists.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let factor = factor!(vec!["abcd", "def", "fg", "fg"]);
    ///    let levels : Vec<_> = factor.levels().unwrap().collect();
    ///    assert_eq!(levels, vec!["abcd", "def", "fg"]);
    /// }
    /// ```
    pub fn levels(&self) -> Option<StrIter> {
        if let Some(levels) = self.get_attrib(wrapper::symbol::levels_symbol()) {
            levels.as_str_iter()
        } else {
            None
        }
    }
}

#[doc(hidden)]
pub unsafe fn new_owned(sexp: SEXP) -> Robj {
    single_threaded(|| {
        ownership::protect(sexp);
        Robj { inner: sexp }
    })
}

/// Compare equality with integer slices.
impl<'a> PartialEq<[i32]> for Robj {
    fn eq(&self, rhs: &[i32]) -> bool {
        self.as_integer_slice() == Some(rhs)
    }
}

/// Compare equality with slices of double.
impl<'a> PartialEq<[f64]> for Robj {
    fn eq(&self, rhs: &[f64]) -> bool {
        self.as_real_slice() == Some(rhs)
    }
}

/// Compare equality with strings.
impl PartialEq<str> for Robj {
    fn eq(&self, rhs: &str) -> bool {
        self.as_str() == Some(rhs)
    }
}

/// Compare equality with two Robjs.
impl PartialEq<Robj> for Robj {
    fn eq(&self, rhs: &Robj) -> bool {
        unsafe {
            if self.get() == rhs.get() {
                return true;
            }

            // see https://github.com/hadley/r-internals/blob/master/misc.md
            R_compute_identical(self.get(), rhs.get(), 16) != 0
        }
    }
}

/// Implement {:?} formatting.
impl std::fmt::Debug for Robj {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.sexptype() {
            NILSXP => write!(f, "r!(NULL)"),
            SYMSXP => {
                if self.is_missing_arg() {
                    write!(f, "missing_arg()")
                } else if self.is_unbound_value() {
                    write!(f, "unbound_value()")
                } else {
                    write!(f, "sym!({})", self.as_symbol().unwrap().as_str())
                }
            }
            LISTSXP => {
                let pairlist = self.as_pairlist().unwrap().iter();
                write!(f, "r!({:?})", pairlist)
            }
            CLOSXP => {
                let func = self.as_function().unwrap();
                let formals = func.formals();
                let body = func.body();
                let environment = func.environment();
                write!(
                    f,
                    "r!(Function::from_parts({:?}, {:?}, {:?}))",
                    formals, body, environment
                )
            }
            ENVSXP => unsafe {
                let sexp = self.get();
                if sexp == R_GlobalEnv {
                    write!(f, "global_env()")
                } else if sexp == R_BaseEnv {
                    write!(f, "base_env()")
                } else if sexp == R_EmptyEnv {
                    write!(f, "empty_env()")
                } else {
                    write!(f, "r!(Environment::from_pairs(...))")
                }
            },
            PROMSXP => {
                let p = self.as_promise().unwrap();
                write!(
                    f,
                    "r!(Promise::from_parts({:?}, {:?}))",
                    p.code(),
                    p.environment()
                )
            }
            LANGSXP => write!(
                f,
                "r!(Language::from_values({:?}))",
                self.as_language().unwrap().values().collect::<Vec<_>>()
            ),
            SPECIALSXP => write!(f, "r!(Special())"),
            BUILTINSXP => write!(f, "r!(Builtin())"),
            CHARSXP => {
                let c = Rstr::try_from(self.clone()).unwrap();
                write!(f, "r!(Rstr::from_string({:?}))", c.as_str())
            }
            LGLSXP => {
                let slice = self.as_logical_slice().unwrap();
                if slice.len() == 1 {
                    write!(f, "r!({:?})", slice[0])
                } else {
                    write!(f, "r!({:?})", slice)
                }
            }
            INTSXP => {
                let slice = self.as_integer_slice().unwrap();
                if slice.len() == 1 {
                    write!(f, "r!({:?})", slice[0])
                } else {
                    write!(f, "r!({:?})", self.as_integer_slice().unwrap())
                }
            }
            REALSXP => {
                let slice = self.as_real_slice().unwrap();
                if slice.len() == 1 {
                    write!(f, "r!({:?})", slice[0])
                } else {
                    write!(f, "r!({:?})", slice)
                }
            }
            VECSXP => {
                let list = self.as_list().unwrap();
                if self.names().is_some() {
                    write!(f, "r!(List::from_pairs({:?}))", list.iter())
                } else {
                    write!(f, "r!(List::from_values({:?}))", list.values())
                }
            }
            EXPRSXP => write!(
                f,
                "r!(Expression::from_values({:?}))",
                self.as_expression().unwrap().values()
            ),
            WEAKREFSXP => write!(f, "r!(Weakref())"),
            // CPLXSXP => false,
            STRSXP => {
                write!(f, "r!([")?;
                let mut sep = "";
                for s in self.as_str_iter().unwrap() {
                    // if s.is_na() {
                    //     write!(f, "{}na_str()", sep)?;
                    // } else {
                    write!(f, "{}{:?}", sep, s)?;
                    // }
                    sep = ", ";
                }
                write!(f, "])")
            }
            DOTSXP => write!(f, "r!(Dot())"),
            ANYSXP => write!(f, "r!(Any())"),
            BCODESXP => write!(f, "r!(Bcode())"),
            EXTPTRSXP => {
                write!(f, "r!(ExternalPtr())")
            }
            RAWSXP => {
                write!(
                    f,
                    "r!(Raw::from_bytes({:?}))",
                    self.as_raw().unwrap().as_slice()
                )
            }
            S4SXP => write!(f, "r!(S4())"),
            NEWSXP => write!(f, "r!(New())"),
            FREESXP => write!(f, "r!(Free())"),
            _ => write!(f, "??"),
        }?;
        if let Some(c) = self.class() {
            write!(f, ".set_class({:?}", c)?;
        }
        Ok(())
    }
}

// Internal utf8 to str conversion.
// Lets not worry about non-ascii/unicode strings for now (or ever).
pub(crate) unsafe fn to_str<'a>(ptr: *const u8) -> &'a str {
    let mut len = 0;
    loop {
        if *ptr.offset(len) == 0 {
            break;
        }
        len += 1;
    }
    let slice = std::slice::from_raw_parts(ptr, len as usize);
    std::str::from_utf8_unchecked(slice)
}

/// Release any owned objects.
impl Drop for Robj {
    fn drop(&mut self) {
        unsafe {
            ownership::unprotect(self.inner);
        }
    }
}