From 9025ecb2ee3ed19865ee2078eb6c01f4660351e9 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 13 Apr 2023 15:13:31 +0200 Subject: Better error spans in `calc` --- src/eval/cast.rs | 46 +++++++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/eval/cast.rs b/src/eval/cast.rs index e2ae115f..b85d6e76 100644 --- a/src/eval/cast.rs +++ b/src/eval/cast.rs @@ -1,6 +1,6 @@ pub use typst_macros::{cast_from_value, cast_to_value, Cast}; -use std::num::{NonZeroI64, NonZeroUsize}; +use std::num::{NonZeroI64, NonZeroU64, NonZeroUsize}; use std::ops::Add; use ecow::EcoString; @@ -95,12 +95,8 @@ cast_to_value! { v: u32 => Value::Int(v as i64) } -cast_to_value! { - v: i32 => Value::Int(v as i64) -} - cast_from_value! { - usize, + u64, int: i64 => int.try_into().map_err(|_| { if int < 0 { "number must be at least zero" @@ -111,11 +107,11 @@ cast_from_value! { } cast_to_value! { - v: usize => Value::Int(v as i64) + v: u64 => Value::Int(v as i64) } cast_from_value! { - u64, + usize, int: i64 => int.try_into().map_err(|_| { if int < 0 { "number must be at least zero" @@ -126,14 +122,32 @@ cast_from_value! { } cast_to_value! { - v: u64 => Value::Int(v as i64) + v: usize => Value::Int(v as i64) +} + +cast_to_value! { + v: i32 => Value::Int(v as i64) } cast_from_value! { - NonZeroUsize, + NonZeroI64, + int: i64 => int.try_into() + .map_err(|_| if int == 0 { + "number must not be zero" + } else { + "number too large" + })?, +} + +cast_to_value! { + v: NonZeroI64 => Value::Int(v.get()) +} + +cast_from_value! { + NonZeroU64, int: i64 => int .try_into() - .and_then(|int: usize| int.try_into()) + .and_then(|int: u64| int.try_into()) .map_err(|_| if int <= 0 { "number must be positive" } else { @@ -142,12 +156,14 @@ cast_from_value! { } cast_to_value! { - v: NonZeroUsize => Value::Int(v.get() as i64) + v: NonZeroU64 => Value::Int(v.get() as i64) } cast_from_value! { - NonZeroI64, - int: i64 => int.try_into() + NonZeroUsize, + int: i64 => int + .try_into() + .and_then(|int: usize| int.try_into()) .map_err(|_| if int <= 0 { "number must be positive" } else { @@ -156,7 +172,7 @@ cast_from_value! { } cast_to_value! { - v: NonZeroI64 => Value::Int(v.get()) + v: NonZeroUsize => Value::Int(v.get() as i64) } cast_from_value! { -- cgit v1.2.3