| @@ -36,7 +36,9 @@ pub const MAIN_STACK: usize = 1 << 30; |
| 36 | 36 | #[derive(Clone)] |
| 37 | 37 | pub enum Val { |
| 38 | 38 | Unit, |
| 39 | + /// An `Int` within 63 bits; outside them it is a `BigInt` (`crate::int`). |
| 39 | 40 | Int(i64), |
| 41 | + BigInt(Rc<num_bigint::BigInt>), |
| 40 | 42 | Float(f64), |
| 41 | 43 | Str(Rc<str>), |
| 42 | 44 | Bytes(Rc<[u8]>), |
| @@ -77,6 +79,7 @@ impl fmt::Debug for Val { |
| 77 | 79 | match self { |
| 78 | 80 | Val::Unit => f.write_str("()"), |
| 79 | 81 | Val::Int(i) => write!(f, "{i}"), |
| 82 | + Val::BigInt(i) => write!(f, "{i}"), |
| 80 | 83 | Val::Float(x) => write!(f, "{x:?}"), |
| 81 | 84 | Val::Str(s) => write!(f, "{s:?}"), |
| 82 | 85 | Val::Bytes(b) => write!(f, "b\"{}\"", b.escape_ascii()), |
| @@ -112,7 +115,7 @@ impl fmt::Display for RtError { |
| 112 | 115 | |
| 113 | 116 | pub(crate) type R<T> = Result<T, RtError>; |
| 114 | 117 | |
| 115 | | −fn panic<T>(msg: impl Into<String>) -> R<T> { |
| 118 | +pub(crate) fn panic<T>(msg: impl Into<String>) -> R<T> { |
| 116 | 119 | Err(RtError::Panic(msg.into())) |
| 117 | 120 | } |
| 118 | 121 | |
| @@ -582,9 +585,10 @@ impl Interp { |
| 582 | 585 | } |
| 583 | 586 | |
| 584 | 587 | fn call_extern(&self, sym: &str, args: Vec<Val>) -> R<Val> { |
| 585 | | − let int = |v: &Val| match v { |
| 586 | | − Val::Int(i) => Ok(*i), |
| 587 | | − other => panic(format!("{sym}: expected an Int, got {other:?}")), |
| 588 | + // An Int used as a count or a bound (see `crate::int::saturate`). |
| 589 | + let int = |v: &Val| match crate::int::saturate(v) { |
| 590 | + Some(n) => Ok(n), |
| 591 | + None => panic(format!("{sym}: expected an Int, got {v:?}")), |
| 588 | 592 | }; |
| 589 | 593 | let float = |v: &Val| match v { |
| 590 | 594 | Val::Float(x) => Ok(*x), |
| @@ -594,33 +598,13 @@ impl Interp { |
| 594 | 598 | Val::Str(s) => Ok(s.clone()), |
| 595 | 599 | other => panic(format!("{sym}: expected a String, got {other:?}")), |
| 596 | 600 | }; |
| 597 | | − // Int is 63-bit (docs/runtime-abi.md): overflow panics. |
| 598 | | − let checked = |r: Option<i64>| match r.filter(|v| (-(1i64 << 62)..(1i64 << 62)).contains(v)) |
| 599 | | − { |
| 600 | | − Some(v) => Ok(Val::Int(v)), |
| 601 | | − None => panic("integer overflow"), |
| 602 | | − }; |
| 603 | 601 | let a = args.first(); |
| 604 | 602 | let b = args.get(1); |
| 605 | 603 | let arg = |v: Option<&Val>| v.cloned().unwrap_or(Val::Unit); |
| 606 | 604 | Ok(match sym { |
| 607 | | − "tl_int_eq" => bool_val(int(&arg(a))? == int(&arg(b))?), |
| 608 | | − "tl_int_compare" => order(int(&arg(a))?.cmp(&int(&arg(b))?)), |
| 609 | | − "tl_int_add" => checked(int(&arg(a))?.checked_add(int(&arg(b))?))?, |
| 610 | | − "tl_int_sub" => checked(int(&arg(a))?.checked_sub(int(&arg(b))?))?, |
| 611 | | − "tl_int_mul" => checked(int(&arg(a))?.checked_mul(int(&arg(b))?))?, |
| 612 | | − "tl_int_div" | "tl_int_rem" => { |
| 613 | | − let (x, y) = (int(&arg(a))?, int(&arg(b))?); |
| 614 | | − if y == 0 { |
| 615 | | − return panic("division by zero"); |
| 616 | | − } |
| 617 | | − checked(if sym == "tl_int_div" { |
| 618 | | − x.checked_div(y) |
| 619 | | − } else { |
| 620 | | − x.checked_rem(y) |
| 621 | | − })? |
| 605 | + s if s.starts_with("tl_int_") || s == "tl_hash_int" => { |
| 606 | + return crate::int::extern_call(s, &args); |
| 622 | 607 | } |
| 623 | | − "tl_int_show" => Val::Str(int(&arg(a))?.to_string().into()), |
| 624 | 608 | "tl_float_eq" => bool_val(float(&arg(a))? == float(&arg(b))?), |
| 625 | 609 | "tl_float_compare" => { |
| 626 | 610 | let (x, y) = (float(&arg(a))?, float(&arg(b))?); |
| @@ -664,13 +648,10 @@ impl Interp { |
| 664 | 648 | } |
| 665 | 649 | s if s.starts_with("tl_array_") => return array_extern(s, args), |
| 666 | 650 | "tl_string_parse_int" => { |
| 667 | | − let parsed = string(&arg(a))? |
| 668 | | − .parse::<i64>() |
| 669 | | − .ok() |
| 670 | | − .filter(|v| (-(1i64 << 62)..(1i64 << 62)).contains(v)); |
| 651 | + let parsed = crate::int::parse(&string(&arg(a))?); |
| 671 | 652 | Val::Tuple(Rc::new([ |
| 672 | 653 | bool_val(parsed.is_some()), |
| 673 | | − Val::Int(parsed.unwrap_or(0)), |
| 654 | + parsed.unwrap_or(Val::Int(0)), |
| 674 | 655 | ])) |
| 675 | 656 | } |
| 676 | 657 | s if s.starts_with("tl_net_") || s == "tl_http_parse_request" => { |
| @@ -687,7 +668,6 @@ impl Interp { |
| 687 | 668 | "tl_url_decode" => Val::Str(url_decode(&string(&arg(a))?).into()), |
| 688 | 669 | "tl_string_length" => Val::Int(string(&arg(a))?.chars().count() as i64), |
| 689 | 670 | "tl_string_debug" => Val::Str(format!("{:?}", &*string(&arg(a))?).into()), |
| 690 | | − "tl_hash_int" => Val::Int(mix(int(&arg(a))? as u64)), |
| 691 | 671 | "tl_hash_float" => Val::Int(mix(float(&arg(a))?.to_bits())), |
| 692 | 672 | "tl_hash_string" => Val::Int(hash_bytes(string(&arg(a))?.as_bytes())), |
| 693 | 673 | "tl_hash_combine" => { |
| @@ -732,7 +712,7 @@ impl Interp { |
| 732 | 712 | return panic("random.int: the bound must be positive"); |
| 733 | 713 | } |
| 734 | 714 | let x = u64::from_le_bytes(random_bytes(8).try_into().expect("8 bytes")); |
| 735 | | − Val::Int((x % below as u64) as i64) |
| 715 | + crate::int::from_i128(i128::from(x % below as u64)) |
| 736 | 716 | } |
| 737 | 717 | "tl_random_token" => { |
| 738 | 718 | let n = int(&arg(a))?.clamp(0, 1 << 20) as usize; |
| @@ -760,9 +740,9 @@ fn bytes_extern(sym: &str, args: &[Val]) -> R<Val> { |
| 760 | 740 | Some(Val::Bytes(b)) => Ok(b.clone()), |
| 761 | 741 | other => panic(format!("{sym}: expected Bytes, got {other:?}")), |
| 762 | 742 | }; |
| 763 | | − let int = |i: usize| match args.get(i) { |
| 764 | | − Some(Val::Int(n)) => Ok(*n), |
| 765 | | − other => panic(format!("{sym}: expected an Int, got {other:?}")), |
| 743 | + let int = |i: usize| match args.get(i).and_then(crate::int::saturate) { |
| 744 | + Some(n) => Ok(n), |
| 745 | + None => panic(format!("{sym}: expected an Int, got {:?}", args.get(i))), |
| 766 | 746 | }; |
| 767 | 747 | let new = |b: &[u8]| Val::Bytes(b.into()); |
| 768 | 748 | Ok(match sym { |
| @@ -815,12 +795,10 @@ fn bytes_extern(sym: &str, args: &[Val]) -> R<Val> { |
| 815 | 795 | "tl_bytes_from_list" => { |
| 816 | 796 | let mut out = Vec::new(); |
| 817 | 797 | for v in list_items(args.first().unwrap_or(&Val::Unit))? { |
| 818 | | − match v { |
| 819 | | − Val::Int(n) => match u8::try_from(n) { |
| 820 | | − Ok(b) => out.push(b), |
| 821 | | − Err(_) => return panic(format!("bytes.from_list: {n} is not a byte")), |
| 822 | | − }, |
| 823 | | − other => return panic(format!("{sym}: expected an Int, got {other:?}")), |
| 798 | + match crate::int::saturate(&v).map(u8::try_from) { |
| 799 | + Some(Ok(b)) => out.push(b), |
| 800 | + Some(Err(_)) => return panic(format!("bytes.from_list: {v:?} is not a byte")), |
| 801 | + None => return panic(format!("{sym}: expected an Int, got {v:?}")), |
| 824 | 802 | } |
| 825 | 803 | } |
| 826 | 804 | new(&out) |
| @@ -844,15 +822,18 @@ fn array_extern(sym: &str, args: Vec<Val>) -> R<Val> { |
| 844 | 822 | Val::Array(items) => Ok(items), |
| 845 | 823 | other => panic(format!("{sym}: expected an Array, got {other:?}")), |
| 846 | 824 | }; |
| 847 | | − let int = |v: &Val| match v { |
| 848 | | − Val::Int(n) => Ok(*n), |
| 849 | | − other => panic(format!("{sym}: expected an Int, got {other:?}")), |
| 825 | + let int = |v: &Val| match crate::int::saturate(v) { |
| 826 | + Some(n) => Ok(n), |
| 827 | + None => panic(format!("{sym}: expected an Int, got {v:?}")), |
| 850 | 828 | }; |
| 851 | 829 | // `i` as an index of `items`, if it is one. |
| 852 | | − let index = |items: &[Val], i: i64| usize::try_from(i).ok().filter(|i| *i < items.len()); |
| 853 | | − let out_of_range = |op: &str, items: &[Val], i: i64| { |
| 830 | + let index = |items: &[Val], i: &Val| { |
| 831 | + let i = usize::try_from(int(i)?).ok().filter(|i| *i < items.len()); |
| 832 | + Ok::<_, RtError>(i) |
| 833 | + }; |
| 834 | + let out_of_range = |op: &str, items: &[Val], i: &Val| { |
| 854 | 835 | panic(format!( |
| 855 | | − "{op}: index {i} out of range for length {}", |
| 836 | + "{op}: index {i:?} out of range for length {}", |
| 856 | 837 | items.len() |
| 857 | 838 | )) |
| 858 | 839 | }; |
| @@ -863,22 +844,22 @@ fn array_extern(sym: &str, args: Vec<Val>) -> R<Val> { |
| 863 | 844 | "tl_array_to_list" => list_val(array(a)?.iter().cloned()), |
| 864 | 845 | "tl_array_get" => { |
| 865 | 846 | let items = array(a)?; |
| 866 | | − match index(&items, int(&b)?) { |
| 847 | + match index(&items, &b)? { |
| 867 | 848 | Some(i) => data(1, "Some", vec![items[i].clone()]), |
| 868 | 849 | None => data(0, "None", Vec::new()), |
| 869 | 850 | } |
| 870 | 851 | } |
| 871 | 852 | "tl_array_at" => { |
| 872 | | − let (items, i) = (array(a)?, int(&b)?); |
| 873 | | − match index(&items, i) { |
| 853 | + let items = array(a)?; |
| 854 | + match index(&items, &b)? { |
| 874 | 855 | Some(i) => items[i].clone(), |
| 875 | | − None => return out_of_range("array.at", &items, i), |
| 856 | + None => return out_of_range("array.at", &items, &b), |
| 876 | 857 | } |
| 877 | 858 | } |
| 878 | 859 | "tl_array_set" => { |
| 879 | | − let (mut items, i) = (array(a)?, int(&b)?); |
| 880 | | − let Some(i) = index(&items, i) else { |
| 881 | | − return out_of_range("array.set", &items, i); |
| 860 | + let mut items = array(a)?; |
| 861 | + let Some(i) = index(&items, &b)? else { |
| 862 | + return out_of_range("array.set", &items, &b); |
| 882 | 863 | }; |
| 883 | 864 | Rc::make_mut(&mut items)[i] = next(); |
| 884 | 865 | Val::Array(items) |
| @@ -911,7 +892,7 @@ fn data(tag: u32, name: &str, fields: Vec<Val>) -> Val { |
| 911 | 892 | } |
| 912 | 893 | |
| 913 | 894 | /// `Lt`, `Eq` or `Gt`. |
| 914 | | −fn order(o: std::cmp::Ordering) -> Val { |
| 895 | +pub(crate) fn order(o: std::cmp::Ordering) -> Val { |
| 915 | 896 | match o { |
| 916 | 897 | std::cmp::Ordering::Less => data(0, "Lt", Vec::new()), |
| 917 | 898 | std::cmp::Ordering::Equal => data(1, "Eq", Vec::new()), |
| @@ -987,7 +968,7 @@ fn random_bytes(n: usize) -> Vec<u8> { |
| 987 | 968 | |
| 988 | 969 | /// A 64-bit mixer (splitmix64's finalizer), reduced to a non-negative Int |
| 989 | 970 | /// (62 bits), so hashes are valid 63-bit Ints. |
| 990 | | −fn mix(mut z: u64) -> i64 { |
| 971 | +pub(crate) fn mix(mut z: u64) -> i64 { |
| 991 | 972 | z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 992 | 973 | z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); |
| 993 | 974 | ((z ^ (z >> 31)) >> 2) as i64 |