mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 11:23:43 +01:00
Merge pull request #9070 from dotCooCoo/feat/scripts-unitvalue
Scripts: UnitValue measurements convert and calculate with their units
This commit is contained in:
11 files changed
+1119
-3
No files matched your search
@@ -2120,6 +2120,7 @@ impl Session {
|
||||
}));
|
||||
}
|
||||
(if fresh { realm.add_script_extensions() } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and
|
||||
//! `toSource`, and what of them one run keeps to itself.
|
||||
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize`, `toSource`
|
||||
//! and `UnitValue`, and what of them one run keeps to itself.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -140,6 +140,15 @@ fn to_source_writes_plain_data() {
|
||||
assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_values_convert_and_calculate_in_a_run() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "UnitValue('1 in').as('pt')"), json!(72));
|
||||
assert_eq!(value(&mut s, "String(new UnitValue(1, 'm') + new UnitValue(10, 'cm'))"), json!("1.1 m"));
|
||||
assert_eq!(value(&mut s, "[UnitValue(98, 'cm') < UnitValue(1, 'm'), UnitValue(98, 'cm') == 98]"), json!([true, true]));
|
||||
assert!(thrown(&mut s, "UnitValue(1, 'in').as('furlong')").starts_with("Error"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -43,8 +43,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// Reading a file or a folder, a file dialog and a message to the person do not change anything
|
||||
/// outside it.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder alert confirm localize prompt toSource"),
|
||||
("", "$ File Folder UnitValue alert confirm localize prompt toSource"),
|
||||
("Object.prototype.", "toSource"),
|
||||
("UnitValue.", "baseUnit baseUnit= length prototype"),
|
||||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||||
("localize.", "length"),
|
||||
("toSource.", "length"),
|
||||
(
|
||||
|
||||
@@ -246,6 +246,8 @@ pub(crate) enum Class {
|
||||
},
|
||||
/// A `.( )` filter in progress.
|
||||
XmlFilter(Box<XmlFilterState>),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
}
|
||||
|
||||
/// What an XML value is.
|
||||
@@ -322,6 +324,7 @@ impl Class {
|
||||
Class::String(_) => "String",
|
||||
Class::RegExp(_) => "RegExp",
|
||||
Class::Date(_) => "Date",
|
||||
Class::UnitValue(_) => "UnitValue",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -395,6 +398,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96;
|
||||
pub(crate) const XML_REF_BYTES: usize = 8;
|
||||
/// The estimated bytes of a namespace an XML node holds.
|
||||
pub(crate) const XML_NS_BYTES: usize = 48;
|
||||
/// The estimated bytes of the measurement a `UnitValue` object holds.
|
||||
pub(crate) const UNIT_VALUE_BYTES: usize = 32;
|
||||
/// The estimated bytes of a piece of code without its instructions, tables and strings.
|
||||
const CODE_BYTES: usize = 384;
|
||||
|
||||
@@ -680,6 +685,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
_ => {}
|
||||
}
|
||||
OBJECT_BYTES + PROP_BYTES * o.props.len() + extra
|
||||
|
||||
@@ -253,6 +253,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) install_error: Option<String>,
|
||||
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
|
||||
pub(crate) files: Option<crate::file_classes::Classes>,
|
||||
/// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the
|
||||
/// operators take no object as a measurement.
|
||||
pub(crate) unit_values: Option<crate::unit_value::Classes>,
|
||||
/// The clock and time zone `Date` reads.
|
||||
pub(crate) date_host: crate::date_builtins::DateHost,
|
||||
/// The bytes native code holds outside the heap's cells through [`HeldBytes`].
|
||||
@@ -518,6 +521,7 @@ impl Interp {
|
||||
held_bytes: 0,
|
||||
install_error: None,
|
||||
files: None,
|
||||
unit_values: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
flattened: std::cell::Cell::new(0),
|
||||
@@ -774,6 +778,7 @@ impl Interp {
|
||||
roots.objects.push(self.global);
|
||||
roots.objects.extend(self.intrinsics.all());
|
||||
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
|
||||
roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object));
|
||||
roots.envs.push(self.global_env);
|
||||
self.heap.collect(&roots);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
@@ -2873,6 +2878,11 @@ impl Interp {
|
||||
|
||||
fn op_unary(&mut self, op: Op) -> JsResult<()> {
|
||||
let v = self.peek(0)?;
|
||||
if self.unit_values.is_some()
|
||||
&& let Some(r) = crate::unit_value::unary(self, op, &v)?
|
||||
{
|
||||
return self.replace(1, r);
|
||||
}
|
||||
let r = match op {
|
||||
Op::Neg => Value::Number(-self.to_number(&v)?),
|
||||
Op::Plus | Op::ToNumber => Value::Number(self.to_number(&v)?),
|
||||
@@ -2892,6 +2902,12 @@ impl Interp {
|
||||
}
|
||||
|
||||
pub(crate) fn binary(&mut self, op: BinaryOp, a: &Value, b: &Value) -> JsResult<Value> {
|
||||
if self.unit_values.is_some()
|
||||
&& (matches!(a, Value::Object(_)) || matches!(b, Value::Object(_)))
|
||||
&& let Some(r) = crate::unit_value::binary(self, op, a, b)?
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
let num = |interp: &mut Self, f: fn(f64, f64) -> f64| -> JsResult<Value> {
|
||||
let x = interp.to_number(a)?;
|
||||
let y = interp.to_number(b)?;
|
||||
|
||||
@@ -69,6 +69,7 @@ mod regexp_builtins;
|
||||
mod regexp_vm;
|
||||
mod string_builtins;
|
||||
mod token;
|
||||
mod unit_value;
|
||||
mod value;
|
||||
mod xml;
|
||||
mod xml_builtins;
|
||||
@@ -213,4 +214,6 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod text_tests;
|
||||
#[cfg(test)]
|
||||
mod unit_value_tests;
|
||||
#[cfg(test)]
|
||||
mod xml_tests;
|
||||
@@ -529,6 +529,18 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the global constructor `UnitValue`, measurements with a magnitude and a unit, and has
|
||||
/// the arithmetic, comparison and unary operators calculate with its objects
|
||||
/// ([`crate::unit_value`]). A realm without it keeps the standard operators. A second call
|
||||
/// after one that succeeded changes nothing; after one that failed, it installs everything
|
||||
/// again.
|
||||
pub fn add_unit_values(&mut self) -> Result<(), RunError> {
|
||||
match crate::unit_value::install(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Defines the global function `name`, whose arguments arrive converted as `args` says
|
||||
/// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as
|
||||
/// it may a built-in function.
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
//! `UnitValue`, the measurement class the help page
|
||||
//! <https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/>
|
||||
//! describes, added to a realm by [`crate::Realm::add_unit_values`].
|
||||
//!
|
||||
//! An object holds a magnitude, a unit and the base that pixels and percentages convert through.
|
||||
//! The length units convert through exact ratios to the inch; a pixel is one base and 100% is one
|
||||
//! base. The base is an absolute length greater than 0, copied into each new object from
|
||||
//! `UnitValue.baseUnit` (1 point, which is 1/72 inch, until a script sets it), and an object's own `baseUnit` may
|
||||
//! replace it. A unit the table does not list, text that is not a number followed by a unit, and a
|
||||
//! magnitude that is not finite make an invalid object: its `type` is `?`, its `value` 0, and it
|
||||
//! cannot be converted or calculated with.
|
||||
//!
|
||||
//! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and
|
||||
//! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in
|
||||
//! its unit; with two, the right one is converted to the left one's unit first, with the left one's
|
||||
//! base for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the
|
||||
//! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its
|
||||
//! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not
|
||||
//! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all
|
||||
//! operators in a realm without `UnitValue`. A calculation whose result is not finite (a division
|
||||
//! by 0 included), a comparison with a number that is not finite, and a conversion of an invalid
|
||||
//! object or any of these operators applied to one throw a `RangeError`; a unit the table does not list throws an
|
||||
//! `Error`.
|
||||
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::builtins::{arg, constructor, method, native};
|
||||
use crate::bytecode::Op;
|
||||
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, Prop, UNIT_VALUE_BYTES, key};
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
|
||||
use crate::value::{Value, is_str_space, number_to_str, string_to_number, to_int32};
|
||||
|
||||
/// The units of the table, in its order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Unit {
|
||||
In,
|
||||
Ft,
|
||||
Yd,
|
||||
Mi,
|
||||
Mm,
|
||||
Cm,
|
||||
M,
|
||||
Km,
|
||||
Pt,
|
||||
Pc,
|
||||
Tpt,
|
||||
Tpc,
|
||||
Ci,
|
||||
Px,
|
||||
Percent,
|
||||
}
|
||||
|
||||
/// Each unit with its abbreviation, singular and plural names, and its length in inches as a ratio
|
||||
/// (0 for the units that convert through the base).
|
||||
const UNITS: [(Unit, &str, &str, &str, u64, u64); 15] = [
|
||||
(Unit::In, "in", "inch", "inches", 1, 1),
|
||||
(Unit::Ft, "ft", "foot", "feet", 12, 1),
|
||||
(Unit::Yd, "yd", "yard", "yards", 36, 1),
|
||||
(Unit::Mi, "mi", "mile", "miles", 63_360, 1),
|
||||
(Unit::Mm, "mm", "millimeter", "millimeters", 5, 127),
|
||||
(Unit::Cm, "cm", "centimeter", "centimeters", 50, 127),
|
||||
(Unit::M, "m", "meter", "meters", 5_000, 127),
|
||||
(Unit::Km, "km", "kilometer", "kilometers", 5_000_000, 127),
|
||||
(Unit::Pt, "pt", "point", "points", 1, 72),
|
||||
(Unit::Pc, "pc", "pica", "picas", 1, 6),
|
||||
(Unit::Tpt, "tpt", "traditional point", "traditional points", 100, 7_227),
|
||||
(Unit::Tpc, "tpc", "traditional pica", "traditional picas", 1_200, 7_227),
|
||||
(Unit::Ci, "ci", "cicero", "ciceros", 111, 625),
|
||||
(Unit::Px, "px", "pixel", "pixels", 0, 0),
|
||||
(Unit::Percent, "%", "percent", "percent", 0, 0),
|
||||
];
|
||||
|
||||
/// The longest unit name in the table, in code units.
|
||||
const LONGEST_NAME: usize = 18;
|
||||
|
||||
/// The longest text the constructor reads as a magnitude and a unit, in code units; longer text
|
||||
/// makes an invalid object without being read.
|
||||
const LONGEST_TEXT: usize = 64;
|
||||
|
||||
impl Unit {
|
||||
fn row(self) -> Option<&'static (Unit, &'static str, &'static str, &'static str, u64, u64)> {
|
||||
UNITS.iter().find(|row| row.0 == self)
|
||||
}
|
||||
|
||||
fn abbreviation(self) -> &'static str {
|
||||
self.row().map_or("?", |row| row.1)
|
||||
}
|
||||
|
||||
/// The unit's length in inches as a ratio, `None` for pixels and percentages.
|
||||
fn inches(self) -> Option<(u64, u64)> {
|
||||
let &(_, _, _, _, n, d) = self.row()?;
|
||||
(n != 0).then_some((n, d))
|
||||
}
|
||||
|
||||
/// The unit with this abbreviation, singular or plural name.
|
||||
fn named(units: &[u16]) -> Option<Unit> {
|
||||
if units.is_empty() || units.len() > LONGEST_NAME {
|
||||
return None;
|
||||
}
|
||||
let name = String::from_utf16(units).ok()?;
|
||||
UNITS.iter().find(|(_, a, s, p, _, _)| name == *a || name == *s || name == *p).map(|row| row.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The length that pixels and percentages convert through: a finite magnitude greater than 0 in a
|
||||
/// unit with a length.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Base {
|
||||
value: f64,
|
||||
unit: Unit,
|
||||
}
|
||||
|
||||
/// 1/72 inch, kept as 1 point so that conversions through it are exact.
|
||||
const DEFAULT_BASE: Base = Base { value: 1.0, unit: Unit::Pt };
|
||||
|
||||
/// What a `UnitValue` object holds. `unit` is `None` for an invalid object.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Measure {
|
||||
value: f64,
|
||||
unit: Option<Unit>,
|
||||
base: Base,
|
||||
}
|
||||
|
||||
/// The prototype of `UnitValue` objects and the current `UnitValue.baseUnit`, kept by the realm.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Classes {
|
||||
proto: ObjId,
|
||||
base: Base,
|
||||
}
|
||||
|
||||
impl Classes {
|
||||
/// The object a collection keeps.
|
||||
pub(crate) fn object(&self) -> ObjId {
|
||||
self.proto
|
||||
}
|
||||
}
|
||||
|
||||
fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 {
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// The ratio of a length in unit `from` to the same length in unit `to`, as a reduced fraction.
|
||||
fn ratio(from: Unit, to: Unit) -> (f64, f64) {
|
||||
let (from, to) = (from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1)));
|
||||
// The products stay below 2^53, so the ratio's terms are exact.
|
||||
let (n, d) = (from.0 * to.1, from.1 * to.0);
|
||||
let g = greatest_common_divisor(n, d).max(1);
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
(((n / g) as f64), ((d / g) as f64))
|
||||
}
|
||||
|
||||
/// `x` as a significand in [0.5, 1) and a power of 2; zero, infinities and NaN as themselves.
|
||||
fn split(x: f64) -> (f64, i32) {
|
||||
if x == 0.0 || !x.is_finite() {
|
||||
return (x, 0);
|
||||
}
|
||||
let (x, shift) = if x.is_normal() { (x, 0) } else { (x * 2f64.powi(64), -64) };
|
||||
let bits = x.to_bits();
|
||||
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
|
||||
let exponent = ((bits >> 52) & 0x7ff) as i32 - 1022;
|
||||
(f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), exponent + shift)
|
||||
}
|
||||
|
||||
/// The product of `factors` divided by each of `divisors`, in that order. Each step rounds as
|
||||
/// plain multiplication and division do, but no step overflows or reaches 0 on the way, so only
|
||||
/// a result outside the range of numbers is infinite or 0.
|
||||
fn product(factors: &[f64], divisors: &[f64]) -> f64 {
|
||||
let (mut m, mut e) = (1.0, 0);
|
||||
for (&x, divide) in factors.iter().map(|x| (x, false)).chain(divisors.iter().map(|x| (x, true))) {
|
||||
let (xm, xe) = split(x);
|
||||
let (rm, re) = split(if divide { m / xm } else { m * xm });
|
||||
(m, e) = (rm, if divide { e - xe } else { e + xe } + re);
|
||||
}
|
||||
while e > 1000 {
|
||||
(m, e) = (m * 2f64.powi(1000), e - 1000);
|
||||
}
|
||||
while e < -1000 {
|
||||
(m, e) = (m * 2f64.powi(-1000), e + 1000);
|
||||
}
|
||||
m * 2f64.powi(e)
|
||||
}
|
||||
|
||||
fn invalid(i: &mut Interp, what: &str) -> Abrupt {
|
||||
i.throw(ErrorType::Range, &format!("{what}: an invalid UnitValue cannot be converted or calculated with"))
|
||||
}
|
||||
|
||||
fn finite_value(i: &mut Interp, what: &str) -> Abrupt {
|
||||
i.throw(ErrorType::Range, &format!("{what}: the value must be a finite number"))
|
||||
}
|
||||
|
||||
fn not_finite(i: &mut Interp, what: &str) -> Abrupt {
|
||||
i.throw(ErrorType::Range, &format!("{what}: the result is not a finite number"))
|
||||
}
|
||||
|
||||
/// The magnitude of `m` in unit `to`, through `m`'s own base.
|
||||
fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult<f64> {
|
||||
let Some(from) = m.unit else {
|
||||
return Err(invalid(i, what));
|
||||
};
|
||||
let base = m.base;
|
||||
let r = match (from, to) {
|
||||
(a, b) if a == b => m.value,
|
||||
(Unit::Px, Unit::Percent) => m.value * 100.0,
|
||||
(Unit::Percent, Unit::Px) => m.value / 100.0,
|
||||
(Unit::Px | Unit::Percent, _) => {
|
||||
let (n, d) = ratio(base.unit, to);
|
||||
if from == Unit::Px { product(&[m.value, base.value, n], &[d]) } else { product(&[m.value, base.value, n], &[100.0, d]) }
|
||||
}
|
||||
(_, Unit::Px | Unit::Percent) => {
|
||||
let (n, d) = ratio(from, base.unit);
|
||||
if to == Unit::Px { product(&[m.value, n], &[d, base.value]) } else { product(&[m.value, n, 100.0], &[d, base.value]) }
|
||||
}
|
||||
(_, _) => {
|
||||
let (n, d) = ratio(from, to);
|
||||
product(&[m.value, n], &[d])
|
||||
}
|
||||
};
|
||||
if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) }
|
||||
}
|
||||
|
||||
/// The measure of `v` when it is a `UnitValue` object.
|
||||
pub(crate) fn measure(i: &Interp, v: &Value) -> Option<Measure> {
|
||||
let o = v.as_object()?;
|
||||
match &i.heap.object(o)?.class {
|
||||
Class::UnitValue(m) => Some(**m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn this_measure(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Measure)> {
|
||||
if let (Some(o), Some(m)) = (this.as_object(), measure(i, this)) {
|
||||
return Ok((o, m));
|
||||
}
|
||||
Err(i.type_error(&format!("{what}: the object is not a UnitValue")))
|
||||
}
|
||||
|
||||
fn store(i: &mut Interp, o: ObjId, m: Measure) {
|
||||
if let Some(obj) = i.heap.object_mut(o)
|
||||
&& let Class::UnitValue(slot) = &mut obj.class
|
||||
{
|
||||
**slot = m;
|
||||
}
|
||||
}
|
||||
|
||||
fn classes(i: &Interp) -> JsResult<Classes> {
|
||||
i.unit_values.clone().ok_or_else(|| Abrupt::Internal("UnitValue is not installed".into()))
|
||||
}
|
||||
|
||||
/// A new `UnitValue` object holding `m`.
|
||||
fn make(i: &mut Interp, m: Measure) -> JsResult<Value> {
|
||||
let proto = classes(i)?.proto;
|
||||
i.reserve_heap(OBJECT_BYTES + UNIT_VALUE_BYTES)?;
|
||||
i.heap.bytes = i.heap.bytes.saturating_add(UNIT_VALUE_BYTES);
|
||||
Ok(Value::Object(i.heap.alloc_object(Object::new(Class::UnitValue(Box::new(m)), Some(proto)))))
|
||||
}
|
||||
|
||||
/// The unit `v` names, or an `Error` naming `what`.
|
||||
fn unit_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult<Unit> {
|
||||
let s = i.to_str(v)?;
|
||||
let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) };
|
||||
unit.ok_or_else(|| i.throw(ErrorType::Error, &format!("{what}: the unit is not known")))
|
||||
}
|
||||
|
||||
/// A magnitude followed by a unit, with spaces around and between them allowed: `12 pt`,
|
||||
/// `-1.5e2 traditional points`, `10%`.
|
||||
fn parse_text(units: &[u16]) -> Option<(f64, Unit)> {
|
||||
let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len());
|
||||
let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |e| e + 1);
|
||||
let text = units.get(start..end)?;
|
||||
let digit = |u: u16| (u16::from(b'0')..=u16::from(b'9')).contains(&u);
|
||||
let at = |k: usize| text.get(k).copied().unwrap_or(0);
|
||||
let mut k = 0;
|
||||
if at(k) == u16::from(b'+') || at(k) == u16::from(b'-') {
|
||||
k += 1;
|
||||
}
|
||||
let mut digits = 0;
|
||||
while digit(at(k)) {
|
||||
k += 1;
|
||||
digits += 1;
|
||||
}
|
||||
if at(k) == u16::from(b'.') {
|
||||
k += 1;
|
||||
while digit(at(k)) {
|
||||
k += 1;
|
||||
digits += 1;
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
return None;
|
||||
}
|
||||
if at(k) == u16::from(b'e') || at(k) == u16::from(b'E') {
|
||||
let mut e = k + 1;
|
||||
if at(e) == u16::from(b'+') || at(e) == u16::from(b'-') {
|
||||
e += 1;
|
||||
}
|
||||
if digit(at(e)) {
|
||||
while digit(at(e)) {
|
||||
e += 1;
|
||||
}
|
||||
k = e;
|
||||
}
|
||||
}
|
||||
let (number, rest) = text.split_at_checked(k)?;
|
||||
let value = string_to_number(number);
|
||||
let u = rest.iter().position(|&u| !is_str_space(u)).unwrap_or(rest.len());
|
||||
let unit = Unit::named(rest.get(u..)?)?;
|
||||
value.is_finite().then_some((value, unit))
|
||||
}
|
||||
|
||||
/// `new UnitValue(value, unit)`, `new UnitValue("value unit")`, `new UnitValue(unitValue)` and the
|
||||
/// same without `new`.
|
||||
fn unit_value_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let base = classes(i)?.base;
|
||||
let bad = Measure { value: 0.0, unit: None, base };
|
||||
let first = arg(args, 0);
|
||||
let m = if args.len() >= 2 {
|
||||
let value = i.to_number(&first)?;
|
||||
let s = i.to_str(&arg(args, 1))?;
|
||||
let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) };
|
||||
match unit {
|
||||
Some(unit) if value.is_finite() => Measure { value, unit: Some(unit), base },
|
||||
_ => bad,
|
||||
}
|
||||
} else if let Some(m) = measure(i, &first) {
|
||||
m
|
||||
} else if matches!(first, Value::Undefined | Value::Number(_)) {
|
||||
bad
|
||||
} else {
|
||||
let s = i.to_str(&first)?;
|
||||
match if s.len() > LONGEST_TEXT { None } else { parse_text(&s.flat()) } {
|
||||
Some((value, unit)) => Measure { value, unit: Some(unit), base },
|
||||
None => bad,
|
||||
}
|
||||
};
|
||||
make(i, m)
|
||||
}
|
||||
|
||||
fn get_value(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (_, m) = this_measure(i, &this, "UnitValue.value")?;
|
||||
Ok(Value::Number(m.value))
|
||||
}
|
||||
|
||||
fn set_value(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_measure(i, &this, "UnitValue.value")?;
|
||||
let value = i.to_number(&arg(args, 0))?;
|
||||
if !value.is_finite() {
|
||||
return Err(finite_value(i, "UnitValue.value"));
|
||||
}
|
||||
// The conversion may have run script code that changed the object, so it is read again.
|
||||
let (_, mut m) = this_measure(i, &this, "UnitValue.value")?;
|
||||
m.value = value;
|
||||
store(i, o, m);
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
fn get_type(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (_, m) = this_measure(i, &this, "UnitValue.type")?;
|
||||
Ok(Value::str(m.unit.map_or("?", Unit::abbreviation)))
|
||||
}
|
||||
|
||||
fn set_type(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_measure(i, &this, "UnitValue.type")?;
|
||||
let unit = unit_arg(i, &arg(args, 0), "UnitValue.type")?;
|
||||
let (_, mut m) = this_measure(i, &this, "UnitValue.type")?;
|
||||
m.unit = Some(unit);
|
||||
store(i, o, m);
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// The base `v` gives: `null` gives the default, and any other value must be a valid `UnitValue`
|
||||
/// with a length greater than 0.
|
||||
fn base_arg(i: &mut Interp, v: &Value, null: Base, what: &str) -> JsResult<Base> {
|
||||
if matches!(v, Value::Null) {
|
||||
return Ok(null);
|
||||
}
|
||||
match measure(i, v) {
|
||||
Some(Measure { value, unit: Some(unit), .. }) if unit.inches().is_some() && value.is_finite() && value > 0.0 => Ok(Base { value, unit }),
|
||||
_ => Err(i.throw(ErrorType::Range, &format!("{what}: the base must be null or a UnitValue of a length greater than 0"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn base_object(i: &mut Interp, base: Base) -> JsResult<Value> {
|
||||
let class = classes(i)?.base;
|
||||
make(i, Measure { value: base.value, unit: Some(base.unit), base: class })
|
||||
}
|
||||
|
||||
fn get_base(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (_, m) = this_measure(i, &this, "UnitValue.baseUnit")?;
|
||||
base_object(i, m.base)
|
||||
}
|
||||
|
||||
fn set_base(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, mut m) = this_measure(i, &this, "UnitValue.baseUnit")?;
|
||||
let class = classes(i)?.base;
|
||||
m.base = base_arg(i, &arg(args, 0), class, "UnitValue.baseUnit")?;
|
||||
store(i, o, m);
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
fn get_class_base(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let base = classes(i)?.base;
|
||||
base_object(i, base)
|
||||
}
|
||||
|
||||
fn set_class_base(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let base = base_arg(i, &arg(args, 0), DEFAULT_BASE, "UnitValue.baseUnit")?;
|
||||
if let Some(c) = i.unit_values.as_mut() {
|
||||
c.base = base;
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// `unitValue.as(unit)`: the magnitude in `unit`, leaving the object as it is.
|
||||
fn unit_as(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
this_measure(i, &this, "UnitValue.as")?;
|
||||
let unit = unit_arg(i, &arg(args, 0), "UnitValue.as")?;
|
||||
let (_, m) = this_measure(i, &this, "UnitValue.as")?;
|
||||
convert(i, &m, unit, "UnitValue.as").map(Value::Number)
|
||||
}
|
||||
|
||||
/// `unitValue.convert(unit)`: changes the object to `unit` and gives `true`. A failure throws and
|
||||
/// leaves the object as it was.
|
||||
fn unit_convert(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
this_measure(i, &this, "UnitValue.convert")?;
|
||||
let unit = unit_arg(i, &arg(args, 0), "UnitValue.convert")?;
|
||||
let (o, mut m) = this_measure(i, &this, "UnitValue.convert")?;
|
||||
m.value = convert(i, &m, unit, "UnitValue.convert")?;
|
||||
m.unit = Some(unit);
|
||||
store(i, o, m);
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
/// `unitValue.toString()`: the magnitude and the abbreviation, `12 pt`; an invalid object gives
|
||||
/// `UnitValue 0.00000`.
|
||||
fn unit_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (_, m) = this_measure(i, &this, "UnitValue.toString")?;
|
||||
Ok(Value::str(&match m.unit {
|
||||
Some(unit) => format!("{} {}", number_to_str(m.value).to_rust_string(), unit.abbreviation()),
|
||||
None => format!("UnitValue {:.5}", m.value),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Defines the accessor `name` on `on`, not enumerable.
|
||||
fn accessor(i: &mut Interp, on: ObjId, name: &'static str, get: NativeFn, set: NativeFn) -> JsResult<()> {
|
||||
let g = native(i, name, get, 0, NativeKind::Plain, false)?;
|
||||
i.rooted(&[Value::Object(g)], |i| {
|
||||
let s = native(i, name, set, 1, NativeKind::Plain, false)?;
|
||||
i.define(on, key(name), Prop::Accessor { get: Some(g), set: Some(s), flags: CONFIGURABLE })
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds the global constructor `UnitValue` ([`crate::Realm::add_unit_values`]). A second call
|
||||
/// after one that succeeded changes nothing; after one that failed, it installs everything again.
|
||||
pub(crate) fn install(i: &mut Interp) -> JsResult<()> {
|
||||
install_with(i, define_members)
|
||||
}
|
||||
|
||||
/// [`install`] with `define` defining the members on the new prototype. When `define` fails, the
|
||||
/// realm is left without the operators, and the global `UnitValue` as it was before the call.
|
||||
pub(crate) fn install_with(i: &mut Interp, define: impl FnOnce(&mut Interp, ObjId) -> JsResult<()>) -> JsResult<()> {
|
||||
if i.unit_values.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let global = i.global;
|
||||
let name = key("UnitValue");
|
||||
let previous = i.get_own_property(global, &name)?;
|
||||
let held: Vec<Value> = match &previous {
|
||||
Some(Prop::Data { value, .. }) => vec![value.clone()],
|
||||
Some(Prop::Accessor { get, set, .. }) => get.iter().chain(set.iter()).map(|&o| Value::Object(o)).collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
i.rooted(&held, |i| {
|
||||
let object_proto = i.intrinsics.object_proto;
|
||||
i.reserve_heap(OBJECT_BYTES)?;
|
||||
let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
|
||||
// `unit_values` roots the prototype while the members are defined, and turns the operators on.
|
||||
i.unit_values = Some(Classes { proto, base: DEFAULT_BASE });
|
||||
let defined = define(i, proto);
|
||||
if defined.is_err() {
|
||||
i.unit_values = None;
|
||||
match previous {
|
||||
Some(p) => i.define(global, name, p)?,
|
||||
None => {
|
||||
i.object_mut(global)?.props.remove(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
defined
|
||||
})
|
||||
}
|
||||
|
||||
/// Defines the constructor, its `baseUnit` and the prototype's members.
|
||||
fn define_members(i: &mut Interp, proto: ObjId) -> JsResult<()> {
|
||||
let ctor = native(i, "UnitValue", unit_value_ctor, 2, NativeKind::Plain, true)?;
|
||||
constructor(i, "UnitValue", ctor, proto)?;
|
||||
accessor(i, ctor, "baseUnit", get_class_base, set_class_base)?;
|
||||
accessor(i, proto, "value", get_value, set_value)?;
|
||||
accessor(i, proto, "type", get_type, set_type)?;
|
||||
accessor(i, proto, "baseUnit", get_base, set_base)?;
|
||||
method(i, proto, "as", unit_as, 1)?;
|
||||
method(i, proto, "convert", unit_convert, 1)?;
|
||||
method(i, proto, "toString", unit_to_string, 0)
|
||||
}
|
||||
|
||||
/// Unary `op` on `v` when `v` is a `UnitValue`; `None` otherwise.
|
||||
pub(crate) fn unary(i: &mut Interp, op: Op, v: &Value) -> JsResult<Option<Value>> {
|
||||
let Some(m) = measure(i, v) else { return Ok(None) };
|
||||
if !matches!(op, Op::Neg | Op::Plus | Op::BitNot | Op::Not) {
|
||||
return Ok(None);
|
||||
}
|
||||
if m.unit.is_none() {
|
||||
return Err(invalid(i, "UnitValue"));
|
||||
}
|
||||
Ok(Some(match op {
|
||||
Op::Neg => Value::Number(-m.value),
|
||||
Op::Plus => Value::Number(m.value),
|
||||
Op::BitNot => Value::Number(f64::from(!to_int32(m.value))),
|
||||
_ => Value::Bool(m.value != 0.0),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Binary `op` on `a` and `b` when one is a `UnitValue` and the other a number or a `UnitValue`,
|
||||
/// for the arithmetic and comparison operators; `None` otherwise.
|
||||
pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsResult<Option<Value>> {
|
||||
let arithmetic = matches!(op, BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod);
|
||||
let comparison = matches!(op, BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq | BinaryOp::Eq | BinaryOp::NotEq);
|
||||
if !arithmetic && !comparison {
|
||||
return Ok(None);
|
||||
}
|
||||
let what = "UnitValue";
|
||||
let (x, y, owner) = match (measure(i, a), measure(i, b), a, b) {
|
||||
(Some(l), Some(r), _, _) => {
|
||||
let Some(unit) = l.unit else {
|
||||
return Err(invalid(i, what));
|
||||
};
|
||||
// Pixels and percentages of the left object are measured with its own base.
|
||||
let y = match unit {
|
||||
Unit::Px | Unit::Percent if r.base != l.base || !matches!(r.unit, Some(Unit::Px | Unit::Percent)) => match r.unit {
|
||||
Some(from @ (Unit::Px | Unit::Percent)) => {
|
||||
let (n, d) = ratio(r.base.unit, l.base.unit);
|
||||
let mut factors = vec![r.value, r.base.value, n];
|
||||
let mut divisors = vec![d, l.base.value];
|
||||
if from == Unit::Percent {
|
||||
divisors.push(100.0);
|
||||
}
|
||||
if unit == Unit::Percent {
|
||||
factors.push(100.0);
|
||||
}
|
||||
let y = product(&factors, &divisors);
|
||||
if !y.is_finite() {
|
||||
return Err(not_finite(i, what));
|
||||
}
|
||||
y
|
||||
}
|
||||
_ => convert(i, &Measure { base: l.base, ..r }, unit, what)?,
|
||||
},
|
||||
_ => convert(i, &r, unit, what)?,
|
||||
};
|
||||
(l.value, y, l)
|
||||
}
|
||||
(Some(l), None, _, Value::Number(n)) => (l.value, *n, l),
|
||||
(None, Some(r), Value::Number(n), _) => (*n, r.value, r),
|
||||
(l, r, _, _) => {
|
||||
if l.or(r).is_some_and(|m| m.unit.is_none()) {
|
||||
return Err(invalid(i, what));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
if owner.unit.is_none() {
|
||||
return Err(invalid(i, what));
|
||||
}
|
||||
if comparison {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return Err(finite_value(i, what));
|
||||
}
|
||||
// Without NaN, `x > y` is the negation of `x <= y` and `x >= y` the negation of `x < y`.
|
||||
return Ok(Some(Value::Bool(match op {
|
||||
BinaryOp::Lt => x < y,
|
||||
BinaryOp::LtEq => x <= y,
|
||||
BinaryOp::Gt => x > y,
|
||||
BinaryOp::GtEq => x >= y,
|
||||
BinaryOp::Eq => x == y,
|
||||
_ => x != y,
|
||||
})));
|
||||
}
|
||||
// A division by 0 gives an infinite result or NaN, which is refused below.
|
||||
let r = match op {
|
||||
BinaryOp::Add => x + y,
|
||||
BinaryOp::Sub => x - y,
|
||||
BinaryOp::Mul => x * y,
|
||||
BinaryOp::Div => x / y,
|
||||
_ => x % y,
|
||||
};
|
||||
if !r.is_finite() {
|
||||
return Err(not_finite(i, what));
|
||||
}
|
||||
make(i, Measure { value: r, ..owner }).map(Some)
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
//! `UnitValue` and the operators in a realm that has it.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn realm() -> Realm {
|
||||
let mut r = Realm::new();
|
||||
r.add_unit_values().unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn number(r: &mut Realm, source: &str) -> f64 {
|
||||
match r.run(source) {
|
||||
Ok(JsValue::Number(n)) => n,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(r: &mut Realm, source: &str) -> String {
|
||||
match r.run(source) {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn boolean(r: &mut Realm, source: &str) -> bool {
|
||||
match r.run(source) {
|
||||
Ok(JsValue::Bool(b)) => b,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the error `statement` throws, or `none`.
|
||||
fn error_name(r: &mut Realm, statement: &str) -> String {
|
||||
text(r, &format!("(function () {{ try {{ {statement}; return 'none'; }} catch (e) {{ return e.name; }} }})()"))
|
||||
}
|
||||
|
||||
fn close(got: f64, want: f64, what: &str) {
|
||||
assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}");
|
||||
}
|
||||
|
||||
/// `got` is within a millionth of `want`, which is not 0, however small `want` is.
|
||||
fn relative(got: f64, want: f64, what: &str) {
|
||||
assert!((got / want - 1.0).abs() <= 1e-6, "{what}: {got} is not {want}");
|
||||
}
|
||||
|
||||
/// Each length unit with its length in inches.
|
||||
const LENGTHS: [(&str, f64); 13] = [
|
||||
("in", 1.0),
|
||||
("ft", 12.0),
|
||||
("yd", 36.0),
|
||||
("mi", 63_360.0),
|
||||
("mm", 1.0 / 25.4),
|
||||
("cm", 1.0 / 2.54),
|
||||
("m", 1.0 / 0.0254),
|
||||
("km", 1000.0 / 0.0254),
|
||||
("pt", 1.0 / 72.0),
|
||||
("pc", 1.0 / 6.0),
|
||||
("tpt", 1.0 / 72.27),
|
||||
("tpc", 12.0 / 72.27),
|
||||
("ci", 12.7872 / 72.0),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_length_unit_converts_to_every_other_and_back() {
|
||||
let mut r = realm();
|
||||
for (from, a) in LENGTHS {
|
||||
for (to, b) in LENGTHS {
|
||||
let there = number(&mut r, &format!("UnitValue(3, '{from}').as('{to}')"));
|
||||
close(there, 3.0 * a / b, &format!("3 {from} in {to}"));
|
||||
let back = number(&mut r, &format!("UnitValue({there}, '{to}').as('{from}')"));
|
||||
close(back, 3.0, &format!("3 {from} through {to} and back"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_relations_are_exact() {
|
||||
let mut r = realm();
|
||||
for (source, want) in [
|
||||
("UnitValue(1, 'in').as('pt')", 72.0),
|
||||
("UnitValue(1, 'ft').as('in')", 12.0),
|
||||
("UnitValue(1, 'yd').as('ft')", 3.0),
|
||||
("UnitValue(1, 'mi').as('m')", 1609.344),
|
||||
("UnitValue(1, 'm').as('cm')", 100.0),
|
||||
("UnitValue(1, 'km').as('m')", 1000.0),
|
||||
("UnitValue(10, 'mm').as('cm')", 1.0),
|
||||
("UnitValue(2.54, 'cm').as('in')", 1.0),
|
||||
("UnitValue(1, 'pc').as('pt')", 12.0),
|
||||
("UnitValue(1, 'tpc').as('tpt')", 12.0),
|
||||
("UnitValue(72.27, 'tpt').as('in')", 1.0),
|
||||
("UnitValue(1, 'ci').as('pt')", 12.7872),
|
||||
("UnitValue(1, 'in').as('px')", 72.0),
|
||||
] {
|
||||
assert_eq!(number(&mut r, source), want, "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_are_named_by_abbreviation_singular_or_plural() {
|
||||
let mut r = realm();
|
||||
for (name, abbreviation) in [
|
||||
("inch", "in"),
|
||||
("inches", "in"),
|
||||
("feet", "ft"),
|
||||
("millimeter", "mm"),
|
||||
("centimeters", "cm"),
|
||||
("traditional point", "tpt"),
|
||||
("traditional picas", "tpc"),
|
||||
("ciceros", "ci"),
|
||||
("pixel", "px"),
|
||||
("percent", "%"),
|
||||
] {
|
||||
assert_eq!(text(&mut r, &format!("UnitValue(1, '{name}').type")), abbreviation, "{name}");
|
||||
assert_eq!(text(&mut r, &format!("UnitValue('2 {name}').type")), abbreviation, "2 {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_constructor_takes_a_number_and_unit_text_or_another_unit_value() {
|
||||
let mut r = realm();
|
||||
assert_eq!(text(&mut r, "String(new UnitValue(12, 'pt'))"), "12 pt");
|
||||
assert_eq!(text(&mut r, "String(UnitValue('12 cm'))"), "12 cm");
|
||||
assert_eq!(text(&mut r, "String(UnitValue(' -1.5e1 centimeters '))"), "-15 cm");
|
||||
assert_eq!(text(&mut r, "String(UnitValue('10%'))"), "10 %");
|
||||
assert_eq!(text(&mut r, "String(UnitValue('12', 'in'))"), "12 in");
|
||||
assert!(boolean(&mut r, "UnitValue(1, 'in') instanceof UnitValue"));
|
||||
assert_eq!(text(&mut r, "Object.prototype.toString.call(UnitValue(1, 'in'))"), "[object UnitValue]");
|
||||
let copy = "var a = UnitValue(5, 'px'); a.baseUnit = UnitValue(1, 'mm'); var b = UnitValue(a); a.value = 1; \
|
||||
[a === b, b.value, b.type, b.as('mm')].join()";
|
||||
assert_eq!(text(&mut r, copy), "false,5,px,5", "a copy is a new object with the same value, unit and base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_unit_or_text_makes_an_invalid_unit_value() {
|
||||
let mut r = realm();
|
||||
for source in [
|
||||
"UnitValue(12, 'furlong')",
|
||||
"UnitValue('12')",
|
||||
"UnitValue('pt')",
|
||||
"UnitValue('12 pt extra')",
|
||||
"UnitValue(12)",
|
||||
"UnitValue()",
|
||||
"UnitValue(NaN, 'pt')",
|
||||
"UnitValue(Infinity, 'pt')",
|
||||
"UnitValue(12, 'PT')",
|
||||
] {
|
||||
assert_eq!(text(&mut r, &format!("var u = {source}; u.type + ' ' + u.value")), "? 0", "{source}");
|
||||
assert_eq!(text(&mut r, &format!("String({source})")), "UnitValue 0.00000", "{source}");
|
||||
}
|
||||
for statement in [
|
||||
"UnitValue(1, 'zz').as('pt')",
|
||||
"UnitValue(1, 'zz').convert('pt')",
|
||||
"UnitValue(1, 'zz') + 1",
|
||||
"UnitValue(1, 'in') + UnitValue(1, 'zz')",
|
||||
"UnitValue('bad') == 0",
|
||||
"1 > UnitValue('bad')",
|
||||
"+UnitValue('bad')",
|
||||
"-UnitValue('bad')",
|
||||
"~UnitValue('bad')",
|
||||
"!UnitValue('bad')",
|
||||
"UnitValue('bad') + 'x'",
|
||||
"'x' < UnitValue('bad')",
|
||||
"UnitValue('bad') == null",
|
||||
] {
|
||||
assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_leaves_the_object_and_convert_changes_it() {
|
||||
let mut r = realm();
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.as('pt'), String(u)].join()"), "72,1 in");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.convert('pt'), String(u)].join()"), "true,72 pt");
|
||||
assert_eq!(error_name(&mut r, "UnitValue(1, 'in').as('furlong')"), "Error");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.convert('furlong'); } catch (e) {} String(u)"), "1 in");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.type = 'furlong'; } catch (e) {} String(u)"), "1 in");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); u.type = 'points'; u.value = 3; String(u)"), "3 pt");
|
||||
assert_eq!(error_name(&mut r, "UnitValue(1, 'in').value = NaN"), "RangeError");
|
||||
assert_eq!(error_name(&mut r, "UnitValue.prototype.as.call({}, 'pt')"), "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_percentages_convert_through_the_base() {
|
||||
let mut r = realm();
|
||||
assert_eq!(number(&mut r, "UnitValue(72, 'px').as('in')"), 1.0);
|
||||
assert_eq!(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(0.75, 'pt'); p.as('pt')"), 7.5);
|
||||
close(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(1/96, 'in'); p.as('in')"), 10.0 / 96.0, "10 px at 96 per inch");
|
||||
assert_eq!(text(&mut r, "String(UnitValue.baseUnit)"), "1 pt");
|
||||
assert_eq!(number(&mut r, "var p = UnitValue(40, '%'); p.baseUnit = UnitValue(10, 'ft'); p.as('ft')"), 4.0);
|
||||
assert_eq!(number(&mut r, "var m = UnitValue(10, 'm'); m.baseUnit = UnitValue(1, 'km'); m.as('%')"), 1.0);
|
||||
assert_eq!(number(&mut r, "var p = UnitValue(3, 'px'); p.baseUnit = UnitValue(2, 'pt'); p.as('%')"), 300.0);
|
||||
assert_eq!(number(&mut r, "var p = UnitValue(50, '%'); p.as('px')"), 0.5);
|
||||
let class = "var before = UnitValue(1, 'in'); UnitValue.baseUnit = UnitValue(0.5, 'pt'); \
|
||||
var after = UnitValue(1, 'in'); var r = [before.as('px'), after.as('px'), String(UnitValue.baseUnit.type)]; \
|
||||
UnitValue.baseUnit = null; r.push(UnitValue(1, 'in').as('px')); r.join()";
|
||||
assert_eq!(text(&mut r, class), "72,144,pt,72", "the class base applies to objects made after it is set, and null restores it");
|
||||
assert_eq!(number(&mut r, "var p = UnitValue(1, 'in'); p.baseUnit = UnitValue(1, 'cm'); p.baseUnit = null; p.as('px')"), 72.0);
|
||||
let large = "var p = UnitValue(100, '%'); p.baseUnit = UnitValue(1e308, 'pt'); var q = UnitValue(2, 'px'); \
|
||||
q.baseUnit = UnitValue(1e308, 'pt'); var l = UnitValue(1e308, 'km'); l.baseUnit = UnitValue(1e300, 'pt'); \
|
||||
[p.as('pt'), q.as('in'), l.as('px')].join()";
|
||||
let got: Vec<f64> = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect();
|
||||
close(got[0], 1e308, "100% of a large base");
|
||||
close(got[1], 1e308 / 72.0 * 2.0, "2 px of a large base in inches");
|
||||
close(got[2], 1e308 / 1e300 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_base_must_be_a_length_greater_than_zero() {
|
||||
let mut r = realm();
|
||||
for base in ["UnitValue(0, 'pt')", "UnitValue(-1, 'pt')", "UnitValue(1, 'px')", "UnitValue(1, '%')", "UnitValue(1, 'zz')"] {
|
||||
assert_eq!(error_name(&mut r, &format!("UnitValue.baseUnit = {base}")), "RangeError", "{base}");
|
||||
assert_eq!(error_name(&mut r, &format!("UnitValue(1, 'px').baseUnit = {base}")), "RangeError", "{base}");
|
||||
}
|
||||
assert_eq!(error_name(&mut r, "UnitValue.baseUnit = 5"), "RangeError");
|
||||
assert_eq!(error_name(&mut r, "UnitValue(1, 'px').baseUnit = '1 pt'"), "RangeError");
|
||||
assert_eq!(number(&mut r, "UnitValue(1, 'in').as('px')"), 72.0, "a refused base leaves the class base as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arithmetic_gives_a_new_unit_value_in_the_left_unit() {
|
||||
let mut r = realm();
|
||||
for (source, want) in [
|
||||
("UnitValue(1, 'm') + UnitValue(10, 'cm')", "1.1 m"),
|
||||
("UnitValue(10, 'cm') + UnitValue(1, 'm')", "110 cm"),
|
||||
("UnitValue(10, 'cm') * 20", "200 cm"),
|
||||
("20 * UnitValue(10, 'cm')", "200 cm"),
|
||||
("10 - UnitValue(3, 'pt')", "7 pt"),
|
||||
("UnitValue(10, 'pt') - 3", "7 pt"),
|
||||
("20 / UnitValue(4, 'pt')", "5 pt"),
|
||||
("UnitValue(20, 'pt') / 4", "5 pt"),
|
||||
("UnitValue(7, 'pt') % 4", "3 pt"),
|
||||
("UnitValue(1, 'in') - UnitValue(36, 'pt')", "0.5 in"),
|
||||
] {
|
||||
assert_eq!(text(&mut r, &format!("String({source})")), want, "{source}");
|
||||
}
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'pt'); u += 2; String(u)"), "3 pt", "compound assignment uses the operator");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); var v = u + 1; String(u)"), "1 in", "the operands do not change");
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(2, 'px'); u.baseUnit = UnitValue(1, 'mm'); (u * 3).as('mm') + ''"), "6", "the result keeps the base");
|
||||
assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_left_objects_base_measures_its_pixels_and_percentages() {
|
||||
let mut r = realm();
|
||||
let pair = "var l = UnitValue(1, 'px'); l.baseUnit = UnitValue(2, 'pt'); var m = UnitValue(1, 'px'); \
|
||||
m.baseUnit = UnitValue(4, 'pt'); var p = UnitValue(50, '%'); p.baseUnit = UnitValue(1, 'in');";
|
||||
assert_eq!(text(&mut r, &format!("{pair} String(l + UnitValue(1, 'in'))")), "37 px");
|
||||
assert_eq!(text(&mut r, &format!("{pair} String(l + m)")), "3 px");
|
||||
close(number(&mut r, &format!("{pair} (p + l).value")), 50.0 + 200.0 / 72.0, "2 pt as a percentage of 1 in");
|
||||
assert!(boolean(&mut r, &format!("{pair} l < m && m > l && l == UnitValue(2, 'pt')")));
|
||||
let large = "var b = UnitValue(0, 'px'); b.baseUnit = UnitValue(1e308, 'pt'); var c = UnitValue(1e300, 'px'); \
|
||||
c.baseUnit = UnitValue(1e10, 'pt'); [(b + UnitValue(1e304, 'km')).value, (b + c).value].join()";
|
||||
let got: Vec<f64> = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect();
|
||||
close(got[0], 1e304 / 1e308 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base");
|
||||
close(got[1], 1e300 / 1e308 * 1e10, "large pixels of one large base in pixels of another");
|
||||
let small = "var s = UnitValue(0, 'px'); s.baseUnit = UnitValue(1e-300, 'pt'); var t = UnitValue(1e-200, 'px'); \
|
||||
t.baseUnit = UnitValue(1e-200, 'pt'); (s + t).value";
|
||||
let units = "var u = UnitValue(0, 'px'); u.baseUnit = UnitValue(1e20, 'pt'); var v = UnitValue(1e308, 'px'); \
|
||||
v.baseUnit = UnitValue(1e10, 'km'); (u + v).value";
|
||||
close(number(&mut r, units), 1e298 * 1000.0 * 5000.0 / 127.0 * 72.0, "large pixels of a base in a larger unit");
|
||||
let apart = "var w = UnitValue(0, 'px'); w.baseUnit = UnitValue(7e-16, 'km'); var x = UnitValue(1e-20, 'px'); \
|
||||
x.baseUnit = UnitValue(1e308, 'pt'); (w + x).value";
|
||||
close(number(&mut r, apart), 1e288 / (1000.0 * 5000.0 / 127.0 * 72.0) / 7e-16, "bases too far apart for their ratio");
|
||||
relative(number(&mut r, small), 1e-100, "small pixels of one small base in pixels of another");
|
||||
let tiny = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-200, 'km'); var z = UnitValue(1e-320, 'px'); (y + z).value";
|
||||
relative(number(&mut r, tiny), 1e-320 * 1e200 / (1000.0 * 5000.0 / 127.0 * 72.0), "a tiny value in pixels of a tiny base");
|
||||
let tinier = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-320, 'pt'); var z = UnitValue(1e-320, 'px'); \
|
||||
z.baseUnit = UnitValue(1e-10, 'pt'); (y + z).value";
|
||||
relative(number(&mut r, tinier), 1e-10, "a tiny value of a small base in pixels of a tiny base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparisons_use_the_numbers_and_greater_is_the_negation() {
|
||||
let mut r = realm();
|
||||
for (source, want) in [
|
||||
("UnitValue(98, 'cm') < UnitValue(1, 'm')", true),
|
||||
("UnitValue(98, 'cm') < 1", false),
|
||||
("UnitValue(98, 'cm') == 98", true),
|
||||
("98 == UnitValue(98, 'cm')", true),
|
||||
("UnitValue(1, 'in') == UnitValue(72, 'pt')", true),
|
||||
("UnitValue(1, 'in') != UnitValue(72, 'pt')", false),
|
||||
("UnitValue(1, 'in') === UnitValue(72, 'pt')", false),
|
||||
("var u = UnitValue(1, 'in'); u === u", true),
|
||||
("UnitValue(1, 'in') <= UnitValue(72, 'pt')", true),
|
||||
("UnitValue(1, 'in') >= UnitValue(72, 'pt')", true),
|
||||
("UnitValue(1, 'in') > UnitValue(72, 'pt')", false),
|
||||
("UnitValue(1, 'in') > UnitValue(71, 'pt')", true),
|
||||
("UnitValue(1, 'in') >= UnitValue(73, 'pt')", false),
|
||||
("2 > UnitValue(1, 'pt')", true),
|
||||
("2 >= UnitValue(3, 'pt')", false),
|
||||
] {
|
||||
assert_eq!(boolean(&mut r, source), want, "{source}");
|
||||
}
|
||||
for statement in [
|
||||
"UnitValue(1, 'pt') < NaN",
|
||||
"UnitValue(1, 'pt') > NaN",
|
||||
"NaN == UnitValue(1, 'pt')",
|
||||
"UnitValue(1, 'pt') < Infinity",
|
||||
"UnitValue(1, 'in') < UnitValue(1, 'zz')",
|
||||
] {
|
||||
assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unary_operators_use_the_number() {
|
||||
let mut r = realm();
|
||||
assert_eq!(text(&mut r, "var u = UnitValue(2.5, 'pt'); [+u, -u, ~u, !u, !UnitValue(0, 'pt'), typeof u].join()"), "2.5,-2.5,-3,true,false,object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_that_are_not_finite_and_division_by_zero_throw() {
|
||||
let mut r = realm();
|
||||
for statement in [
|
||||
"UnitValue(1e308, 'pt') * 10",
|
||||
"UnitValue(1, 'pt') / 0",
|
||||
"1 / UnitValue(0, 'pt')",
|
||||
"UnitValue(1, 'pt') % 0",
|
||||
"UnitValue(1, 'pt') + NaN",
|
||||
"UnitValue(1e308, 'mi').as('pt')",
|
||||
"UnitValue(1, 'pt') + UnitValue(1e308, 'mi')",
|
||||
] {
|
||||
assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}");
|
||||
}
|
||||
assert_eq!(number(&mut r, "UnitValue(1e300, 'pt').as('mi') * 0"), 0.0);
|
||||
close(number(&mut r, "UnitValue(1e307, 'km').as('mi')"), 1e307 * (1000.0 / 1609.344), "a large value that fits after the division");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_realm_without_unit_values_keeps_the_standard_operators() {
|
||||
let mut r = Realm::new();
|
||||
assert_eq!(text(&mut r, "typeof UnitValue"), "undefined");
|
||||
let mut r = realm();
|
||||
let plain = "var o = {valueOf: function () { return 4; }}; [o + 1, o * 2, o < 5, o == 4].join()";
|
||||
assert_eq!(text(&mut r, plain), "5,8,true,true", "other objects use their valueOf");
|
||||
let named = "function P() {} P.prototype['+'] = function () { return 'called'; }; String(new P() + 1)";
|
||||
assert_eq!(text(&mut r, named), "[object Object]1", "a method named for an operator is not called");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_ends_in_an_error_or_a_limit() {
|
||||
let mut r = realm();
|
||||
let long = "var s = 'pt'; for (var i = 0; i < 17; i++) s += s; ";
|
||||
assert_eq!(text(&mut r, &format!("{long} UnitValue(1, s).type")), "?");
|
||||
assert_eq!(text(&mut r, &format!("{long} UnitValue('1 ' + s).type")), "?");
|
||||
assert_eq!(error_name(&mut r, &format!("{long} UnitValue(1, 'in').as(s)")), "Error");
|
||||
let loop_text = "var o = {toString: function () { return String(UnitValue(o)); }}; UnitValue(o)";
|
||||
match r.run(loop_text) {
|
||||
Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let value_of = "var o = {valueOf: function () { return UnitValue(1, 'pt') * o; }}; UnitValue(1, 'pt') * o";
|
||||
match r.run(value_of) {
|
||||
Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(text(&mut r, "String(UnitValue(3, 'pt'))"), "3 pt", "the realm runs on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_values_survive_a_collection() {
|
||||
let mut r = realm();
|
||||
r.run("var keep = UnitValue(2, 'in'); for (var i = 0; i < 1000; i++) UnitValue(i, 'pt');").unwrap();
|
||||
r.collect_garbage();
|
||||
assert_eq!(text(&mut r, "String(keep + UnitValue(72, 'pt')) + ' ' + String(UnitValue(1, 'pc'))"), "3 in 1 pc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_measurement_counts_toward_the_heap() {
|
||||
let mut r = realm();
|
||||
// The growth from 100 objects to 200, so the script's own code and strings cancel out.
|
||||
let mut per_hundred = |make: &str| {
|
||||
let mut grown = |count: usize| {
|
||||
r.run("var kept = [];").unwrap();
|
||||
let before = r.collect_garbage();
|
||||
r.run(&format!("for (var i = 0; i < {count}; i++) kept.push({make});")).unwrap();
|
||||
r.collect_garbage() - before
|
||||
};
|
||||
grown(200) - grown(100)
|
||||
};
|
||||
// The first runs also leave bindings and names the later ones reuse.
|
||||
per_hundred("{}");
|
||||
let plain = per_hundred("{}");
|
||||
let measures = per_hundred("UnitValue(i, 'pt')");
|
||||
assert_eq!(measures - plain, 100 * crate::heap::UNIT_VALUE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_install_that_hits_the_heap_limit_installs_everything_on_the_next_call() {
|
||||
let cost = {
|
||||
let mut r = Realm::new();
|
||||
let before = r.collect_garbage();
|
||||
r.add_unit_values().unwrap();
|
||||
r.collect_garbage() - before
|
||||
};
|
||||
let mut failed = 0;
|
||||
for step in 0..=16 {
|
||||
let mut r = Realm::new();
|
||||
let live = r.collect_garbage();
|
||||
r.set_limits(Limits { heap_bytes: live + cost * step / 16, ..Limits::default() });
|
||||
let first = r.add_unit_values();
|
||||
r.set_limits(Limits::default());
|
||||
if first.is_err() {
|
||||
failed += 1;
|
||||
r.add_unit_values().unwrap();
|
||||
}
|
||||
assert_eq!(number(&mut r, "UnitValue(1, 'in').as('pt')"), 72.0, "limit at {step}/16 of the install");
|
||||
}
|
||||
assert!(failed >= 1, "no limit stopped the install");
|
||||
}
|
||||
|
||||
/// Installs with members that stop after the global `UnitValue` is defined.
|
||||
fn stopped_install(r: &mut Realm) {
|
||||
let stopped = crate::unit_value::install_with(r.interp(), |i, proto| {
|
||||
crate::builtins::method(i, proto, "toString", |_, _, _, _| Ok(crate::value::Value::Undefined), 0)?;
|
||||
let global = i.global;
|
||||
crate::builtins::data(i, global, "UnitValue", crate::value::Value::Number(1.0), 0)?;
|
||||
Err(crate::interp::Abrupt::Internal("stopped".into()))
|
||||
});
|
||||
assert!(stopped.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_install_that_fails_part_way_installs_everything_on_the_next_call() {
|
||||
let mut r = Realm::new();
|
||||
stopped_install(&mut r);
|
||||
assert_eq!(text(&mut r, "typeof UnitValue"), "undefined");
|
||||
assert!(boolean(&mut r, "!('UnitValue' in this)"));
|
||||
let mut kept = Realm::new();
|
||||
kept.run("var UnitValue = 'mine';").unwrap();
|
||||
stopped_install(&mut kept);
|
||||
assert_eq!(text(&mut kept, "UnitValue"), "mine");
|
||||
r.add_unit_values().unwrap();
|
||||
assert_eq!(number(&mut r, "UnitValue(1, 'in').as('pt')"), 72.0);
|
||||
assert_eq!(text(&mut r, "String(UnitValue(1, 'in') + UnitValue(72, 'pt'))"), "2 in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_install_changes_nothing() {
|
||||
let mut r = realm();
|
||||
r.run("UnitValue.baseUnit = UnitValue(1, 'mm'); var Kept = UnitValue;").unwrap();
|
||||
r.add_unit_values().unwrap();
|
||||
assert!(boolean(&mut r, "Kept === UnitValue && UnitValue(1, 'mm').as('px') === 1"));
|
||||
}
|
||||
+21
@@ -2743,6 +2743,27 @@ itself throws a `TypeError`. So does a property that is not writable or not conf
|
||||
would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216
|
||||
characters throws a `RangeError`.
|
||||
|
||||
`UnitValue` holds a measurement: a number and a unit
|
||||
(https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/). Scripts make one
|
||||
with or without `new`, as `UnitValue(12, 'pt')`, `UnitValue('12 pt')` or `UnitValue(other)` (a copy). The units are
|
||||
`in`, `ft`, `yd`, `mi`, `mm`, `cm`, `m`, `km`, `pt`, `pc`, `tpt`, `tpc`, `ci`, `px` and `%`, each also written as its
|
||||
singular or plural name (`inch`, `inches`, `traditional point`); `type` gives the abbreviation. `as(unit)` gives the
|
||||
number in another unit and `convert(unit)` changes the object to it and returns `true`. A pixel is one `baseUnit` and
|
||||
100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets
|
||||
it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation,
|
||||
such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and
|
||||
give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit, with the left one's
|
||||
`baseUnit` for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and
|
||||
`>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~`
|
||||
inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators,
|
||||
work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or
|
||||
longer than 64 characters), and a number that is not finite make an object whose `type` is `?` and whose `value` is
|
||||
0, which prints as `UnitValue 0.00000`; converting it, using it with any of these operators, a result that is not finite (a division
|
||||
by 0 included) and a comparison with a number that is not finite throw a `RangeError`; an unknown unit given to `as`, `convert` or `type` throws an
|
||||
`Error` and leaves the object as it was; `value` takes only a finite number; and `baseUnit` takes only `null` or a
|
||||
length greater than 0 (not pixels or percentages). Two units of length convert through their exact ratio to the inch,
|
||||
so `UnitValue(1, 'in').as('pt')` is exactly 72.
|
||||
|
||||
The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A
|
||||
run that changes no document adds no undo step. The journal records each command the run finished, as it records
|
||||
commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app
|
||||
|
||||
@@ -1035,6 +1035,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `UnitValue` measurements ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/)): the constructor with a number and a unit, with text such as `12 pt`, or with another `UnitValue`; the length units, `px` and `%` by abbreviation, singular or plural; `value`, `type` and `baseUnit` on the class and on each object; `as` and `convert`; and the arithmetic, comparison and unary operators with a number or another `UnitValue`, the right one converted to the left one's unit, with `>` and `>=` as the negations of `<=` and `<`. Realms without `UnitValue` keep the standard operators. VectorCraft's own rules: an invalid object has `type` `?` and value 0, and converting it or using it with these operators, a result that is not finite (a division by 0 included), a comparison with a number that is not finite and a base that is not a length greater than 0 throw. `crates/js/src/unit_value_tests.rs`, `crates/engine/src/tests/script_dollar.rs`.
|
||||
- Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`).
|
||||
- Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user