1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
//! Managed type for arbitrary Julia data.
//!
//! Julia data returned by the C API is often returned as a pointer to `jl_value_t`, which is
//! an opaque type. This pointer is wrapped in jlrs by [`Value`]. The layout of the data that is
//! pointed to depends on its underlying type. Julia guarantees that the data is preceded in
//! memory by a header which contains a pointer to the data's type information, its [`DataType`].
//!
//! For example, if the `DataType` is `UInt8`, the pointer points to a `u8`. If the
//! `DataType` is some Julia array type like `Array{Int, 2}`, the pointer points to
//! Julia's internal array type, `jl_array_t`. In the first case tha value can be unboxed as a
//! `u8`, in the second case it can be cast to [`Array`] or [`TypedArray<isize>`].
//!
//! The `Value` type is very commonly used in jlrs. A `Value` can be called as a Julia function,
//! the arguments such a function takes are all `Value`s, and it will return either a `Value` or
//! an exception which is also a `Value`. This type also provides methods to create new `Value`s,
//! access their fields, cast them to the appropriate managed type, and unbox their contents.
//!
//! One special kind of value is the `NamedTuple`. You will need to create values of this type in
//! order to call functions with keyword arguments. The macro [`named_tuple`] is defined in this
//! module which provides an easy way to create values of this type.
//!
//! [`TypedArray<isize>`]: crate::data::managed::array::TypedArray
//! [`named_tuple`]: crate::named_tuple!
/*
TODO
Atomic operations:
jl_atomic_cmpswap_bits
jl_atomic_bool_cmpswap_bits
jl_atomic_new_bits
jl_atomic_store_bits
jl_atomic_swap_bits
*/
pub mod field_accessor;
pub mod tracked;
pub mod typed;
#[doc(hidden)]
#[macro_export]
macro_rules! count {
($name:expr => $value:expr) => {
2
};
($name:expr => $value:expr, $($rest:tt)+) => {
count!(2, $($rest)+)
};
($n:expr, $name:expr => $value:expr) => {
$n + 1
};
($n:expr, $name:expr => $value:expr, $($rest:tt)+) => {
count!($n + 1, $($rest)+)
};
}
/// Create a new named tuple. You will need a named tuple to call functions with keyword
/// arguments.
///
/// Example:
///
/// ```
/// # use jlrs::prelude::*;
/// # use jlrs::util::test::JULIA;
/// # fn main() {
/// # JULIA.with(|j| {
/// # let mut julia = j.borrow_mut();
/// # let mut frame = StackFrame::new();
/// # let mut julia = julia.instance(&mut frame);
/// // Three slots; two for the inputs and one for the output.
/// julia.scope(|mut frame| {
/// // Create the two arguments, each value requires one slot
/// let i = Value::new(&mut frame, 2u64);
/// let j = Value::new(&mut frame, 1u32);
///
/// let _nt = named_tuple!(&mut frame, "i" => i, "j" => j);
///
/// Ok(())
/// }).unwrap();
/// # });
/// # }
/// ```
#[macro_export]
macro_rules! named_tuple {
($frame:expr, $name:expr => $value:expr) => {
{
let name = $crate::convert::to_symbol::ToSymbol::to_symbol(&$name, &$frame);
$crate::data::managed::value::Value::new_named_tuple($frame, &[(name, $value)])
}
};
($frame:expr, $name:expr => $value:expr, $($rest:tt)+) => {
{
const n: usize = $crate::count!($($rest)+);
let mut pairs: [::std::mem::MaybeUninit::<($crate::data::managed::symbol::Symbol, $crate::data::managed::value::Value)>; n] = [::std::mem::MaybeUninit::uninit(); n];
let name = $crate::convert::to_symbol::ToSymbol::to_symbol(&$name, &$frame);
pairs[0].write((name, $value));
$crate::named_tuple!($frame, 1, &mut pairs, $($rest)+)
}
};
($frame:expr, $i:expr, $pairs:expr, $name:expr => $value:expr, $($rest:tt)+) => {
{
let name = $crate::convert::to_symbol::ToSymbol::to_symbol(&$name, &$frame);
$pairs[$i].write((name, $value));
named_tuple!($frame, $i + 1, $pairs, $($rest)+)
}
};
($frame:expr, $i:expr, $pairs:expr, $name:expr => $value:expr) => {
{
let name = $crate::convert::to_symbol::ToSymbol::to_symbol(&$name, &$frame);
$pairs[$i].write((name, $value));
let pairs: &[($crate::data::managed::symbol::Symbol, $crate::data::managed::value::Value); n] = unsafe {
::std::mem::transmute::<
&[::std::mem::MaybeUninit::<($crate::data::managed::symbol::Symbol, $crate::data::managed::value::Value)>; n],
&[($crate::data::managed::symbol::Symbol, $crate::data::managed::value::Value); n]
>($pairs)
};
$crate::data::managed::value::Value::new_named_tuple($frame, pairs)
}
};
}
use std::{
ffi::{c_void, CStr, CString},
marker::PhantomData,
mem::MaybeUninit,
path::Path,
ptr::NonNull,
usize,
};
#[julia_version(since = "1.7")]
use jl_sys::jl_pair_type;
use jl_sys::{
jl_an_empty_string, jl_an_empty_vec_any, jl_any_type, jl_apply_generic, jl_apply_type,
jl_array_any_type, jl_array_int32_type, jl_array_symbol_type, jl_array_uint8_type,
jl_bottom_type, jl_call, jl_call0, jl_call1, jl_call2, jl_call3, jl_diverror_exception,
jl_egal, jl_emptytuple, jl_eval_string, jl_exception_occurred, jl_false, jl_field_index,
jl_field_isptr, jl_gc_add_finalizer, jl_gc_add_ptr_finalizer, jl_get_nth_field,
jl_get_nth_field_noalloc, jl_get_world_counter, jl_interrupt_exception, jl_isa,
jl_memory_exception, jl_new_struct_uninit, jl_nothing, jl_object_id,
jl_readonlymemory_exception, jl_set_nth_field, jl_stackovf_exception, jl_stderr_obj,
jl_stdout_obj, jl_subtype, jl_true, jl_typeof_str, jl_undefref_exception, jl_value_t,
};
use jlrs_macros::julia_version;
use self::{field_accessor::FieldAccessor, typed::TypedValue};
use super::Ref;
use crate::{
args::Values,
call::{Call, ProvideKeywords, WithKeywords},
catch::catch_exceptions,
convert::{into_julia::IntoJulia, to_symbol::ToSymbol, unbox::Unbox},
data::{
layout::{
is_bits::IsBits,
typed_layout::HasLayout,
valid_layout::{ValidField, ValidLayout},
},
managed::{
array::Array,
datatype::DataType,
module::Module,
private::ManagedPriv,
string::JuliaString,
symbol::Symbol,
union::Union,
union_all::UnionAll,
value::tracked::{Tracked, TrackedMut},
Managed,
},
types::{
construct_type::ConstructType,
typecheck::{NamedTuple, Typecheck},
},
},
error::{AccessError, IOError, JlrsError, JlrsResult, TypeError, CANNOT_DISPLAY_TYPE},
memory::{
context::ledger::Ledger,
get_tls,
target::{unrooted::Unrooted, Target, TargetException, TargetResult},
},
prelude::NTuple,
private::Private,
};
/// Arbitrary Julia data.
///
/// A `Value` is essentially a non-null pointer to some data owned by the Julia garbage
/// collector with two lifetimes: `'scope` and `'data`. The first of these ensures that a
/// `Value` can only be used while it's rooted, the second accounts for data borrowed from Rust.
/// The only way to borrow data from Rust is to create an Julia array that borrows its contents
/// by calling [`Array::from_slice`]; if a Julia function is called with such an array as an
/// argument the result will inherit the second lifetime of the borrowed data to ensure that
/// such a `Value` can only be used while the borrow is active.
///
/// See the [module-level documentation] for more information.
#[repr(transparent)]
#[derive(Copy, Clone, Eq)]
pub struct Value<'scope, 'data>(
NonNull<jl_value_t>,
PhantomData<&'scope ()>,
PhantomData<&'data mut ()>,
);
impl<'scope, 'data, T: Managed<'scope, 'data>> PartialEq<T> for Value<'_, '_> {
#[inline]
fn eq(&self, other: &T) -> bool {
self.egal(other.as_value())
}
}
// Safety: it's always safe to treat managed data as a `Value`.
unsafe impl Typecheck for Value<'_, '_> {
#[inline]
fn typecheck(_: DataType) -> bool {
true
}
}
/// # Create new `Value`s
///
/// Several methods are available to create new values. The simplest of these is [`Value::new`],
/// which can be used to convert relatively simple data from Rust to Julia. Data that can be
/// converted this way must implement [`IntoJulia`], which is the case for types like the
/// primitive number types. This trait is also automatically derived by JlrsReflect.jl for types
/// that are trivially guaranteed to be bits-types: the type must have no type parameters, no
/// unions, and all fields must be immutable bits-types themselves.
impl Value<'_, '_> {
/// Create a new Julia value, any type that implements [`IntoJulia`] can be converted using
/// this function.
#[inline]
pub fn new<'target, V, Tgt>(target: Tgt, value: V) -> ValueData<'target, 'static, Tgt>
where
V: IntoJulia,
Tgt: Target<'target>,
{
value.into_julia(target)
}
/// Create a new Julia value, any type that implements [`IsBits`] can be converted using
/// this function.
pub fn new_bits<'target, T, Tgt>(target: Tgt, layout: T) -> ValueData<'target, 'static, Tgt>
where
T: ConstructType + ValidLayout + IsBits,
Tgt: Target<'target>,
{
unsafe {
let ty = T::construct_type(&target)
.as_value()
.cast_unchecked::<DataType>();
let val = NonNull::new_unchecked(jl_new_struct_uninit(ty.unwrap(Private)));
val.cast::<MaybeUninit<T>>().as_mut().write(layout);
target.data_from_ptr(val, Private)
}
}
/// Create a new Julia value using `T` to construct the type. The layout must implement
/// `IsBits`.
pub fn new_bits_from_layout<'target, T, Tgt>(
target: Tgt,
layout: T::Layout,
) -> JlrsResult<ValueData<'target, 'static, Tgt>>
where
T: HasLayout<'target, 'static>,
T::Layout: IsBits,
Tgt: Target<'target>,
{
unsafe {
let ty = T::construct_type(&target).as_value().cast::<DataType>()?;
let val = NonNull::new_unchecked(jl_new_struct_uninit(ty.unwrap(Private)));
val.cast::<MaybeUninit<T::Layout>>().as_mut().write(layout);
Ok(target.data_from_ptr(val, Private))
}
}
/// Create a new Julia value using `T` to construct the type and an arbitrary layout `L`.
///
/// If the layout is not valid for `T` `TypeError::InvalidLayout` is returned.
pub fn new_bits_with_type<'target, T, L, Tgt>(
target: Tgt,
layout: L,
) -> JlrsResult<ValueData<'target, 'static, Tgt>>
where
T: ConstructType,
L: IsBits + ValidLayout,
Tgt: Target<'target>,
{
unsafe {
let ty = T::construct_type(&target).as_value();
if !L::valid_layout(ty) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE);
Err(TypeError::InvalidLayout { value_type })?;
}
let ty = ty.cast_unchecked::<DataType>();
let val = NonNull::new_unchecked(jl_new_struct_uninit(ty.unwrap(Private)));
val.cast::<MaybeUninit<L>>().as_mut().write(layout);
Ok(target.data_from_ptr(val, Private))
}
}
/// Create a new `Value` from the provided layout and type constructor.
///
/// This is a more powerful version of [`Value::new`]. While that method is limited to types
/// that implement `IntoJulia`, this method can create instances of any constructible type by
/// providing a layout which is compatible with that type.
///
/// This method returns an error if `L` is not a valid layout for `V`.
///
/// Safety:
///
/// If the layout contains references to Julia data, those fields must either be `None` or
/// point to valid data.
pub unsafe fn try_new_with<'target, Ty, L, Tgt>(
target: Tgt,
layout: L,
) -> JlrsResult<ValueData<'target, 'static, Tgt>>
where
Ty: ConstructType,
L: ValidLayout,
Tgt: Target<'target>,
{
target.with_local_scope::<_, _, 1>(|target, mut frame| {
let ty = Ty::construct_type(&mut frame);
let ty_dt = ty.cast::<DataType>()?;
if !ty_dt.is_concrete_type() {
let value = ty.display_string_or(CANNOT_DISPLAY_TYPE);
Err(TypeError::NotConcrete { value })?;
}
if !L::valid_layout(ty) || L::IS_REF {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE);
Err(TypeError::InvalidLayout { value_type })?;
}
if let Some(n_fields) = ty_dt.n_fields() {
for i in 0..n_fields as usize {
let ft = ty_dt.field_type_unchecked(&frame, i).unwrap().as_value();
if ty_dt.is_pointer_field_unchecked(i) {
let offset = ty_dt.field_offset_unchecked(i) as usize;
check_field_isa(ft, &layout, offset)?;
} else if let Ok(u) = ft.cast::<Union>() {
check_union_equivalent::<L, _>(&frame, i, u)?;
}
}
}
let ptr = jl_new_struct_uninit(ty_dt.unwrap(Private));
std::ptr::write(ptr.cast::<L>(), layout);
Ok(target.data_from_ptr(NonNull::new_unchecked(ptr), Private))
})
}
/// Create a new named tuple, you should use the `named_tuple` macro rather than this method.
pub fn new_named_tuple<'target, 'value, 'data, Tgt, const N: usize>(
target: Tgt,
pairs: &[(Symbol<'value>, Value<'value, 'data>); N],
) -> ValueData<'target, 'data, Tgt>
where
Tgt: Target<'target>,
{
unsafe {
target
.with_local_scope::<_, _, 1>(|target, mut frame| {
// Safety: this method can only be called from a thread known to Julia. The
// unchecked methods are used because it can be guaranteed they won't throw
// an exception for the given arguments.
let field_names = pairs.map(|(sym, _)| sym.as_value());
let names = NTuple::<Symbol, N>::construct_type(&frame)
.as_value()
.cast::<DataType>()?
.instantiate_unchecked(&mut frame, &field_names);
let values = pairs.map(|(_, val)| val);
let field_types = values.map(|val| val.datatype().as_value());
let field_types = DataType::anytuple_type(&frame)
.as_value()
.apply_type_unchecked(&frame, &field_types)
.as_value();
let ty = UnionAll::namedtuple_type(&frame)
.as_value()
.apply_type_unchecked(&frame, &[names, field_types])
.as_value()
.cast_unchecked::<DataType>();
Ok(ty.instantiate_unchecked(target, values))
})
.unwrap_unchecked()
}
}
/// Apply the given types to `self`.
///
/// If `self` is the [`DataType`] `anytuple_type`, calling this method will return a new
/// tuple type with the given types as its field types. If it is the [`DataType`]
/// `uniontype_type`, calling this method is equivalent to calling [`Union::new`]. If
/// the value is a `UnionAll`, the given types will be applied and the resulting type is
/// returned.
///
/// If the types can't be applied to `self` this methods catches and returns the exception.
///
/// [`Union::new`]: crate::data::managed::union::Union::new
pub fn apply_type<'target, 'value, 'data, V, T>(
self,
target: T,
types: V,
) -> ValueResult<'target, 'data, T>
where
T: Target<'target>,
V: AsRef<[Value<'value, 'data>]>,
{
// Safety: if an exception is thrown it's caught, the result is immediately rooted
unsafe {
let types = types.as_ref();
let callback =
|| jl_apply_type(self.unwrap(Private), types.as_ptr() as *mut _, types.len());
let exc = |err: Value| err.unwrap_non_null(Private);
let res = match catch_exceptions(callback, exc) {
Ok(ptr) => Ok(NonNull::new_unchecked(ptr)),
Err(e) => Err(e),
};
target.result_from_ptr(res, Private)
}
}
/// Apply the given types to `self`.
///
/// If `self` is the [`DataType`] `anytuple_type`, calling this method will return a new
/// tuple type with the given types as its field types. If it is the [`DataType`]
/// `uniontype_type`, calling this method is equivalent to calling [`Union::new`]. If
/// the value is a `UnionAll`, the given types will be applied and the resulting type is
/// returned.
///
/// If an exception is thrown it isn't caught
///
/// Safety: an exception must not be thrown if this method is called from a `ccall`ed
/// function.
///
/// [`Union::new`]: crate::data::managed::union::Union::new
#[inline]
pub unsafe fn apply_type_unchecked<'target, 'value, 'data, T, V>(
self,
target: T,
types: V,
) -> ValueData<'target, 'data, T>
where
T: Target<'target>,
V: AsRef<[Value<'value, 'data>]>,
{
let types = types.as_ref();
let applied = jl_apply_type(self.unwrap(Private), types.as_ptr() as *mut _, types.len());
target.data_from_ptr(NonNull::new_unchecked(applied), Private)
}
}
/// # Type information
///
/// Every value is guaranteed to have a [`DataType`]. This contains all of the value's type
/// information.
impl<'scope, 'data> Value<'scope, 'data> {
#[julia_version(until = "1.9")]
/// Returns the `DataType` of this value.
#[inline]
pub fn datatype(self) -> DataType<'scope> {
// Safety: the pointer points to valid data, every value can be converted to a tagged
// value.
unsafe {
let header = NonNull::new_unchecked(jl_sys::jl_astaggedvalue(self.unwrap(Private)))
.as_ref()
.__bindgen_anon_1
.header;
let ptr = (header & !15usize) as *mut jl_value_t;
DataType::wrap_non_null(NonNull::new_unchecked(ptr.cast()), Private)
}
}
#[julia_version(since = "1.10")]
#[inline]
/// Returns the `DataType` of this value.
pub fn datatype(self) -> DataType<'scope> {
// Safety: the pointer points to valid data, every value has a type.
unsafe {
let self_ptr = self.unwrap(Private);
let ty = jl_sys::jlrs_typeof(self_ptr);
DataType::wrap_non_null(NonNull::new_unchecked(ty), Private)
}
}
/// Returns the name of this value's [`DataType`] as a string slice.
#[inline]
pub fn datatype_name(self) -> JlrsResult<&'scope str> {
// Safety: the pointer points to valid data, the C API function
// is called with a valid argument.
unsafe {
let type_name = jl_typeof_str(self.unwrap(Private));
let type_name_ref = CStr::from_ptr(type_name);
Ok(type_name_ref.to_str().map_err(JlrsError::other)?)
}
}
}
/// # Type checking
///
/// Many properties of Julia types can be checked, including whether instances of the type are
/// mutable, if the value is an array, and so on. The method [`Value::is`] can be used to perform
/// these checks. All these checks implement the [`Typecheck`] trait. If the type that implements
/// this trait also implements [`ValidLayout`], the typecheck indicates whether or not the value
/// can be cast to or unboxed as that type.
impl Value<'_, '_> {
/// Performs the given typecheck:
///
/// ```
/// # use jlrs::prelude::*;
/// # use jlrs::util::test::JULIA;
/// # fn main() {
/// # JULIA.with(|j| {
/// # let mut julia = j.borrow_mut();
/// # let mut frame = StackFrame::new();
/// # let mut julia = julia.instance(&mut frame);
/// julia
/// .scope(|mut frame| {
/// let i = Value::new(&mut frame, 2u64);
/// assert!(i.is::<u64>());
/// Ok(())
/// })
/// .unwrap();
/// # });
/// # }
/// ```
///
/// A full list of supported checks can be found [here].
///
/// [`JuliaStruct`]: crate::data::managed::traits::julia_struct::JuliaStruct
/// [here]: ../../../layout/typecheck/trait.Typecheck.html#implementors
#[inline]
pub fn is<T: Typecheck>(self) -> bool {
self.datatype().is::<T>()
}
/// Returns true if the value is an array with elements of type `T`.
#[inline]
pub fn is_array_of<T: ValidField>(self) -> bool {
match self.cast::<Array>() {
Ok(arr) => arr.contains::<T>(),
Err(_) => false,
}
}
/// Returns true if `self` is a subtype of `sup`.
#[inline]
pub fn subtype(self, sup: Value) -> bool {
// Safety: the pointers point to valid data, the C API function
// is called with valid arguments.
unsafe { jl_subtype(self.unwrap(Private), sup.unwrap(Private)) != 0 }
}
/// Returns true if `self` is the type of a `DataType`, `UnionAll`, `Union`, or `Union{}` (the
/// bottom type).
#[inline]
pub fn is_kind(self) -> bool {
// Safety: this method can only be called from a thread known to Julia, its lifetime is
// never used
let global = unsafe { Unrooted::new() };
let ptr = self.unwrap(Private);
ptr == DataType::datatype_type(&global).unwrap(Private).cast()
|| ptr == DataType::unionall_type(&global).unwrap(Private).cast()
|| ptr == DataType::uniontype_type(&global).unwrap(Private).cast()
|| ptr == DataType::typeofbottom_type(&global).unwrap(Private).cast()
}
/// Returns true if the value is a type, ie a `DataType`, `UnionAll`, `Union`, or `Union{}`
/// (the bottom type).
#[inline]
pub fn is_type(self) -> bool {
Value::is_kind(self.datatype().as_value())
}
/// Returns true if `self` is of type `ty`.
#[inline]
pub fn isa(self, ty: Value) -> bool {
// Safety: the pointers point to valid data, the C API function
// is called with valid arguments.
unsafe { jl_isa(self.unwrap(Private), ty.unwrap(Private)) != 0 }
}
}
/// These methods let you track a `Value`, while it's tracked it's internal pointer is
/// dereferenced and you can access its contents directly.
///
/// Tracking works with a ledger that's shared between all active instances of jlrs. This ledger
/// contains a list of all active borrows, which lets it be used to prevent mutable aliasing.
/// Unfortunately, this system isn't perfect, it's unaware of how this data is used in Julia. It's
/// your responsibility that you only try to access data which isn't being used by some task
/// running in the background. The raw ledger API is available in `JlrsCore.Ledger`, you can prevent
/// mutable access to data by tracking from Julia by calling these functions. If you do so, you
/// should use a finalizer to ensure the borrow is removed from the ledger when the data is
/// finalized.
impl<'scope, 'data> Value<'scope, 'data> {
/// Track `self` immutably.
///
/// When this method is called on some `Value`, it's checked if the layout of `T` matches
/// that of the data and if the data is already mutably borrowed from Rust. If it's not, the
/// data is derefenced and returned as a `Tracked` which provides direct access to the
/// reference.
///
/// If the data is immutable the borrow isn't tracked by the ledger because it can't be
/// mutably borrowed.
#[inline]
pub fn track_shared<'borrow, T: ValidLayout>(
&'borrow self,
) -> JlrsResult<Tracked<'borrow, 'scope, 'data, T>> {
let ty = self.datatype();
if !T::valid_layout(ty.as_value()) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(AccessError::InvalidLayout { value_type })?;
}
if !ty.mutable() {
unsafe {
return Ok(Tracked::new(self));
}
}
unsafe {
Ledger::try_borrow_shared(*self)?;
Ok(Tracked::new(self))
}
}
/// Track `self` exclusively.
///
/// When this method is called on some `Value`, it's checked if the layout of `T` matches
/// that of the data and if the data is already borrowed from Rust. If it's not, the data is
/// mutably derefenced and returned as a `TrackedMut` which provides direct access to the
/// mutable reference.
///
/// Note that if `T` contains any references to Julia data, if such a reference is mutated
/// through `TrackedMut` you must call [`write_barrier`] after mutating it. This ensures the
/// garbage collector remains aware of old-generation objects pointing to young-generation
/// objects.
///
/// In general, it's recommended that only fields that contain no references to Julia data are
/// updated through `TrackedMut`.
///
/// Safety:
///
/// This method can only track references that exist in Rust code. It also gives unrestricted
/// mutable access to the contents of the data, which is inherently unsafe.
///
/// [`write_barrier`]: crate::memory::gc::write_barrier
#[inline]
pub unsafe fn track_exclusive<'borrow, T: ValidLayout>(
&'borrow mut self,
) -> JlrsResult<TrackedMut<'borrow, 'scope, 'data, T>> {
let ty = self.datatype();
if !ty.mutable() {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(TypeError::Immutable { value_type })?;
}
if !T::valid_layout(ty.as_value()) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(AccessError::InvalidLayout { value_type })?;
}
Ledger::try_borrow_exclusive(*self)?;
Ok(TrackedMut::new(self))
}
/// Returns `true` if `self` is currently tracked.
#[inline]
pub fn is_tracked(self) -> JlrsResult<bool> {
Ledger::is_borrowed(self)
}
/// Returns `true` if `self` is currently tracked.
#[inline]
pub fn is_tracked_shared(self) -> JlrsResult<bool> {
Ledger::is_borrowed_shared(self)
}
/// Returns `true` if `self` is currently mutably tracked.
#[inline]
pub fn is_tracked_exclusive(self) -> JlrsResult<bool> {
Ledger::is_borrowed_exclusive(self)
}
}
impl ValueUnbound {
/// Track `self` immutably.
///
/// This method is equivalent to [`Value::track_shared`] except it takes `self` by value and
/// can only be used with `ValueUnbound`. This is intended to be used from `ccall`able
/// functions that take a [`Value`] and operate on its contents in another thread.
///
/// Because `T: Send`, it's not possible to track types that contain references to Julia data.
///
/// Safety:
///
/// The returned instance of `Tracked` must only be used in the `ccall`ed function and the
/// `AsyncCallback`.
#[inline]
pub unsafe fn track_shared_unbound<T: ValidLayout + Send>(
self,
) -> JlrsResult<Tracked<'static, 'static, 'static, T>> {
let ty = self.datatype();
if !T::valid_layout(ty.as_value()) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(AccessError::InvalidLayout { value_type })?;
}
unsafe {
Ledger::try_borrow_shared(self)?;
Ok(Tracked::new_owned(self))
}
}
/// Track `self` exclusively.
///
/// This method is equivalent to [`Value::track_exclusive`] except it takes `self` by value
/// and can only be used with `ValueUnbound`. This is intended to be used from `ccall`able
/// functions that take a [`Value`] and operate on its contents in another thread.
///
/// Because `T: Send`, it's not possible to track types that contain references to Julia data.
///
/// Safety:
///
/// The returned instance of `TrackedMut` must only be used in the `ccall`ed function and the
/// `AsyncCallback`.
#[inline]
pub unsafe fn track_exclusive_unbound<T: ValidLayout + Send>(
self,
) -> JlrsResult<TrackedMut<'static, 'static, 'static, T>> {
let ty = self.datatype();
if !ty.mutable() {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(TypeError::Immutable { value_type })?;
}
if !T::valid_layout(ty.as_value()) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
Err(AccessError::InvalidLayout { value_type })?;
}
Ledger::try_borrow_exclusive(self)?;
Ok(TrackedMut::new_owned(self))
}
}
/// # Lifetime management
///
/// Values have two lifetimes, `'scope` and `'data`. The first ensures that a value can only be
/// used while it's rooted, the second ensures that values that (might) borrow array data from
/// Rust are also restricted by the lifetime of that borrow. This second restriction can be
/// relaxed with [`Value::assume_owned`] if it doesn't borrow any data from Rust.
impl<'scope, 'data> Value<'scope, 'data> {
/// If you call a Julia function with one or more borrowed arrays as arguments, its result can
/// only be used when all the borrows are active. If this result doesn't contain any borrowed
/// data this function can be used to relax its second lifetime to `'static`.
///
/// Safety: The value must not contain any data borrowed from Rust.
#[inline]
pub unsafe fn assume_owned(self) -> Value<'scope, 'static> {
Value::wrap_non_null(self.unwrap_non_null(Private), Private)
}
}
/// # Conversions
///
/// There are two ways to convert a [`Value`] to some other type. The first is casting, which is
/// used to convert a [`Value`] to the appropriate managed type. For example, if the
/// [`Value`] is a Julia array it can be cast to [`Array`]. Because this only involves a pointer
/// cast it's always possible to convert a managed type to a [`Value`] by calling
/// [`Managed::as_value`]. The second way is unboxing, which is used to copy the data the
/// [`Value`] points to to Rust. If a [`Value`] is a `UInt8`, it can be unboxed as a `u8`. By
/// default, jlrs can unbox the default primitive types and Julia strings, but the [`Unbox`] trait
/// can be implemented for other types. It's recommended that you use JlrsReflect.jl to do so.
/// Unlike casting, unboxing dereferences the pointer. As a result it loses its header, so an
/// unboxed value can't be used as a [`Value`] again without reallocating it.
impl<'scope, 'data> Value<'scope, 'data> {
/// Cast the value to a managed type `T`. Returns an error if the conversion is invalid.
#[inline]
pub fn cast<T: Managed<'scope, 'data> + Typecheck>(self) -> JlrsResult<T> {
if self.is::<T>() {
// Safety: self.is::<T>() returning true guarantees this is safe
unsafe { Ok(self.cast_unchecked()) }
} else {
Err(AccessError::InvalidLayout {
value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
}
/// Cast the value to a managed type `T` without checking if this conversion is valid.
///
/// Safety: You must guarantee `self.is::<T>()` would have returned `true`.
#[inline]
pub unsafe fn cast_unchecked<T: Managed<'scope, 'data>>(self) -> T {
T::from_value_unchecked(self, Private)
}
/// Unbox the contents of the value as the output type associated with `T`. Returns an error
/// if the layout of `T::Output` is incompatible with the layout of the type in Julia.
#[inline]
pub fn unbox<T: Unbox + Typecheck>(self) -> JlrsResult<T::Output> {
if !self.is::<T>() {
Err(AccessError::InvalidLayout {
value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?;
}
// Safety: self.is::<T>() returning true guarantees this is safe
unsafe { Ok(T::unbox(self)) }
}
/// Unbox the contents of the value as the output type associated with `T` without checking
/// if the layout of `T::Output` is compatible with the layout of the type in Julia.
///
/// Safety: You must guarantee `self.is::<T>()` would have returned `true`.
#[inline]
pub unsafe fn unbox_unchecked<T: Unbox>(self) -> T::Output {
T::unbox(self)
}
/// Convert this value to a typed value if this value is an instance of the constructed type.
pub fn as_typed<'target, T: ConstructType, Tgt: Target<'target>>(
self,
target: &Tgt,
) -> JlrsResult<TypedValue<'scope, 'data, T>> {
target.with_local_scope::<_, _, 1>(|_, mut frame| {
let ty = T::construct_type(&mut frame);
if self.isa(ty) {
unsafe { Ok(TypedValue::<T>::from_value_unchecked(self)) }
} else {
Err(TypeError::NotA {
value: self.display_string_or("<Cannot display value>"),
field_type: ty.display_string_or("<Cannot display type>"),
})?
}
})
}
/// Convert this value to a typed value without checking if the conversion is valid.
///
/// Safety: the converted value must be an instance of the constructed type.
#[inline]
pub unsafe fn as_typed_unchecked<T: ConstructType>(self) -> TypedValue<'scope, 'data, T> {
TypedValue::<T>::from_value_unchecked(self)
}
/// Returns a pointer to the data, this is useful when the output type of `Unbox` is different
/// than the implementation type and you have to write a custom unboxing function. It's your
/// responsibility this pointer is used correctly.
#[inline]
pub fn data_ptr(self) -> NonNull<c_void> {
self.unwrap_non_null(Private).cast()
}
}
/// # Fields
///
/// Most Julia values have fields. For example, if the value is an instance of this struct:
///
/// ```julia
/// struct Example
/// fielda
/// fieldb::UInt32
/// end
/// ```
///
/// it will have two fields, `fielda` and `fieldb`. The first field is a pointer field, the second
/// is stored inline as a `u32`. It's possible to safely access the raw contents of these fields
/// with the method [`Value::field_accessor`]. The first field can be accessed as a [`ValueRef`],
/// the second as a `u32`.
impl<'scope, 'data> Value<'scope, 'data> {
/// Returns the field names of this value as a slice of `Symbol`s.
#[inline]
pub fn field_names(self) -> &'scope [Symbol<'scope>] {
// Symbol and SymbolRef have the same layout, and this data is non-null. Symbols are
// globally rooted.
unsafe { std::mem::transmute(self.datatype().field_names().data().as_slice()) }
}
/// Returns the number of fields the underlying Julia value has.
#[inline]
pub fn n_fields(self) -> usize {
self.datatype().n_fields().unwrap() as _
}
/// Returns an accessor to access the contents of this value without allocating temporary Julia data.
#[inline]
pub fn field_accessor(self) -> FieldAccessor<'scope, 'data> {
FieldAccessor::new(self)
}
/// Roots the field at index `idx` if it exists and returns it, or a
/// `JlrsError::AccessError` if the index is out of bounds.
pub fn get_nth_field<'target, T>(
self,
target: T,
idx: usize,
) -> JlrsResult<ValueData<'target, 'data, T>>
where
T: Target<'target>,
{
if idx >= self.n_fields() {
Err(AccessError::OutOfBoundsField {
idx,
n_fields: self.n_fields(),
value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
// Safety: the bounds check succeeded, the pointer points to valid data. The result is
// rooted immediately.
unsafe {
let fld_ptr = jl_get_nth_field(self.unwrap(Private), idx as _);
if fld_ptr.is_null() {
Err(AccessError::UndefRef)?;
}
Ok(target.data_from_ptr(NonNull::new_unchecked(fld_ptr), Private))
}
}
/// Returns the field at index `idx` if it's a pointer field.
///
/// If the field doesn't exist or if the field can't be referenced because its data is stored
/// inline, a `JlrsError::AccessError` is returned.
pub fn get_nth_field_ref(self, idx: usize) -> JlrsResult<ValueRef<'scope, 'data>> {
let ty = self.datatype();
if idx >= ty.n_fields().unwrap() as _ {
Err(AccessError::OutOfBoundsField {
idx,
n_fields: self.n_fields(),
value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
// Safety: the bounds check succeeded, the pointer points to valid data. All C API
// functions are called with valid arguments. The result is rooted immediately.
unsafe {
if !jl_field_isptr(ty.unwrap(Private), idx as _) {
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE);
let field_name = if let Some(field_name) = self.field_names().get(idx) {
field_name
.as_str()
.unwrap_or("<Cannot display field name>")
.to_string()
} else {
format!("{}", idx)
};
Err(AccessError::NotAPointerField {
value_type: value_type,
field_name,
})?
}
Ok(ValueRef::wrap(NonNull::new_unchecked(
jl_get_nth_field_noalloc(self.unwrap(Private), idx),
)))
}
}
/// Roots the field with the name `field_name` if it exists and returns it, or a
/// `JlrsError::AccessError` if there's no field with that name.
pub fn get_field<'target, N, T>(
self,
target: T,
field_name: N,
) -> JlrsResult<ValueData<'target, 'data, T>>
where
N: ToSymbol,
T: Target<'target>,
{
// Safety: the pointer points to valid data, the C API function is called with valid
// arguments, the result is rooted immediately.
unsafe {
let symbol = field_name.to_symbol_priv(Private);
let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);
if idx < 0 {
Err(AccessError::NoSuchField {
type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
})?
}
let fld_ptr = jl_get_nth_field(self.unwrap(Private), idx as _);
if fld_ptr.is_null() {
Err(AccessError::UndefRef)?;
}
Ok(target.data_from_ptr(NonNull::new_unchecked(fld_ptr), Private))
}
}
/// Returns the field with the name `field_name` if it's a pointer field.
///
/// If the field doesn't exist or if the field can't be referenced because its data is stored
/// inline, a `JlrsError::AccessError` is returned.
pub fn get_field_ref<N>(self, field_name: N) -> JlrsResult<Option<ValueRef<'scope, 'data>>>
where
N: ToSymbol,
{
// Safety: the pointer points to valid data. All C API functions are called with valid
// arguments.
unsafe {
let symbol = field_name.to_symbol_priv(Private);
let ty = self.datatype();
let idx = jl_field_index(ty.unwrap(Private), symbol.unwrap(Private), 0);
if idx < 0 {
Err(AccessError::NoSuchField {
type_name: ty.display_string_or(CANNOT_DISPLAY_TYPE),
field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
})?
}
if !jl_field_isptr(ty.unwrap(Private), idx as _) {
let idx = idx as usize;
let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE);
let field_name = self.field_names()[idx]
.as_str()
.unwrap_or("<Cannot display field name>")
.to_string();
Err(AccessError::NotAPointerField {
value_type: value_type,
field_name,
})?
}
let ptr = jl_get_nth_field_noalloc(self.unwrap(Private), idx as _);
if ptr.is_null() {
Ok(None)
} else {
Ok(Some(ValueRef::wrap(NonNull::new_unchecked(ptr))))
}
}
}
/// Set the value of the field at `idx`. If Julia throws an exception it's caught, rooted in
/// the frame, and returned. If the index is out of bounds or the value is not a subtype of
/// the field an error is returned,
///
/// Safety: Mutating things that should absolutely not be mutated, like the fields of a
/// `DataType`, is not prevented.
pub unsafe fn set_nth_field<'target, T>(
self,
target: T,
idx: usize,
value: Value<'_, 'data>,
) -> JlrsResult<TargetException<'target, 'data, (), T>>
where
T: Target<'target>,
{
let n_fields = self.n_fields();
if n_fields <= idx {
Err(AccessError::OutOfBoundsField {
idx,
n_fields,
value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?;
}
let field_type = self
.datatype()
.field_types(&target)
.as_managed()
.data()
.as_slice()[idx as usize]
.unwrap()
.as_value();
let dt = value.datatype();
if !Value::subtype(dt.as_value(), field_type) {
Err(TypeError::NotASubtype {
field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
let callback = || jl_set_nth_field(self.unwrap(Private), idx, value.unwrap(Private));
let exc = |err: Value| err.unwrap_non_null(Private);
let res = match catch_exceptions(callback, exc) {
Ok(_) => Ok(()),
Err(e) => Err(e),
};
Ok(target.exception_from_ptr(res, Private))
}
/// Set the value of the field at `idx`. If Julia throws an exception the process aborts.
///
/// Safety: this method doesn't check if the type of the value is a subtype of the field's
/// type. Mutating things that should absolutely not be mutated, like the fields of a
/// `DataType`, is also not prevented.
#[inline]
pub unsafe fn set_nth_field_unchecked(self, idx: usize, value: Value<'_, 'data>) {
jl_set_nth_field(self.unwrap(Private), idx, value.unwrap(Private))
}
/// Set the value of the field with the name `field_name`. If Julia throws an exception it's
/// caught, rooted in the frame, and returned. If there's no field with the given name or the
/// value is not a subtype of the field an error is returned.
///
/// Safety: Mutating things that should absolutely not be mutated, like the fields of a
/// `DataType`, is not prevented.
pub unsafe fn set_field<'target, N, T>(
self,
target: T,
field_name: N,
value: Value<'_, 'data>,
) -> JlrsResult<TargetException<'target, 'data, (), T>>
where
N: ToSymbol,
T: Target<'target>,
{
let symbol = field_name.to_symbol_priv(Private);
let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);
if idx < 0 {
Err(AccessError::NoSuchField {
type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
})?
}
let field_type = self
.datatype()
.field_types(&target)
.as_managed()
.data()
.as_slice()[idx as usize]
.unwrap()
.as_value();
let dt = value.datatype();
if !Value::subtype(dt.as_value(), field_type) {
Err(TypeError::NotASubtype {
field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
let callback =
|| jl_set_nth_field(self.unwrap(Private), idx as usize, value.unwrap(Private));
let exc = |err: Value| err.unwrap_non_null(Private);
let res = match catch_exceptions(callback, exc) {
Ok(_) => Ok(()),
Err(e) => Err(e),
};
Ok(target.exception_from_ptr(res, Private))
}
/// Set the value of the field with the name `field_name`. If Julia throws an exception the
/// process aborts. If there's no field with the given name an error is returned.
///
/// Safety: this method doesn't check if the type of the value is a subtype of the field's
/// type. Mutating things that should absolutely not be mutated, like the fields of a
/// `DataType`, is also not prevented.
pub unsafe fn set_field_unchecked<N>(
self,
field_name: N,
value: Value<'_, 'data>,
) -> JlrsResult<()>
where
N: ToSymbol,
{
let symbol = field_name.to_symbol_priv(Private);
let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);
if idx < 0 {
Err(AccessError::NoSuchField {
type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
})?
}
Ok(jl_set_nth_field(
self.unwrap(Private),
idx as usize,
value.unwrap(Private),
))
}
}
/// # Evaluate Julia code
///
/// The easiest way to call Julia from Rust is by evaluating some Julia code directly. This can be
/// used to call simple functions without any arguments provided from Rust and to execute
/// using-statements.
impl Value<'_, '_> {
/// Execute a Julia command `cmd`, for example `Value::eval_string(&mut *frame, "sqrt(2)")` or
/// `Value::eval_string(&mut *frame, "using LinearAlgebra")`.
///
/// Safety: The command can't be checked for correctness, nothing prevents you from causing a
/// segmentation fault with a command like `unsafe_load(Ptr{Float64}(C_NULL))`.
#[inline]
pub unsafe fn eval_string<'target, C, T>(target: T, cmd: C) -> ValueResult<'target, 'static, T>
where
C: AsRef<str>,
T: Target<'target>,
{
let cmd = cmd.as_ref();
let cmd_cstring = CString::new(cmd).map_err(JlrsError::other).unwrap();
let cmd_ptr = cmd_cstring.as_ptr();
let res = jl_eval_string(cmd_ptr);
let exc = jl_exception_occurred();
let output = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(output, Private)
}
/// Execute a Julia command `cmd`. This is equivalent to `Value::eval_string`, but uses a
/// null-terminated string.
///
/// Safety: The command can't be checked for correctness, nothing prevents you from causing a
/// segmentation fault with a command like `unsafe_load(Ptr{Float64}(C_NULL))`.
#[inline]
pub unsafe fn eval_cstring<'target, C, T>(target: T, cmd: C) -> ValueResult<'target, 'static, T>
where
C: AsRef<CStr>,
T: Target<'target>,
{
let cmd = cmd.as_ref();
let cmd_ptr = cmd.as_ptr();
let res = jl_eval_string(cmd_ptr);
let exc = jl_exception_occurred();
let output = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(output, Private)
}
/// Calls `include` in the `Main` module in Julia, which evaluates the file's contents in that
/// module. This has the same effect as calling `include` in the Julia REPL.
///
/// Safety: The content of the file can't be checked for correctness, nothing prevents you
/// from causing a segmentation fault with code like `unsafe_load(Ptr{Float64}(C_NULL))`.
pub unsafe fn include<'target, 'current, 'borrow, P, Tgt>(
target: Tgt,
path: P,
) -> JlrsResult<ValueResult<'target, 'static, Tgt>>
where
P: AsRef<Path>,
Tgt: Target<'target>,
{
if path.as_ref().exists() {
return target.with_local_scope::<_, _, 1>(|target, mut frame| {
let path_jl_str = JuliaString::new(&mut frame, path.as_ref().to_string_lossy());
let include_func = Module::main(&frame)
.function(&frame, "include")?
.as_managed();
Ok(include_func.call1(target, path_jl_str.as_value()))
});
}
Err(IOError::NotFound {
path: path.as_ref().to_string_lossy().into(),
})?
}
}
/// # Equality
impl Value<'_, '_> {
/// Returns the object id of this value.
#[inline]
pub fn object_id(self) -> usize {
// Safety: the pointer points to valid data, the C API
// functions is called with a valid argument.
unsafe { jl_object_id(self.unwrap(Private)) }
}
/// Returns true if `self` and `other` are equal.
#[inline]
pub fn egal(self, other: Value) -> bool {
// Safety: the pointer points to valid data, the C API
// functions is called with a valid argument.
unsafe { jl_egal(self.unwrap(Private), other.unwrap(Private)) != 0 }
}
}
/// # Finalization
impl Value<'_, '_> {
/// Add a finalizer `f` to this value. The finalizer must be a Julia function, it will be
/// called when this value is about to be freed by the garbage collector.
///
/// Safety: the finalizer must be compatible with the data.
#[inline]
pub unsafe fn add_finalizer(self, f: Value<'_, 'static>) {
jl_gc_add_finalizer(self.unwrap(Private), f.unwrap(Private))
}
/// Add a finalizer `f` to this value. The finalizer must be an `extern "C"` function that
/// takes one argument, the value as a void pointer.
///
/// Safety: the finalizer must be compatible with the data.
#[inline]
pub unsafe fn add_ptr_finalizer(self, f: unsafe extern "C" fn(*mut c_void) -> ()) {
jl_gc_add_ptr_finalizer(get_tls(), self.unwrap(Private), f as *mut c_void)
}
}
/// # Constant values.
impl<'scope> Value<'scope, 'static> {
/// `Union{}`.
#[inline]
pub fn bottom_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_bottom_type), Private) }
}
/// `StackOverflowError`.
#[inline]
pub fn stackovf_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stackovf_exception), Private) }
}
/// `OutOfMemoryError`.
#[inline]
pub fn memory_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_memory_exception), Private) }
}
/// `ReadOnlyMemoryError`.
#[inline]
pub fn readonlymemory_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe {
Value::wrap_non_null(NonNull::new_unchecked(jl_readonlymemory_exception), Private)
}
}
/// `DivideError`.
#[inline]
pub fn diverror_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_diverror_exception), Private) }
}
/// `UndefRefError`.
#[inline]
pub fn undefref_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_undefref_exception), Private) }
}
/// `InterruptException`.
#[inline]
pub fn interrupt_exception<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_interrupt_exception), Private) }
}
/// An empty `Array{Any, 1}.
#[inline]
pub fn an_empty_vec_any<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_an_empty_vec_any), Private) }
}
/// An empty immutable String, "".
#[inline]
pub fn an_empty_string<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_an_empty_string), Private) }
}
/// `Array{UInt8, 1}`
#[inline]
pub fn array_uint8_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_uint8_type), Private) }
}
/// `Array{Any, 1}`
#[inline]
pub fn array_any_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_any_type), Private) }
}
/// `Array{Symbol, 1}`
#[inline]
pub fn array_symbol_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_symbol_type), Private) }
}
/// `Array{Int32, 1}`
#[inline]
pub fn array_int32_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_int32_type), Private) }
}
/// The empty tuple, `()`.
#[inline]
pub fn emptytuple<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_emptytuple), Private) }
}
/// The instance of `true`.
#[inline]
pub fn true_v<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_true), Private) }
}
/// The instance of `false`.
#[inline]
pub fn false_v<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_false), Private) }
}
/// The instance of `Nothing`, `nothing`.
#[inline]
pub fn nothing<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_nothing), Private) }
}
/// The handle to `stdout` as a Julia value.
#[inline]
pub fn stdout<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stdout_obj()), Private) }
}
/// The handle to `stderr` as a Julia value.
#[inline]
pub fn stderr<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stderr_obj()), Private) }
}
#[julia_version(since = "1.7")]
/// The `Pair` type
#[inline]
pub fn pair_type<T>(_: &T) -> Self
where
T: Target<'scope>,
{
// Safety: global constant
unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_pair_type), Private) }
}
}
impl<'data> Call<'data> for Value<'_, 'data> {
#[inline]
unsafe fn call0<'target, T>(self, target: T) -> ValueResult<'target, 'data, T>
where
T: Target<'target>,
{
let res = jl_call0(self.unwrap(Private));
let exc = jl_exception_occurred();
let res = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(res, Private)
}
#[inline]
unsafe fn call_unchecked<'target, 'value, V, T, const N: usize>(
self,
target: T,
args: V,
) -> ValueData<'target, 'data, T>
where
V: Values<'value, 'data, N>,
T: Target<'target>,
{
#[cfg(feature = "julia-1-6")]
let mut task = NonNull::new_unchecked(jl_sys::jl_get_ptls_states());
#[cfg(not(feature = "julia-1-6"))]
let mut task = NonNull::new_unchecked(jl_sys::jl_get_current_task());
let last_age = {
let task = task.as_mut();
let last_age = task.world_age;
task.world_age = jl_get_world_counter();
last_age
};
let args = args.as_slice(Private);
let v = jl_apply_generic(self.0.as_ptr(), args.as_ptr() as *mut _, args.len() as _);
{
let task = task.as_mut();
task.world_age = last_age;
}
target.data_from_ptr(NonNull::new_unchecked(v), Private)
}
#[inline]
unsafe fn call1<'target, T>(
self,
target: T,
arg0: Value<'_, 'data>,
) -> ValueResult<'target, 'data, T>
where
T: Target<'target>,
{
let res = jl_call1(self.unwrap(Private), arg0.unwrap(Private));
let exc = jl_exception_occurred();
let res = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(res, Private)
}
#[inline]
unsafe fn call2<'target, T>(
self,
target: T,
arg0: Value<'_, 'data>,
arg1: Value<'_, 'data>,
) -> ValueResult<'target, 'data, T>
where
T: Target<'target>,
{
let res = jl_call2(
self.unwrap(Private),
arg0.unwrap(Private),
arg1.unwrap(Private),
);
let exc = jl_exception_occurred();
let res = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(res, Private)
}
#[inline]
unsafe fn call3<'target, T>(
self,
target: T,
arg0: Value<'_, 'data>,
arg1: Value<'_, 'data>,
arg2: Value<'_, 'data>,
) -> ValueResult<'target, 'data, T>
where
T: Target<'target>,
{
let res = jl_call3(
self.unwrap(Private),
arg0.unwrap(Private),
arg1.unwrap(Private),
arg2.unwrap(Private),
);
let exc = jl_exception_occurred();
let res = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(res, Private)
}
#[inline]
unsafe fn call<'target, 'value, V, T, const N: usize>(
self,
target: T,
args: V,
) -> ValueResult<'target, 'data, T>
where
V: Values<'value, 'data, N>,
T: Target<'target>,
{
let args = args.as_slice(Private);
let n = args.len();
let res = jl_call(
self.unwrap(Private),
args.as_ptr() as *const _ as *mut _,
n as _,
);
let exc = jl_exception_occurred();
let res = if exc.is_null() {
Ok(NonNull::new_unchecked(res))
} else {
Err(NonNull::new_unchecked(exc))
};
target.result_from_ptr(res, Private)
}
}
impl<'value, 'data> ProvideKeywords<'value, 'data> for Value<'value, 'data> {
#[inline]
fn provide_keywords(
self,
kws: Value<'value, 'data>,
) -> JlrsResult<WithKeywords<'value, 'data>> {
if !kws.is::<NamedTuple>() {
let ty = kws.datatype().display_string_or(CANNOT_DISPLAY_TYPE);
Err(TypeError::NotANamedTuple { ty })?
}
Ok(WithKeywords::new(self, kws))
}
}
impl_debug!(Value<'_, '_>);
impl<'scope, 'data> ManagedPriv<'scope, 'data> for Value<'scope, 'data> {
type Wraps = jl_value_t;
type TypeConstructorPriv<'target, 'da> = Value<'target, 'da>;
const NAME: &'static str = "Value";
// Safety: `inner` must not have been freed yet, the result must never be
// used after the GC might have freed it.
#[inline]
unsafe fn wrap_non_null(inner: NonNull<Self::Wraps>, _: Private) -> Self {
Self(inner, PhantomData, PhantomData)
}
#[inline]
fn unwrap_non_null(self, _: Private) -> NonNull<Self::Wraps> {
self.0
}
}
/// A reference to a [`Value`] that has not been explicitly rooted.
pub type ValueRef<'scope, 'data> = Ref<'scope, 'data, Value<'scope, 'data>>;
/// A [`ValueRef`] with static lifetimes. This is a useful shorthand for signatures of
/// `ccall`able functions that return a [`Value`].
pub type ValueRet = Ref<'static, 'static, Value<'static, 'static>>;
/// A [`Value`] with static lifetimes.
///
/// This is a useful shorthand for signatures of `ccall`able functions that take a [`Value`] and
/// operate on its contents in another thread.
pub type ValueUnbound = Value<'static, 'static>;
unsafe impl ValidLayout for ValueRef<'_, '_> {
#[inline]
fn valid_layout(v: Value) -> bool {
if v.is::<DataType>() {
let dt = unsafe { v.cast_unchecked::<DataType>() };
!dt.is_inline_alloc()
} else if v.is::<UnionAll>() {
true
} else if v.is::<Union>() {
let u = unsafe { v.cast_unchecked::<Union>() };
!u.is_bits_union()
} else {
false
}
}
#[inline]
fn type_object<'target, Tgt: Target<'target>>(target: &Tgt) -> Value<'target, 'static> {
DataType::any_type(target).as_value()
}
const IS_REF: bool = true;
}
unsafe impl ValidLayout for Value<'static, 'static> {
#[inline]
fn valid_layout(v: Value) -> bool {
if v.is::<DataType>() {
let dt = unsafe { v.cast_unchecked::<DataType>() };
!dt.is_inline_alloc()
} else if v.is::<UnionAll>() {
true
} else if v.is::<Union>() {
let u = unsafe { v.cast_unchecked::<Union>() };
!u.is_bits_union()
} else {
false
}
}
#[inline]
fn type_object<'target, Tgt: Target<'target>>(target: &Tgt) -> Value<'target, 'static> {
DataType::any_type(target).as_value()
}
const IS_REF: bool = true;
}
unsafe impl ValidField for Option<ValueRef<'_, '_>> {
#[inline]
fn valid_field(v: Value) -> bool {
if v.is::<DataType>() {
let dt = unsafe { v.cast_unchecked::<DataType>() };
!dt.is_inline_alloc()
} else if v.is::<UnionAll>() {
true
} else if v.is::<Union>() {
let u = unsafe { v.cast_unchecked::<Union>() };
!u.is_bits_union()
} else {
false
}
}
}
use crate::memory::target::TargetType;
/// `Value` or `ValueRef`, depending on the target type `T`.
pub type ValueData<'target, 'data, T> =
<T as TargetType<'target>>::Data<'data, Value<'target, 'data>>;
/// `JuliaResult<Value>` or `JuliaResultRef<ValueRef>`, depending on the target type `T`.
pub type ValueResult<'target, 'data, T> = TargetResult<'target, 'data, Value<'target, 'data>, T>;
impl_ccall_arg_managed!(Value, 2);
impl_construct_type_managed!(Value, 2, jl_any_type);
unsafe fn check_union_equivalent<'target, L: ValidLayout, Tgt: Target<'target>>(
target: &Tgt,
idx: usize,
u: Union,
) -> JlrsResult<()> {
// TODO: Union{}?
// Field is a bits union. Check if the union in the layout and the constructed type contain
// the same types.
let type_obj = L::type_object(target);
if let Ok(type_obj) = type_obj.cast::<DataType>() {
let ft_in_layout = type_obj
.field_type_unchecked(target, idx)
.unwrap()
.as_value();
if ft_in_layout != u {
Err(TypeError::IncompatibleType {
element_type: u.display_string_or(CANNOT_DISPLAY_TYPE),
value_type: ft_in_layout.display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
} else if let Ok(type_obj) = type_obj.cast::<UnionAll>() {
let base_type_obj = type_obj.base_type();
let ft_in_layout = base_type_obj
.field_type_unchecked(target, idx)
.unwrap()
.as_value();
if ft_in_layout != u {
Err(TypeError::IncompatibleType {
element_type: u.display_string_or(CANNOT_DISPLAY_TYPE),
value_type: ft_in_layout.display_string_or(CANNOT_DISPLAY_TYPE),
})?
}
} else {
Err(TypeError::NotA {
value: type_obj.display_string_or(CANNOT_DISPLAY_TYPE),
field_type: "DataType or UnionAll".into(),
})?
}
Ok(())
}
unsafe fn check_field_isa<L: ValidLayout>(
ft: Value,
l_ptr: *const L,
offset: usize,
) -> JlrsResult<()> {
// Field is a pointer field, check if the provided value in that position is a valid instance
// of the field type.
if let Some(field) = l_ptr
.cast::<MaybeUninit<u8>>()
.add(offset)
.cast::<Value>()
.as_ref()
{
if !field.isa(ft) {
Err(TypeError::NotA {
value: field.display_string_or("<Cannot display value>"),
field_type: ft.display_string_or("<Cannot display type>"),
})?
}
}
Ok(())
}