artichoke_backend/convert/conv.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
//! Implicit conversion routines based on `convert_type_with_id` in MRI.
//!
//! See: <https://github.com/ruby/ruby/blob/v3_1_2/object.c#L2908-L3018>.
use std::ffi::CStr;
use std::sync::OnceLock;
use artichoke_core::debug::Debug as _;
use artichoke_core::value::Value as _;
use qed::const_cstr_from_str as cstr;
use spinoso_exception::TypeError;
use crate::types::Ruby;
use crate::value::Value;
use crate::{Artichoke, Error};
/// Strategy to use for handling errors in [`convert_type`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConvertOnError {
/// Turn conversion errors into `TypeError`s.
Raise,
/// Turn conversion errors into a successful `nil` value.
ReturnNil,
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
struct ConvMethod {
method: &'static str,
cstr: &'static CStr,
id: u32,
is_implicit_conversion: bool,
}
fn conv_method_table(interp: &mut Artichoke) -> &'static [ConvMethod; 12] {
// https://github.com/ruby/ruby/blob/v3_1_2/object.c#L2908-L2928
#[rustfmt::skip]
const METHODS: [(&str, &CStr, bool); 12] = [
("to_int", cstr!("to_int\0"), true),
("to_ary", cstr!("to_ary\0"), true),
("to_str", cstr!("to_str\0"), true),
("to_sym", cstr!("to_sym\0"), true),
("to_hash", cstr!("to_hash\0"), true),
("to_proc", cstr!("to_proc\0"), true),
("to_io", cstr!("to_io\0"), true),
("to_a", cstr!("to_a\0"), false),
("to_s", cstr!("to_s\0"), false),
("to_i", cstr!("to_i\0"), false),
("to_f", cstr!("to_f\0"), false),
("to_r", cstr!("to_r\0"), false),
];
static CONV_METHOD_TABLE: OnceLock<[ConvMethod; 12]> = OnceLock::new();
CONV_METHOD_TABLE.get_or_init(|| {
METHODS.map(|(method, method_cstr, is_implicit_conversion)| {
let bytes = method_cstr.to_bytes_with_nul();
let sym = interp.intern_bytes_with_trailing_nul(bytes).unwrap();
ConvMethod {
method,
cstr: method_cstr,
id: sym,
is_implicit_conversion,
}
})
})
}
/// Attempt a fallible conversion of a Ruby value to a given type tag.
///
/// This function can convert Ruby values at the granularity of a [`Ruby`] type
/// tag. Conversion works as follows:
///
/// - If the given value has the same type tag as the given `convert_to`, return
/// the given value.
/// - Assert that the given conversion method is a valid conversion type.
/// - Call the conversion method on the given value. If this method raises,
/// return the error.
/// - If the converted value does not match the given type tag, raise a
/// [`TypeError`].
/// - The converted value matches the target type, return it.
///
/// # Conversion types
///
/// The method to be called to perform the implicit conversion must be one of a
/// permitted set. Valid method calls are:
///
/// - `to_int`
/// - `to_ary`
/// - `to_str`
/// - `to_sym`
/// - `to_hash`
/// - `to_proc`
/// - `to_io`
/// - `to_a`
/// - `to_s`
/// - `to_i`
/// - `to_f`
/// - `to_r`
///
/// # MRI Compatibility
///
/// This function is modeled after the [`rb_convert_type`] C API in MRI Ruby.
///
/// [`rb_convert_type`]: https://github.com/ruby/ruby/blob/v3_1_2/object.c#L2993-L3004
///
/// # Panics
///
/// If the given method is not a valid conversion method, this function will
/// panic.
///
/// # Errors
///
/// - If the call to the conversion method returns an error, that error is
/// returned.
/// - If the call to the conversion method returns a value that does not match
/// the target type tag, a [`TypeError`] is returned.
pub fn convert_type(
interp: &mut Artichoke,
value: Value,
convert_to: Ruby,
type_name: &str,
method: &str,
raise: ConvertOnError,
) -> Result<Value, Error> {
if value.ruby_type() == convert_to {
return Ok(value);
}
let converted = {
let conversion = conv_method_table(interp)
.iter()
.find(|conversion| conversion.method == method)
.unwrap_or_else(|| panic!("{method} is not a valid conversion method"));
convert_type_inner(interp, value, type_name, conversion, raise)?
};
if converted.ruby_type() != convert_to {
return Err(conversion_mismatch(interp, value, type_name, method, converted).into());
}
Ok(converted)
}
/// Attempt a fallible conversion of a Ruby value to a given type tag or `nil`.
///
/// This function can convert Ruby values at the granularity of a [`Ruby`] type
/// tag. Conversion works as follows:
///
/// - If the given value has the same type tag as the given `convert_to`, return
/// the given value.
/// - Assert that the given conversion method is a valid conversion type.
/// - Call the conversion method on the given value. If this method raises,
/// return the error.
/// - If the converted value is `nil`, return `nil`.
/// - If the converted value does not match the given type tag, raise a
/// [`TypeError`].
/// - The converted value matches the target type, return it.
///
/// # Conversion types
///
/// The method to be called to perform the implicit conversion must be one of a
/// permitted set. Valid method calls are:
///
/// - `to_int`
/// - `to_ary`
/// - `to_str`
/// - `to_sym`
/// - `to_hash`
/// - `to_proc`
/// - `to_io`
/// - `to_a`
/// - `to_s`
/// - `to_i`
/// - `to_f`
/// - `to_r`
///
/// # MRI Compatibility
///
/// This function is modeled after the [`rb_check_convert_type_with_id`] C API
/// in MRI Ruby.
///
/// [`rb_check_convert_type_with_id`]: https://github.com/ruby/ruby/blob/v3_1_2/object.c#L3035-L3049
///
/// # Panics
///
/// If the given method is not a valid conversion method, this function will
/// panic.
///
/// # Errors
///
/// - If the call to the conversion method returns an error, that error is
/// returned.
/// - If the call to the conversion method returns a value that does is non-`nil`
/// and not match the target type tag, a [`TypeError`] is returned.
pub fn check_convert_type(
interp: &mut Artichoke,
value: Value,
convert_to: Ruby,
type_name: &str,
method: &str,
) -> Result<Value, Error> {
// always convert T_DATA
if value.ruby_type() == convert_to && convert_to != Ruby::Data {
return Ok(value);
}
let converted = {
let conversion = conv_method_table(interp)
.iter()
.find(|conversion| conversion.method == method)
.unwrap_or_else(|| panic!("{method} is not a valid conversion method"));
convert_type_inner(interp, value, type_name, conversion, ConvertOnError::ReturnNil)?
};
match converted.ruby_type() {
Ruby::Nil => Ok(Value::nil()),
tt if tt == convert_to => Ok(converted),
_ => Err(conversion_mismatch(interp, value, type_name, method, converted).into()),
}
}
// https://github.com/ruby/ruby/blob/v3_1_2/object.c#L2948-L2971
fn convert_type_inner(
interp: &mut Artichoke,
value: Value,
type_name: &str,
conversion: &'static ConvMethod,
raise: ConvertOnError,
) -> Result<Value, Error> {
if value.respond_to(interp, conversion.method)? {
return value.funcall(interp, conversion.method, &[], None);
}
let mut message = match raise {
ConvertOnError::ReturnNil => return Ok(Value::nil()),
ConvertOnError::Raise if conversion.is_implicit_conversion => String::from("no implicit conversion of "),
ConvertOnError::Raise => String::from("can't convert "),
};
match value.try_convert_into::<Option<bool>>(interp) {
Ok(None) => message.push_str("nil"),
Ok(Some(true)) => message.push_str("true"),
Ok(Some(false)) => message.push_str("false"),
Err(_) => message.push_str(interp.class_name_for_value(value)),
}
message.push_str(" into ");
message.push_str(type_name);
Err(TypeError::from(message).into())
}
// https://github.com/ruby/ruby/blob/v3_1_2/object.c#L2982-L2991
fn conversion_mismatch(
interp: &mut Artichoke,
value: Value,
type_name: &str,
method: &str,
result: Value,
) -> TypeError {
let cname = interp.inspect_type_name_for_value(value);
let mut message = String::from("can't convert ");
message.push_str(cname);
message.push_str(" to ");
message.push_str(type_name);
message.push_str(" (");
message.push_str(cname);
message.push('#');
message.push_str(method);
message.push_str(" gives ");
message.push_str(interp.class_name_for_value(result));
message.push(')');
TypeError::from(message)
}
#[inline]
fn try_to_int(interp: &mut Artichoke, val: Value, method: &str, raise: ConvertOnError) -> Result<Value, Error> {
let conversion = conv_method_table(interp)
.iter()
.find(|conversion| conversion.method == method)
.unwrap_or_else(|| panic!("{method} is not a valid conversion method"));
convert_type_inner(interp, val, "Integer", conversion, raise)
}
/// Fallible conversion of the given value to a Ruby `Integer` via `#to_int`.
///
/// If the given value is an integer, it is returned. If the give value responds
/// to a `#to_int` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// a non-`nil` Ruby `Integer`.
///
/// # Errors
///
/// - If the call to `#to_int` returns an error, that error is returned.
/// - If the call to `#to_int` returns anything other than a `Integer`, a
/// [`TypeError`] is returned.
#[inline]
pub fn to_int(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
// Fast path (no additional funcalls) for values that are already integers.
if let Ruby::Fixnum = value.ruby_type() {
return Ok(value);
}
convert_type(interp, value, Ruby::Fixnum, "Integer", "to_int", ConvertOnError::Raise)
}
/// Fallible conversion of the given value to a Ruby `Integer` or `nil` via
/// `#to_int`.
///
/// If the given value is an integer, it is returned. If the give value responds
/// to a `#to_int` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// either a Ruby `Integer` or `nil`.
///
/// # Errors
///
/// - If the call to `#to_int` returns an error, that error is returned.
/// - If the call to `#to_int` returns anything other than an `Integer` or `nil`,
/// a [`TypeError`] is returned.
#[inline]
pub fn check_to_int(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
// Fast path (no additional funcalls) for values that are already integers.
if let Ruby::Fixnum = value.ruby_type() {
return Ok(value);
}
let value = try_to_int(interp, value, "to_int", ConvertOnError::ReturnNil)?;
if let Ruby::Fixnum = value.ruby_type() {
Ok(value)
} else {
Ok(Value::nil())
}
}
/// Fallible coercion of the given value to a Ruby `Integer` via `#to_i`.
///
/// If the given value is an integer, it is returned. If the give value responds
/// to a `#to_i` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// a non-`nil` Ruby `Integer`.
///
/// # Errors
///
/// - If the call to `#to_i` returns an error, that error is returned.
/// - If the call to `#to_i` returns anything other than a `Integer`, a
/// [`TypeError`] is returned.
#[inline]
pub fn to_i(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
if let Ruby::Fixnum = value.ruby_type() {
return Ok(value);
}
convert_type(interp, value, Ruby::Fixnum, "Integer", "to_i", ConvertOnError::Raise)
}
// NOTE: A `check_to_i` variant is only used in `Kernel#Integer`.
//
// This API is not necessary in Artichoke since exceptions are passed by value
// instead of via unwinding.
//
// See: https://github.com/ruby/ruby/blob/v3_1_2/object.c#L3149
/*
#[inline(always)]
pub(crate) fn check_to_i(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
// Fast path (no additional funcalls) for values that are already integers.
if let Ruby::Fixnum = value.ruby_type() {
return Ok(value);
}
let val = try_to_int(interp, val, "to_i", ConvertOnError::ReturnNil)?;
if let Ruby::Fixnum = val.ruby_type() {
Ok(val)
} else {
Ok(Value::nil())
}
}
*/
/// Fallible conversion of the given value to a Ruby `String` via `#to_str`.
///
/// If the given value is a string, it is returned. If the give value responds
/// to a `#to_str` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// a non-`nil` Ruby `String`.
///
/// # Errors
///
/// - If the call to `#to_str` returns an error, that error is returned.
/// - If the call to `#to_str` returns anything other than a `String`, a
/// [`TypeError`] is returned.
pub fn to_str(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
convert_type(interp, value, Ruby::String, "String", "to_str", ConvertOnError::Raise)
}
/// Fallible conversion of the given value to a Ruby `String` or `nil` via
/// `#to_str`.
///
/// If the given value is a string, it is returned. If the give value responds
/// to a `#to_str` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// either a Ruby `String` or `nil`.
///
/// # Errors
///
/// - If the call to `#to_str` returns an error, that error is returned.
/// - If the call to `#to_str` returns anything other than a `String` or `nil`,
/// a [`TypeError`] is returned.
pub fn check_to_str(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
check_convert_type(interp, value, Ruby::String, "String", "to_str")
}
pub fn check_string_type(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
check_convert_type(interp, value, Ruby::String, "String", "to_str")
}
/// Fallible conversion of the given value to a Ruby `Array` via `#to_ary`.
///
/// If the given value is a array, it is returned. If the give value responds
/// to a `#to_ary` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// a non-`nil` Ruby `Array`.
///
/// # Errors
///
/// - If the call to `#to_ary` returns an error, that error is returned.
/// - If the call to `#to_ary` returns anything other than an `Array`, a
/// [`TypeError`] is returned.
pub fn to_ary(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
convert_type(interp, value, Ruby::Array, "Array", "to_ary", ConvertOnError::Raise)
}
/// Fallible conversion of the given value to a Ruby `Array` or `nil` via
/// `#to_ary`.
///
/// If the given value is a array, it is returned. If the give value responds
/// to a `#to_ary` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// either a Ruby `Array` or `nil`.
///
/// # Errors
///
/// - If the call to `#to_ary` returns an error, that error is returned.
/// - If the call to `#to_ary` returns anything other than an `Array` or `nil`,
/// a [`TypeError`] is returned.
pub fn check_to_ary(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
check_convert_type(interp, value, Ruby::Array, "Array", "to_ary")
}
/// Fallible coercion of the given value to a Ruby `Array` via `#to_a`.
///
/// If the given value is a array, it is returned. If the give value responds
/// to a `#to_a` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// a non-`nil` Ruby `Array`.
///
/// # Errors
///
/// - If the call to `#to_a` returns an error, that error is returned.
/// - If the call to `#to_a` returns anything other than an `Array`, a
/// [`TypeError`] is returned.
pub fn to_a(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
convert_type(interp, value, Ruby::Array, "Array", "to_a", ConvertOnError::Raise)
}
/// Fallible coercion of the given value to a Ruby `Array` or `nil` via `#to_a`.
///
/// If the given value is a array, it is returned. If the give value responds
/// to a `#to_a` method, it is called. Otherwise, a [`TypeError`] is raised.
///
/// If this function returns [`Ok`], the returned [`Value`] is guaranteed to be
/// either a Ruby `Array` or `nil`.
///
/// # Errors
///
/// - If the call to `#to_a` returns an error, that error is returned.
/// - If the call to `#to_a` returns anything other than an `Array` or `nil`,
/// a [`TypeError`] is returned.
pub fn check_to_a(interp: &mut Artichoke, value: Value) -> Result<Value, Error> {
check_convert_type(interp, value, Ruby::Array, "Array", "to_a")
}
#[cfg(test)]
mod tests {
use bstr::ByteSlice;
use super::{conv_method_table, convert_type, to_int, ConvertOnError};
use crate::test::prelude::*;
#[test]
fn conv_method_table_is_built() {
let mut interp = interpreter();
assert_eq!(
conv_method_table(&mut interp).as_ptr(),
conv_method_table(&mut interp).as_ptr()
);
}
#[test]
fn seven_implicit_conversions() {
let mut interp = interpreter();
for (idx, conv) in conv_method_table(&mut interp).iter().enumerate() {
if idx < 7 {
assert!(
conv.is_implicit_conversion,
"{} should be implicit conversion",
conv.method
);
} else {
assert!(
!conv.is_implicit_conversion,
"{} should NOT be implicit conversion",
conv.method
);
}
}
}
#[test]
fn to_int_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_int")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_ary_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_ary")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_str_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_str")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_sym_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_sym")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_hash_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_hash")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_proc_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_proc")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_io_is_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_io")
.unwrap();
assert!(conv.is_implicit_conversion);
}
#[test]
fn to_a_is_not_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_a")
.unwrap();
assert!(!conv.is_implicit_conversion);
}
#[test]
fn to_s_is_not_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_s")
.unwrap();
assert!(!conv.is_implicit_conversion);
}
#[test]
fn to_i_is_not_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_i")
.unwrap();
assert!(!conv.is_implicit_conversion);
}
#[test]
fn to_f_is_not_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_f")
.unwrap();
assert!(!conv.is_implicit_conversion);
}
#[test]
fn to_r_is_not_implicit_conversion() {
let mut interp = interpreter();
let conv = conv_method_table(&mut interp)
.iter()
.find(|conv| conv.method == "to_r")
.unwrap();
assert!(!conv.is_implicit_conversion);
}
#[test]
fn implicit_to_int_reflexive() {
let mut interp = interpreter();
let i = interp.convert(17);
let converted =
convert_type(&mut interp, i, Ruby::Fixnum, "Integer", "to_int", ConvertOnError::Raise).unwrap();
let converted = converted.try_convert_into::<i64>(&interp).unwrap();
assert_eq!(17, converted);
}
#[test]
fn implicit_to_int_conv() {
let mut interp = interpreter();
interp.eval(b"class A; def to_int; 17; end; end").unwrap();
let value = interp.eval(b"A.new").unwrap();
let converted = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap();
let converted = converted.try_convert_into::<i64>(&interp).unwrap();
assert_eq!(17, converted);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[true]
// (irb):2:in `<main>': no implicit conversion of true into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn implicit_to_int_true_type_error() {
let mut interp = interpreter();
let value = interp.convert(true);
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of true into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[false]
// (irb):3:in `<main>': no implicit conversion of false into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn implicit_to_int_false_type_error() {
let mut interp = interpreter();
let value = interp.convert(false);
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of false into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[Object.new]
// (irb):3:in `<main>': no implicit conversion of Object into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn implicit_to_int_object_type_error() {
let mut interp = interpreter();
let value = interp.eval(b"Object.new").unwrap();
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of Object into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class C; def to_int; nil; end; end
// => :to_int
// [3.1.2] > a[C.new]
// (irb):5:in `<main>': can't convert C to Integer (C#to_int gives NilClass) (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn implicit_to_int_object_with_nil_to_int_returns_nil() {
let mut interp = interpreter();
// define class
interp.eval(b"class C; def to_int; nil; end; end").unwrap();
let value = interp.eval(b"C.new").unwrap();
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"can't convert C to Integer (C#to_int gives NilClass)".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class D; def to_int; 'not an integer'; end; end
// => :to_int
// [3.1.2] > a[D.new]
// (irb):7:in `<main>': can't convert D to Integer (D#to_int gives String) (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn implicit_to_int_object_with_string_to_int_returns_type_error() {
let mut interp = interpreter();
// define class
interp.eval(b"class D; def to_int; 'not an integer'; end; end").unwrap();
let value = interp.eval(b"D.new").unwrap();
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"can't convert D to Integer (D#to_int gives String)".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class F; def to_int; raise ArgumentError, 'not an integer'; end; end
// => :to_int
// [3.1.2] > a[F.new]
// (irb):8:in `to_int': not an integer (ArgumentError)
// from (irb):9:in `<main>'
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
#[test]
fn implicit_to_int_object_with_raising_to_int_returns_raised_exception() {
let mut interp = interpreter();
// define class
interp
.eval(b"class F; def to_int; raise ArgumentError, 'not an integer'; end; end")
.unwrap();
let value = interp.eval(b"F.new").unwrap();
let err = convert_type(
&mut interp,
value,
Ruby::Fixnum,
"Integer",
"to_int",
ConvertOnError::Raise,
)
.unwrap_err();
assert_eq!(err.name(), "ArgumentError");
assert_eq!(err.message().as_bstr(), b"not an integer".as_bstr());
}
#[test]
fn to_int_reflexive() {
let mut interp = interpreter();
let i = interp.convert(17);
let converted = to_int(&mut interp, i).unwrap();
let converted = converted.try_convert_into::<i64>(&interp).unwrap();
assert_eq!(17, converted);
}
#[test]
fn to_int_conv() {
let mut interp = interpreter();
interp.eval(b"class A; def to_int; 17; end; end").unwrap();
let value = interp.eval(b"A.new").unwrap();
let converted = to_int(&mut interp, value).unwrap();
let converted = converted.try_convert_into::<i64>(&interp).unwrap();
assert_eq!(17, converted);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[true]
// (irb):2:in `<main>': no implicit conversion of true into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn to_int_true_type_error() {
let mut interp = interpreter();
let value = interp.convert(true);
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of true into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[false]
// (irb):3:in `<main>': no implicit conversion of false into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn to_int_false_type_error() {
let mut interp = interpreter();
let value = interp.convert(false);
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of false into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > a[Object.new]
// (irb):3:in `<main>': no implicit conversion of Object into Integer (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn to_int_object_type_error() {
let mut interp = interpreter();
let value = interp.eval(b"Object.new").unwrap();
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"no implicit conversion of Object into Integer".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class C; def to_int; nil; end; end
// => :to_int
// [3.1.2] > a[C.new]
// (irb):5:in `<main>': can't convert C to Integer (C#to_int gives NilClass) (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn to_int_object_with_nil_to_int_returns_nil() {
let mut interp = interpreter();
// define class
interp.eval(b"class C; def to_int; nil; end; end").unwrap();
let value = interp.eval(b"C.new").unwrap();
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"can't convert C to Integer (C#to_int gives NilClass)".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class D; def to_int; 'not an integer'; end; end
// => :to_int
// [3.1.2] > a[D.new]
// (irb):7:in `<main>': can't convert D to Integer (D#to_int gives String) (TypeError)
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
// ```
#[test]
fn to_int_object_with_string_to_int_returns_type_error() {
let mut interp = interpreter();
// define class
interp.eval(b"class D; def to_int; 'not an integer'; end; end").unwrap();
let value = interp.eval(b"D.new").unwrap();
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "TypeError");
assert_eq!(
err.message().as_bstr(),
b"can't convert D to Integer (D#to_int gives String)".as_bstr()
);
}
// ```console
// [3.1.2] > a = []
// => []
// [3.1.2] > class F; def to_int; raise ArgumentError, 'not an integer'; end; end
// => :to_int
// [3.1.2] > a[F.new]
// (irb):8:in `to_int': not an integer (ArgumentError)
// from (irb):9:in `<main>'
// from /usr/local/var/rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `load'
// from /usr/local/var/rbenv/versions/3.1.2/bin/irb:25:in `<main>'
#[test]
fn to_int_object_with_raising_to_int_returns_raised_exception() {
let mut interp = interpreter();
// define class
interp
.eval(b"class F; def to_int; raise ArgumentError, 'not an integer'; end; end")
.unwrap();
let value = interp.eval(b"F.new").unwrap();
let err = to_int(&mut interp, value).unwrap_err();
assert_eq!(err.name(), "ArgumentError");
assert_eq!(err.message().as_bstr(), b"not an integer".as_bstr());
}
}