oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/foundations.rs
57.9 KiB, 58 runs
created by r1870400018:63234, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // U3 owns this file. Foundations: `type`, `repr`, `assert`, `panic`, `eval`, `range`, the type |
| 2 | // constructors, `plugin` (refused with a diagnostic, as an interim), and methods on int, float, version and |
| 3 | // bytes. `repr` is the one text form every other unit prints a value by. |
| 4 | // |
| 5 | // Three entry points exist for the evaluator core (U2) beyond `call`: `constructor(ty)` is what calling a |
| 6 | // type value runs (`int("3")`, `str(x)`), `type_scope(ty, name)` answers `str.from-unicode`, `float.inf` |
| 7 | // and the unbound methods (`str.len`), and `field(value, name)` answers `1pt.abs`, `(50% + 1pt).ratio`, |
| 8 | // `(left + top).x`, `stroke.paint` and `version.major`. `method(ty, name)` is the one method table. |
| 9 | |
| 10 | use crate::diag::DiagnosticKind; |
| 11 | use crate::eval::args::Args; |
| 12 | use crate::eval::content::{ |
| 13 | Content, |
| 14 | ElemKind, |
| 15 | }; |
| 16 | use crate::eval::eval::{ |
| 17 | eval_string, |
| 18 | EvalMode, |
| 19 | }; |
| 20 | use crate::eval::func::{ |
| 21 | Func, |
| 22 | NativeFunc, |
| 23 | }; |
| 24 | use crate::eval::intro::{ |
| 25 | Counter, |
| 26 | CounterKey, |
| 27 | State, |
| 28 | }; |
| 29 | use crate::eval::lib::decimal::Decimal; |
| 30 | use crate::eval::lib::{ |
| 31 | array, |
| 32 | color, |
| 33 | datetime, |
| 34 | dict, |
| 35 | geom, |
| 36 | math, |
| 37 | string, |
| 38 | sym, |
| 39 | }; |
| 40 | use crate::eval::scope::Scope; |
| 41 | use crate::eval::select::Selector; |
| 42 | use crate::eval::value::{ |
| 43 | Alignment, |
| 44 | Angle, |
| 45 | Dash, |
| 46 | DashItem, |
| 47 | Datetime, |
| 48 | Dict, |
| 49 | Direction, |
| 50 | Duration, |
| 51 | Fraction, |
| 52 | HAlign, |
| 53 | Label, |
| 54 | Length, |
| 55 | LineCap, |
| 56 | LineJoin, |
| 57 | Module, |
| 58 | Paint, |
| 59 | Ratio, |
| 60 | RegexValue, |
| 61 | Stroke, |
| 62 | Tiling, |
| 63 | Type, |
| 64 | VAlign, |
| 65 | Value, |
| 66 | }; |
| 67 | use crate::eval::Engine; |
| 68 | use crate::syntax::Span; |
| 69 | |
| 70 | use oxedyne_fe2o3_core::prelude::*; |
| 71 | |
| 72 | use std::sync::Arc; |
| 73 | |
| 74 | native_fns! { |
| 75 | pub enum FoundFn { |
| 76 | Type => "type", |
| 77 | Repr => "repr", |
| 78 | Assert => "assert", |
| 79 | AssertEq => "eq", |
| 80 | AssertNe => "ne", |
| 81 | Panic => "panic", |
| 82 | Eval => "eval", |
| 83 | Range => "range", |
| 84 | Int => "int", |
| 85 | Float => "float", |
| 86 | Str => "str", |
| 87 | Bool => "bool", |
| 88 | Label => "label", |
| 89 | Regex => "regex", |
| 90 | Version => "version", |
| 91 | Bytes => "bytes", |
| 92 | Arguments => "arguments", |
| 93 | Plugin => "plugin", |
| 94 | PluginTransition => "transition", |
| 95 | Decimal => "decimal", |
| 96 | Target => "target", |
| 97 | At => "at", |
| 98 | Len => "len", |
| 99 | Slice => "slice", |
| 100 | Signum => "signum", |
| 101 | IntBitNot => "bit-not", |
| 102 | IntBitAnd => "bit-and", |
| 103 | IntBitOr => "bit-or", |
| 104 | IntBitXor => "bit-xor", |
| 105 | IntBitLshift => "bit-lshift", |
| 106 | IntBitRshift => "bit-rshift", |
| 107 | ToBytes => "to-bytes", |
| 108 | IntFromBytes => "from-bytes", |
| 109 | FloatIsNan => "is-nan", |
| 110 | FloatIsInfinite => "is-infinite", |
| 111 | FloatFromBytes => "from-bytes", |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | // The Typst version this library follows, for `sys.version`. |
| 116 | const TYPST_VERSION: [u32; 3] = [0, 15, 1]; |
| 117 | |
| 118 | pub fn define(scope: &mut Scope) { |
| 119 | for ty in [ |
| 120 | Type::Bool, Type::Int, Type::Float, Type::Decimal, Type::Str, Type::Label, Type::Bytes, Type::Content, |
| 121 | Type::Array, Type::Dict, Type::Func, Type::Args, Type::Type, Type::Module, Type::Regex, |
| 122 | Type::Selector, Type::Datetime, Type::Symbol, Type::Duration, Type::Version, Type::Length, |
| 123 | Type::Angle, Type::Ratio, Type::Relative, Type::Fraction, Type::Direction, Type::Alignment, |
| 124 | Type::Color, Type::Gradient, Type::Tiling, Type::Stroke, Type::Location, Type::Counter, |
| 125 | Type::State, |
| 126 | ] { |
| 127 | scope.define(ty.name(), Value::Type(ty)); |
| 128 | } |
| 129 | for f in [FoundFn::Repr, FoundFn::Panic, FoundFn::Assert, FoundFn::Eval, FoundFn::Plugin, |
| 130 | FoundFn::Target, FoundFn::Range] |
| 131 | { |
| 132 | scope.define(f.name(), native(f)); |
| 133 | } |
| 134 | scope.define("sys", Value::Module(Arc::new(sys_module(&[])))); |
| 135 | } |
| 136 | |
| 137 | fn native(f: FoundFn) -> Value { Value::Func(Func::Native(NativeFunc::Found(f))) } |
| 138 | |
| 139 | /// The `sys` module, whose `inputs` holds `inputs` as strings in the order given. A key given twice keeps |
| 140 | /// the place it first took and the value it was last given, as Typst's dictionary collects them. |
| 141 | pub fn sys_module(inputs: &[(String, String)]) -> Module { |
| 142 | let mut s = Scope::new(); |
| 143 | let mut dict = Dict::new(); |
| 144 | for (key, val) in inputs { |
| 145 | dict.insert(key, Value::str(val.as_str())); |
| 146 | } |
| 147 | define_nth(&mut s, 0, "version", Value::Version(Arc::new(TYPST_VERSION.to_vec()))); |
| 148 | define_nth(&mut s, 1, "inputs", Value::dict(dict)); |
| 149 | Module::new("sys", s) |
| 150 | } |
| 151 | |
| 152 | /// Binds the `n`th member of a native module. The binding's detached span carries the ordinal, so |
| 153 | /// `dictionary(module)`, which orders a module's bindings by where they were bound, lists a native |
| 154 | /// module in Typst's definition order. |
| 155 | pub fn define_nth(scope: &mut Scope, n: usize, name: &str, value: Value) { |
| 156 | let at = n as u32; |
| 157 | scope.define_at(name, value, Span { file: crate::syntax::FileId::DETACHED, start: at, end: at }); |
| 158 | } |
| 159 | |
| 160 | /// What calling a type value runs: `int("3")`, `datetime(..)`, `counter(heading)`. `None` for a type |
| 161 | /// Typst gives no constructor ("type content does not have a constructor"). |
| 162 | pub fn constructor(ty: Type) -> Option<NativeFunc> { |
| 163 | use crate::eval::lib::intro::IntroFn; |
| 164 | use crate::eval::lib::visual::VisualFn; |
| 165 | use crate::eval::select::StyleFn; |
| 166 | match ty { |
| 167 | Type::Bool => Some(NativeFunc::Found(FoundFn::Bool)), |
| 168 | Type::Int => Some(NativeFunc::Found(FoundFn::Int)), |
| 169 | Type::Float => Some(NativeFunc::Found(FoundFn::Float)), |
| 170 | Type::Decimal => Some(NativeFunc::Found(FoundFn::Decimal)), |
| 171 | Type::Str => Some(NativeFunc::Found(FoundFn::Str)), |
| 172 | Type::Label => Some(NativeFunc::Found(FoundFn::Label)), |
| 173 | Type::Regex => Some(NativeFunc::Found(FoundFn::Regex)), |
| 174 | Type::Version => Some(NativeFunc::Found(FoundFn::Version)), |
| 175 | Type::Bytes => Some(NativeFunc::Found(FoundFn::Bytes)), |
| 176 | Type::Args => Some(NativeFunc::Found(FoundFn::Arguments)), |
| 177 | Type::Type => Some(NativeFunc::Found(FoundFn::Type)), |
| 178 | Type::Array => Some(NativeFunc::Array(array::ArrayFn::Construct)), |
| 179 | Type::Dict => Some(NativeFunc::Dict(dict::DictFn::Construct)), |
| 180 | Type::Datetime => Some(NativeFunc::Datetime(datetime::DatetimeFn::Datetime)), |
| 181 | Type::Duration => Some(NativeFunc::Datetime(datetime::DatetimeFn::Duration)), |
| 182 | Type::Symbol => Some(NativeFunc::Sym(sym::SymFn::Symbol)), |
| 183 | Type::Stroke => Some(NativeFunc::Visual(VisualFn::Stroke)), |
| 184 | Type::Tiling => Some(NativeFunc::Visual(VisualFn::Tiling)), |
| 185 | Type::Selector => Some(NativeFunc::Style(StyleFn::Selector)), |
| 186 | Type::Counter => Some(NativeFunc::Intro(IntroFn::Counter)), |
| 187 | Type::State => Some(NativeFunc::Intro(IntroFn::State)), |
| 188 | _ => None, |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// A value that can be called: a function, a type with a constructor (`(1, 2).map(str)`), or a symbol that |
| 193 | /// is an accent or an opening delimiter (`map(math.floor)`), the cast Typst makes wherever it expects a |
| 194 | /// function. |
| 195 | pub fn as_func(v: &Value) -> Option<Func> { |
| 196 | match v { |
| 197 | Value::Func(f) => Some(f.clone()), |
| 198 | Value::Type(t) => constructor(*t).map(Func::Native), |
| 199 | Value::Symbol(s) => math::symbol_func(sym::text(s)), |
| 200 | _ => None, |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /// Why `v` is not a function: Typst names a symbol that cannot be called, and the type of anything else. |
| 205 | pub fn func_refusal(v: &Value) -> String { |
| 206 | match v { |
| 207 | Value::Symbol(s) => fmt!("symbol {} is not callable", sym::text(s)), |
| 208 | other => fmt!("expected function, found {}", type_desc(other.ty())), |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// The type whose constructor `f` is, for a constructor function's scope (`str.from-unicode` read |
| 213 | /// through a function bound to `str`). |
| 214 | pub fn constructed_type(f: NativeFunc) -> Option<Type> { |
| 215 | const TYPES: [Type; 21] = [ |
| 216 | Type::Bool, Type::Int, Type::Float, Type::Decimal, Type::Str, Type::Label, Type::Regex, Type::Version, |
| 217 | Type::Bytes, Type::Args, Type::Type, Type::Array, Type::Dict, Type::Datetime, Type::Duration, |
| 218 | Type::Symbol, Type::Stroke, Type::Tiling, Type::Selector, Type::Counter, Type::State, |
| 219 | ]; |
| 220 | TYPES.iter().copied().find(|t| constructor(*t) == Some(f)) |
| 221 | } |
| 222 | |
| 223 | /// The methods of int, float, version and bytes, by name. A name several of these types share (`at`, |
| 224 | /// `signum`, `to-bytes`) is one function that dispatches on its receiver. |
| 225 | pub fn method(name: &str) -> Option<FoundFn> { |
| 226 | let f = match name { |
| 227 | "at" => FoundFn::At, |
| 228 | "len" => FoundFn::Len, |
| 229 | "slice" => FoundFn::Slice, |
| 230 | "signum" => FoundFn::Signum, |
| 231 | "bit-not" => FoundFn::IntBitNot, |
| 232 | "bit-and" => FoundFn::IntBitAnd, |
| 233 | "bit-or" => FoundFn::IntBitOr, |
| 234 | "bit-xor" => FoundFn::IntBitXor, |
| 235 | "bit-lshift" => FoundFn::IntBitLshift, |
| 236 | "bit-rshift" => FoundFn::IntBitRshift, |
| 237 | "to-bytes" => FoundFn::ToBytes, |
| 238 | "is-nan" => FoundFn::FloatIsNan, |
| 239 | "is-infinite" => FoundFn::FloatIsInfinite, |
| 240 | _ => return None, |
| 241 | }; |
| 242 | Some(f) |
| 243 | } |
| 244 | |
| 245 | // The receiver types each method of this area accepts. |
| 246 | fn method_types(f: FoundFn) -> &'static [Type] { |
| 247 | match f { |
| 248 | FoundFn::At => &[Type::Version, Type::Bytes], |
| 249 | FoundFn::Len | FoundFn::Slice => &[Type::Bytes], |
| 250 | FoundFn::Signum | FoundFn::ToBytes => &[Type::Int, Type::Float], |
| 251 | FoundFn::IntBitNot | FoundFn::IntBitAnd | FoundFn::IntBitOr | FoundFn::IntBitXor |
| 252 | | FoundFn::IntBitLshift | FoundFn::IntBitRshift => &[Type::Int], |
| 253 | FoundFn::FloatIsNan | FoundFn::FloatIsInfinite => &[Type::Float], |
| 254 | _ => &[], |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// "type integer has no method `is-nan`": a method reached through a name another type owns. |
| 259 | pub fn no_method(engine: &mut Engine, span: Span, ty: Type, name: &str) -> Error<ErrTag> { |
| 260 | engine.error(DiagnosticKind::Type, span, fmt!("type {} has no method `{}`", ty.long_name(), name)) |
| 261 | } |
| 262 | |
| 263 | /// `ty.name`: a type's static members (`float.inf`, `str.from-unicode`, `color.hsl`, `datetime.today`), |
| 264 | /// then its methods, which Typst also exposes unbound. |
| 265 | pub fn type_scope(ty: Type, name: &str) -> Option<Value> { |
| 266 | let stat = match (ty, name) { |
| 267 | (Type::Float, "inf") => Some(Value::Float(f64::INFINITY)), |
| 268 | (Type::Float, "nan") => Some(Value::Float(f64::NAN)), |
| 269 | (Type::Float, "from-bytes") => Some(native(FoundFn::FloatFromBytes)), |
| 270 | (Type::Int, "from-bytes") => Some(native(FoundFn::IntFromBytes)), |
| 271 | (Type::Array, "range") => Some(native(FoundFn::Range)), |
| 272 | (Type::Str, _) => string::static_fn(name) |
| 273 | .map(|f| Value::Func(Func::Native(NativeFunc::Str(f)))), |
| 274 | (Type::Color, _) => color::color_static(name), |
| 275 | (Type::Gradient, _) => color::gradient_static(name), |
| 276 | (Type::Datetime, "today") => Some(Value::Func(Func::Native( |
| 277 | NativeFunc::Datetime(datetime::DatetimeFn::Today)))), |
| 278 | (Type::Direction, _) => geom::type_static(ty, name) |
| 279 | .map(|f| Value::Func(Func::Native(NativeFunc::Geom(f)))), |
| 280 | _ => None, |
| 281 | }; |
| 282 | match stat { |
| 283 | Some(v) => Some(v), |
| 284 | None => crate::eval::methods::type_method(ty, name).map(|f| Value::Func(Func::Native(f))), |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | /// `f.name` for native functions that carry members: `assert.eq`, `json.encode`. |
| 289 | pub fn func_scope(f: &Func, name: &str) -> Option<Value> { |
| 290 | match f { |
| 291 | Func::Native(NativeFunc::Found(FoundFn::Assert)) => match name { |
| 292 | "eq" => Some(native(FoundFn::AssertEq)), |
| 293 | "ne" => Some(native(FoundFn::AssertNe)), |
| 294 | _ => None, |
| 295 | }, |
| 296 | Func::Native(NativeFunc::Data(d)) => crate::eval::lib::data::func_scope(*d, name), |
| 297 | Func::Native(NativeFunc::Found(FoundFn::Plugin)) if name == "transition" |
| 298 | => Some(native(FoundFn::PluginTransition)), |
| 299 | _ => None, |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// `value.name` for the value types whose fields Typst exposes. `None` when the type has no such field. |
| 304 | pub fn field(v: &Value, name: &str) -> Option<Value> { |
| 305 | match (v, name) { |
| 306 | (Value::Length(l), "abs") => Some(Value::Length(Length::pt(l.abs))), |
| 307 | (Value::Length(l), "em") => Some(Value::Float(l.em)), |
| 308 | (Value::Relative(r), "ratio") => Some(Value::Ratio(r.rel)), |
| 309 | (Value::Relative(r), "length") => Some(Value::Length(r.abs)), |
| 310 | (Value::Alignment(a), "x") => Some(match a.x { |
| 311 | Some(x) => Value::Alignment(Alignment { x: Some(x), y: None }), |
| 312 | None => Value::None, |
| 313 | }), |
| 314 | (Value::Alignment(a), "y") => Some(match a.y { |
| 315 | Some(y) => Value::Alignment(Alignment { x: None, y: Some(y) }), |
| 316 | None => Value::None, |
| 317 | }), |
| 318 | // A component the version was not given is "unknown version component", not zero. |
| 319 | (Value::Version(v), "major") => v.first().map(|x| Value::Int(*x as i64)), |
| 320 | (Value::Version(v), "minor") => v.get(1).map(|x| Value::Int(*x as i64)), |
| 321 | (Value::Version(v), "patch") => v.get(2).map(|x| Value::Int(*x as i64)), |
| 322 | (Value::Stroke(s), _) => stroke_field(s, name), |
| 323 | _ => None, |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | fn stroke_field(s: &Stroke, name: &str) -> Option<Value> { |
| 328 | let v = match name { |
| 329 | "paint" => match &s.paint { |
| 330 | Some(p) => paint_value(p), |
| 331 | None => Value::Auto, |
| 332 | }, |
| 333 | "thickness" => s.thickness.map(Value::Length).unwrap_or(Value::Auto), |
| 334 | "cap" => s.cap.map(|c| Value::str(cap_name(c))).unwrap_or(Value::Auto), |
| 335 | "join" => s.join.map(|j| Value::str(join_name(j))).unwrap_or(Value::Auto), |
| 336 | "dash" => match &s.dash { |
| 337 | None => Value::Auto, |
| 338 | Some(None) => Value::None, |
| 339 | Some(Some(d)) => dash_value(d), |
| 340 | }, |
| 341 | "miter-limit" => s.miter_limit.map(Value::Float).unwrap_or(Value::Auto), |
| 342 | _ => return None, |
| 343 | }; |
| 344 | Some(v) |
| 345 | } |
| 346 | |
| 347 | pub fn paint_value(p: &Paint) -> Value { |
| 348 | match p { |
| 349 | Paint::Color(c) => Value::Color(*c), |
| 350 | Paint::Gradient(g) => Value::Gradient(g.clone()), |
| 351 | Paint::Tiling(t) => Value::Tiling(t.clone()), |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn dash_value(d: &Dash) -> Value { |
| 356 | let arr = d.array.iter().map(|i| match i { |
| 357 | DashItem::Len(l) => Value::Length(*l), |
| 358 | DashItem::Dot => Value::str("dot"), |
| 359 | }).collect(); |
| 360 | let mut dict = Dict::new(); |
| 361 | dict.insert("array", Value::array(arr)); |
| 362 | dict.insert("phase", Value::Length(d.phase)); |
| 363 | Value::dict(dict) |
| 364 | } |
| 365 | |
| 366 | fn cap_name(c: LineCap) -> &'static str { |
| 367 | match c { |
| 368 | LineCap::Butt => "butt", |
| 369 | LineCap::Round => "round", |
| 370 | LineCap::Square => "square", |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | fn join_name(j: LineJoin) -> &'static str { |
| 375 | match j { |
| 376 | LineJoin::Miter => "miter", |
| 377 | LineJoin::Round => "round", |
| 378 | LineJoin::Bevel => "bevel", |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | // Argument helpers shared by every U3 area. |
| 383 | |
| 384 | /// The receiver of a method call: the first positional argument. |
| 385 | pub fn receiver(args: &mut Args) -> Outcome<Value> { |
| 386 | args.expect::<Value>("self") |
| 387 | } |
| 388 | |
| 389 | /// The next positional argument, required, with Typst's message when absent. |
| 390 | pub fn need(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<Value> { |
| 391 | match res!(args.eat::<Value>()) { |
| 392 | Some(v) => Ok(v), |
| 393 | None => Err(engine.error(DiagnosticKind::Type, args.span, fmt!("missing argument: {}", what))), |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// "expected X, found Y", as a spanned diagnostic. |
| 398 | pub fn mismatch(engine: &mut Engine, span: Span, expected: &str, found: &Value) -> Error<ErrTag> { |
| 399 | engine.error(DiagnosticKind::Type, span, fmt!("expected {}, found {}", expected, type_desc(found.ty()))) |
| 400 | } |
| 401 | |
| 402 | /// Typst's refusal of a keyword parameter, a string from a closed set: `choices` is its wording of the |
| 403 | /// alternatives (`"cover", "contain", or "stretch"`). A string outside the set is named without what was |
| 404 | /// found, and any other type, a symbol among them, with it. |
| 405 | pub fn keyword_message(choices: &str, v: &Value) -> String { |
| 406 | match v { |
| 407 | Value::Str(_) => fmt!("expected {}", choices), |
| 408 | other => fmt!("expected {}, found {}", choices, type_desc(other.ty())), |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// The keyword `v` is, one of `words`. A symbol is not cast to the string it stands for, as it is where a |
| 413 | /// parameter is a `str`: no keyword of Typst's is a symbol's text, and Typst refuses one by its type. |
| 414 | pub fn keyword(v: &Value, words: &[&str], choices: &str) -> Outcome<Arc<String>> { |
| 415 | match v { |
| 416 | Value::Str(s) if words.contains(&s.as_str()) => Ok(s.clone()), |
| 417 | other => Err(err!("{}", keyword_message(choices, other); Input, Invalid)), |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | /// A type as Typst names it in "expected ..., found ..." messages. |
| 422 | pub fn type_desc(ty: Type) -> &'static str { ty.long_name() } |
| 423 | |
| 424 | /// Rejects arguments left over after a native took what it reads. |
| 425 | pub fn finish(engine: &mut Engine, args: Args) -> Outcome<()> { |
| 426 | let span = args.span; |
| 427 | match args.items.first() { |
| 428 | None => Ok(()), |
| 429 | Some(a) => { |
| 430 | let msg = match &a.name { |
| 431 | Some(n) => fmt!("unexpected argument: {}", n), |
| 432 | None => "unexpected argument".to_string(), |
| 433 | }; |
| 434 | let s = if a.span.is_detached() { span } else { a.span }; |
| 435 | Err(engine.error(DiagnosticKind::Type, s, msg)) |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /// An integer argument (floats are refused, as Typst does for `int` parameters). |
| 441 | pub fn int_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<i64> { |
| 442 | match v { |
| 443 | Value::Int(i) => Ok(i), |
| 444 | other => Err(mismatch(engine, span, "integer", &other)), |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /// A number argument: int or float, as f64. |
| 449 | pub fn num_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<f64> { |
| 450 | match v { |
| 451 | Value::Int(i) => Ok(i as f64), |
| 452 | Value::Float(f) => Ok(f), |
| 453 | other => Err(mismatch(engine, span, "integer or float", &other)), |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | pub fn named_bool(engine: &mut Engine, args: &mut Args, name: &str, default: bool) -> Outcome<bool> { |
| 458 | match res!(args.named::<Value>(name)) { |
| 459 | None => Ok(default), |
| 460 | Some(Value::Bool(b)) => Ok(b), |
| 461 | Some(other) => Err(mismatch(engine, args.span, "boolean", &other)), |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | pub fn str_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<Arc<String>> { |
| 466 | match v.str_cast() { |
| 467 | Some(s) => Ok(s), |
| 468 | None => Err(mismatch(engine, span, "string", &v)), |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | pub fn call(f: FoundFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> { |
| 473 | let span = args.span; |
| 474 | let types = method_types(f); |
| 475 | let recv_ty = args.items.iter().find(|a| a.name.is_none()).map(|a| a.value.ty()); |
| 476 | if !types.is_empty() { |
| 477 | if let Some(ty) = recv_ty { |
| 478 | if !types.contains(&ty) { |
| 479 | return Err(no_method(engine, span, ty, f.name())); |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | let v = match f { |
| 484 | FoundFn::Type => { |
| 485 | let v = res!(need(engine, &mut args, "value")); |
| 486 | res!(finish(engine, args)); |
| 487 | Value::Type(v.ty()) |
| 488 | } |
| 489 | FoundFn::Repr => { |
| 490 | let v = res!(need(engine, &mut args, "value")); |
| 491 | res!(finish(engine, args)); |
| 492 | Value::str(repr(&v)) |
| 493 | } |
| 494 | FoundFn::Assert => { |
| 495 | let cond = res!(need(engine, &mut args, "condition")); |
| 496 | let msg = res!(args.named::<Value>("message")); |
| 497 | res!(finish(engine, args)); |
| 498 | match cond { |
| 499 | Value::Bool(true) => Value::None, |
| 500 | Value::Bool(false) => return Err(assert_fail(engine, span, msg, "assertion failed".to_string())), |
| 501 | other => return Err(mismatch(engine, span, "boolean", &other)), |
| 502 | } |
| 503 | } |
| 504 | FoundFn::AssertEq | FoundFn::AssertNe => { |
| 505 | let a = res!(need(engine, &mut args, "left")); |
| 506 | let b = res!(need(engine, &mut args, "right")); |
| 507 | let msg = res!(args.named::<Value>("message")); |
| 508 | res!(finish(engine, args)); |
| 509 | let eq = crate::eval::ops::equal(&a, &b); |
| 510 | let want = f == FoundFn::AssertEq; |
| 511 | if eq != want { |
| 512 | let text = if want { |
| 513 | fmt!("equality assertion failed: value {} was not equal to {}", repr(&a), repr(&b)) |
| 514 | } else { |
| 515 | fmt!("inequality assertion failed: value {} was equal to {}", repr(&a), repr(&b)) |
| 516 | }; |
| 517 | return Err(assert_fail(engine, span, msg, text)); |
| 518 | } |
| 519 | Value::None |
| 520 | } |
| 521 | FoundFn::Panic => { |
| 522 | let vals = res!(args.all::<Value>()); |
| 523 | let mut msg = String::from("panicked"); |
| 524 | if !vals.is_empty() { |
| 525 | msg.push_str(" with: "); |
| 526 | // A string is shown as its text, anything else by its repr. |
| 527 | let parts: Vec<String> = vals.iter().map(|v| match v { |
| 528 | Value::Str(s) => (**s).clone(), |
| 529 | other => repr(other), |
| 530 | }).collect(); |
| 531 | msg.push_str(&parts.join(", ")); |
| 532 | } |
| 533 | return Err(engine.error(DiagnosticKind::Type, span, msg)); |
| 534 | } |
| 535 | FoundFn::Eval => { |
| 536 | let text = res!(need(engine, &mut args, "source")); |
| 537 | let text = res!(str_of(engine, span, text)); |
| 538 | let mode = match res!(args.named::<Value>("mode")) { |
| 539 | None => EvalMode::Code, |
| 540 | Some(Value::Str(s)) => match s.as_str() { |
| 541 | "code" => EvalMode::Code, |
| 542 | "markup" => EvalMode::Markup, |
| 543 | "math" => EvalMode::Math, |
| 544 | _ => return Err(engine.error(DiagnosticKind::Type, span, |
| 545 | "expected \"markup\", \"math\", or \"code\"")), |
| 546 | }, |
| 547 | Some(other) => return Err(mismatch(engine, span, "string", &other)), |
| 548 | }; |
| 549 | let mut scope = Scope::new(); |
| 550 | match res!(args.named::<Value>("scope")) { |
| 551 | None => (), |
| 552 | Some(Value::Dict(d)) => for (k, v) in d.iter() { scope.define(k, v.clone()); }, |
| 553 | Some(other) => return Err(mismatch(engine, span, "dictionary", &other)), |
| 554 | } |
| 555 | res!(finish(engine, args)); |
| 556 | return eval_string(engine, &text, mode, scope, span); |
| 557 | } |
| 558 | FoundFn::Range => return range(engine, args), |
| 559 | FoundFn::Int => { |
| 560 | let v = res!(need(engine, &mut args, "value")); |
| 561 | res!(finish(engine, args)); |
| 562 | res!(to_int(engine, span, v)) |
| 563 | } |
| 564 | FoundFn::Float => { |
| 565 | let v = res!(need(engine, &mut args, "value")); |
| 566 | res!(finish(engine, args)); |
| 567 | res!(to_float(engine, span, v)) |
| 568 | } |
| 569 | FoundFn::Str => { |
| 570 | let v = res!(need(engine, &mut args, "value")); |
| 571 | let base = res!(args.named::<Value>("base")); |
| 572 | res!(finish(engine, args)); |
| 573 | res!(to_str(engine, span, v, base)) |
| 574 | } |
| 575 | FoundFn::Bool => return Err(engine.error(DiagnosticKind::Type, span, "type boolean does not have a constructor")), |
| 576 | FoundFn::Label => { |
| 577 | let v = res!(need(engine, &mut args, "name")); |
| 578 | res!(finish(engine, args)); |
| 579 | let s = res!(str_of(engine, span, v)); |
| 580 | if s.is_empty() { |
| 581 | return Err(engine.error(DiagnosticKind::Type, span, "label name must not be empty")); |
| 582 | } |
| 583 | Value::Label(Label::new(&s)) |
| 584 | } |
| 585 | FoundFn::Regex => { |
| 586 | let v = res!(need(engine, &mut args, "regex")); |
| 587 | res!(finish(engine, args)); |
| 588 | let s = res!(str_of(engine, span, v)); |
| 589 | match RegexValue::new(&s) { |
| 590 | Ok(r) => Value::Regex(Arc::new(r)), |
| 591 | // The `regex` crate's layout: a heading line, the pattern, then the fault. |
| 592 | Err(e) => { |
| 593 | let m = e.msgs().last().cloned().unwrap_or_default(); |
| 594 | let m = m.strip_prefix("regex: ").unwrap_or(&m).trim_end_matches('.').to_string(); |
| 595 | return Err(engine.error(DiagnosticKind::Type, span, fmt!("regex parse error:\n {}\nerror: {}", s, m))); |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | FoundFn::Version => { |
| 600 | let parts = res!(args.all::<Value>()); |
| 601 | res!(finish(engine, args)); |
| 602 | let mut out = Vec::new(); |
| 603 | for p in parts { |
| 604 | res!(version_part(engine, span, p, &mut out)); |
| 605 | } |
| 606 | Value::Version(Arc::new(out)) |
| 607 | } |
| 608 | FoundFn::Bytes => { |
| 609 | let v = res!(need(engine, &mut args, "value")); |
| 610 | res!(finish(engine, args)); |
| 611 | match v.symbol_as_str() { |
| 612 | Value::Str(s) => Value::Bytes(Arc::new(s.as_bytes().to_vec())), |
| 613 | Value::Bytes(b) => Value::Bytes(b), |
| 614 | Value::Array(a) => { |
| 615 | let mut out = Vec::with_capacity(a.len()); |
| 616 | for x in a.iter() { |
| 617 | match x { |
| 618 | Value::Int(i) if (0..=255).contains(i) => out.push(*i as u8), |
| 619 | Value::Int(_) => return Err(engine.error(DiagnosticKind::Type, span, "number must be between 0 and 255")), |
| 620 | other => return Err(mismatch(engine, span, "integer", other)), |
| 621 | } |
| 622 | } |
| 623 | Value::Bytes(Arc::new(out)) |
| 624 | } |
| 625 | other => return Err(mismatch(engine, span, "string, array, or bytes", &other)), |
| 626 | } |
| 627 | } |
| 628 | FoundFn::Arguments => { |
| 629 | let mut a = args.clone(); |
| 630 | a.span = span; |
| 631 | Value::Args(Arc::new(a)) |
| 632 | } |
| 633 | #[cfg(not(feature = "plugin"))] |
| 634 | FoundFn::Plugin | FoundFn::PluginTransition => return Err(engine.error_hint(DiagnosticKind::Unsupported, span, |
| 635 | "wasm plugins are not supported by Austenite", |
| 636 | "a package that needs a plugin cannot be compiled here")), |
| 637 | #[cfg(feature = "plugin")] |
| 638 | FoundFn::Plugin => { |
| 639 | let at = args.items.iter().find(|a| a.name.is_none()).map(|a| a.value_span).unwrap_or(span); |
| 640 | let v = res!(need(engine, &mut args, "source")); |
| 641 | res!(finish(engine, args)); |
| 642 | let bytes = res!(crate::eval::lib::data::source(engine, at, v)); |
| 643 | let p = match engine.caches.plugin_load(&bytes, engine.plugin_fuel) { |
| 644 | Ok(p) => p, |
| 645 | Err(e) => return Err(plugin_error(engine, at, e)), |
| 646 | }; |
| 647 | Value::Module(Arc::new(crate::eval::plugin::Plugin::into_module(p))) |
| 648 | } |
| 649 | #[cfg(feature = "plugin")] |
| 650 | FoundFn::PluginTransition => { |
| 651 | let at = args.items.iter().find(|a| a.name.is_none()).map(|a| a.value_span).unwrap_or(span); |
| 652 | let f = res!(need(engine, &mut args, "func")); |
| 653 | let p = match f { |
| 654 | Value::Func(Func::Plugin(p)) => p, |
| 655 | // Typst's cast names no found type here. |
| 656 | _ => return Err(engine.error(DiagnosticKind::Type, at, "expected plugin function")), |
| 657 | }; |
| 658 | let bytes = res!(plugin_args(engine, args)); |
| 659 | match engine.caches.plugin_transition(&p, bytes, engine.plugin_fuel) { |
| 660 | Ok(q) => Value::Module(Arc::new(crate::eval::plugin::Plugin::into_module(q))), |
| 661 | Err(e) => return Err(plugin_error(engine, span, e)), |
| 662 | } |
| 663 | } |
| 664 | FoundFn::Decimal => { |
| 665 | let v = res!(need(engine, &mut args, "value")); |
| 666 | res!(finish(engine, args)); |
| 667 | match v.symbol_as_str() { |
| 668 | Value::Decimal(d) => Value::Decimal(d), |
| 669 | Value::Int(i) => Value::Decimal(Decimal::from(i)), |
| 670 | Value::Bool(b) => Value::Decimal(Decimal::from(b as i64)), |
| 671 | Value::Float(f) => match Decimal::from_f64(f) { |
| 672 | Some(d) => Value::Decimal(d), |
| 673 | None => return Err(engine.error(DiagnosticKind::Type, span, fmt!("float is not a valid decimal: {}", |
| 674 | format_float(f, None, true, "")))), |
| 675 | }, |
| 676 | Value::Str(s) => match Decimal::parse(&s.replace(MINUS, "-")) { |
| 677 | Some(d) => Value::Decimal(d), |
| 678 | None => return Err(engine.error(DiagnosticKind::Type, span, fmt!("invalid decimal: {}", s))), |
| 679 | }, |
| 680 | other => return Err(mismatch(engine, span, "decimal, integer, boolean, float, or string", &other)), |
| 681 | } |
| 682 | } |
| 683 | FoundFn::Target => { |
| 684 | res!(finish(engine, args)); |
| 685 | if engine.context.styles.is_none() && engine.context.location.is_none() { |
| 686 | return Err(engine.error_hint(DiagnosticKind::Type, span, "can only be used when context is known", |
| 687 | "try wrapping this in a `context` expression")); |
| 688 | } |
| 689 | Value::str("paged") |
| 690 | } |
| 691 | FoundFn::At if recv_ty == Some(Type::Version) => { |
| 692 | let v = res!(receiver(&mut args)); |
| 693 | let i = res!(need(engine, &mut args, "index")); |
| 694 | let i = res!(int_of(engine, span, i)); |
| 695 | res!(finish(engine, args)); |
| 696 | let parts = match v { |
| 697 | Value::Version(p) => p, |
| 698 | other => return Err(mismatch(engine, span, "version", &other)), |
| 699 | }; |
| 700 | let n = parts.len() as i64; |
| 701 | let idx = if i < 0 { n + i } else { i }; |
| 702 | if idx < 0 { |
| 703 | return Err(engine.error(DiagnosticKind::Type, span, fmt!("component index out of bounds (index: {}, len: {})", i, n))); |
| 704 | } |
| 705 | Value::Int(parts.get(idx as usize).copied().unwrap_or(0) as i64) |
| 706 | } |
| 707 | FoundFn::Len => { |
| 708 | let b = res!(bytes_recv(engine, &mut args)); |
| 709 | res!(finish(engine, args)); |
| 710 | Value::Int(b.len() as i64) |
| 711 | } |
| 712 | FoundFn::At => { |
| 713 | let b = res!(bytes_recv(engine, &mut args)); |
| 714 | let i = res!(need(engine, &mut args, "index")); |
| 715 | let i = res!(int_of(engine, span, i)); |
| 716 | let default = res!(args.named::<Value>("default")); |
| 717 | res!(finish(engine, args)); |
| 718 | match locate_index(i, b.len()) { |
| 719 | Some(k) => Value::Int(b[k] as i64), |
| 720 | None => match default { |
| 721 | Some(d) => d, |
| 722 | None => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 723 | "byte index out of bounds (index: {}, len: {}) and no default value was specified", |
| 724 | i, b.len()))), |
| 725 | }, |
| 726 | } |
| 727 | } |
| 728 | FoundFn::Slice => { |
| 729 | let b = res!(bytes_recv(engine, &mut args)); |
| 730 | let (s, e) = res!(slice_bounds(engine, &mut args, b.len(), "byte", |_| true)); |
| 731 | res!(finish(engine, args)); |
| 732 | Value::Bytes(Arc::new(b[s..e].to_vec())) |
| 733 | } |
| 734 | FoundFn::Signum if recv_ty == Some(Type::Int) => { |
| 735 | let i = res!(int_recv(engine, &mut args)); |
| 736 | res!(finish(engine, args)); |
| 737 | Value::Int(i.signum()) |
| 738 | } |
| 739 | FoundFn::IntBitNot => { |
| 740 | let i = res!(int_recv(engine, &mut args)); |
| 741 | res!(finish(engine, args)); |
| 742 | Value::Int(!i) |
| 743 | } |
| 744 | FoundFn::IntBitAnd | FoundFn::IntBitOr | FoundFn::IntBitXor => { |
| 745 | let i = res!(int_recv(engine, &mut args)); |
| 746 | let j = res!(need(engine, &mut args, "rhs")); |
| 747 | let j = res!(int_of(engine, span, j)); |
| 748 | res!(finish(engine, args)); |
| 749 | Value::Int(match f { |
| 750 | FoundFn::IntBitAnd => i & j, |
| 751 | FoundFn::IntBitOr => i | j, |
| 752 | _ => i ^ j, |
| 753 | }) |
| 754 | } |
| 755 | FoundFn::IntBitLshift => { |
| 756 | let i = res!(int_recv(engine, &mut args)); |
| 757 | let n = res!(need(engine, &mut args, "shift")); |
| 758 | let n = res!(int_of(engine, span, n)); |
| 759 | res!(finish(engine, args)); |
| 760 | if n < 0 { |
| 761 | return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero")); |
| 762 | } |
| 763 | match i.checked_shl(n as u32) { |
| 764 | Some(r) if n < 64 => Value::Int(r), |
| 765 | _ => return Err(engine.error(DiagnosticKind::Type, span, "the result is too large")), |
| 766 | } |
| 767 | } |
| 768 | FoundFn::IntBitRshift => { |
| 769 | let i = res!(int_recv(engine, &mut args)); |
| 770 | let n = res!(need(engine, &mut args, "shift")); |
| 771 | let n = res!(int_of(engine, span, n)); |
| 772 | let logical = res!(named_bool(engine, &mut args, "logical", false)); |
| 773 | res!(finish(engine, args)); |
| 774 | if n < 0 { |
| 775 | return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero")); |
| 776 | } |
| 777 | if logical { |
| 778 | if n >= 64 { Value::Int(0) } else { Value::Int(((i as u64) >> n) as i64) } |
| 779 | } else if n >= 64 { |
| 780 | Value::Int(if i < 0 { -1 } else { 0 }) |
| 781 | } else { |
| 782 | Value::Int(i >> n) |
| 783 | } |
| 784 | } |
| 785 | FoundFn::ToBytes if recv_ty == Some(Type::Int) => { |
| 786 | let i = res!(int_recv(engine, &mut args)); |
| 787 | let big = res!(endian(engine, &mut args)); |
| 788 | let size = match res!(args.named::<Value>("size")) { |
| 789 | None => 8, |
| 790 | Some(v) => res!(int_of(engine, span, v)), |
| 791 | }; |
| 792 | res!(finish(engine, args)); |
| 793 | if size < 0 { |
| 794 | return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero")); |
| 795 | } |
| 796 | let size = size as usize; |
| 797 | let le = i.to_le_bytes(); |
| 798 | let fill = if i < 0 { 0xffu8 } else { 0 }; |
| 799 | let mut out: Vec<u8> = (0..size).map(|k| le.get(k).copied().unwrap_or(fill)).collect(); |
| 800 | if big { |
| 801 | out.reverse(); |
| 802 | } |
| 803 | Value::Bytes(Arc::new(out)) |
| 804 | } |
| 805 | FoundFn::IntFromBytes => { |
| 806 | let b = res!(need(engine, &mut args, "bytes")); |
| 807 | let b = match b { |
| 808 | Value::Bytes(b) => b, |
| 809 | other => return Err(mismatch(engine, span, "bytes", &other)), |
| 810 | }; |
| 811 | let big = res!(endian(engine, &mut args)); |
| 812 | let signed = res!(named_bool(engine, &mut args, "signed", true)); |
| 813 | res!(finish(engine, args)); |
| 814 | if b.len() > 8 { |
| 815 | return Err(engine.error(DiagnosticKind::Type, span, "too many bytes to convert to a 64 bit number")); |
| 816 | } |
| 817 | let mut le: Vec<u8> = b.to_vec(); |
| 818 | if big { |
| 819 | le.reverse(); |
| 820 | } |
| 821 | let neg = signed && le.last().map(|x| x & 0x80 != 0).unwrap_or(false); |
| 822 | let mut buf = [if neg { 0xffu8 } else { 0 }; 8]; |
| 823 | for (k, x) in le.iter().enumerate() { |
| 824 | buf[k] = *x; |
| 825 | } |
| 826 | Value::Int(i64::from_le_bytes(buf)) |
| 827 | } |
| 828 | FoundFn::FloatIsNan => { |
| 829 | let x = res!(float_recv(engine, &mut args)); |
| 830 | res!(finish(engine, args)); |
| 831 | Value::Bool(x.is_nan()) |
| 832 | } |
| 833 | FoundFn::FloatIsInfinite => { |
| 834 | let x = res!(float_recv(engine, &mut args)); |
| 835 | res!(finish(engine, args)); |
| 836 | Value::Bool(x.is_infinite()) |
| 837 | } |
| 838 | FoundFn::Signum => { |
| 839 | let x = res!(float_recv(engine, &mut args)); |
| 840 | res!(finish(engine, args)); |
| 841 | Value::Float(x.signum()) |
| 842 | } |
| 843 | FoundFn::ToBytes => { |
| 844 | let x = res!(float_recv(engine, &mut args)); |
| 845 | let big = res!(endian(engine, &mut args)); |
| 846 | let size = match res!(args.named::<Value>("size")) { |
| 847 | None => 8, |
| 848 | Some(v) => res!(int_of(engine, span, v)), |
| 849 | }; |
| 850 | res!(finish(engine, args)); |
| 851 | let mut out = match size { |
| 852 | 8 => x.to_le_bytes().to_vec(), |
| 853 | 4 => (x as f32).to_le_bytes().to_vec(), |
| 854 | _ => return Err(engine.error(DiagnosticKind::Type, span, "size must be either 4 or 8")), |
| 855 | }; |
| 856 | if big { |
| 857 | out.reverse(); |
| 858 | } |
| 859 | Value::Bytes(Arc::new(out)) |
| 860 | } |
| 861 | FoundFn::FloatFromBytes => { |
| 862 | let b = res!(need(engine, &mut args, "bytes")); |
| 863 | let b = match b { |
| 864 | Value::Bytes(b) => b, |
| 865 | other => return Err(mismatch(engine, span, "bytes", &other)), |
| 866 | }; |
| 867 | let big = res!(endian(engine, &mut args)); |
| 868 | res!(finish(engine, args)); |
| 869 | let mut le: Vec<u8> = b.to_vec(); |
| 870 | if big { |
| 871 | le.reverse(); |
| 872 | } |
| 873 | match le.len() { |
| 874 | 8 => { |
| 875 | let mut a = [0u8; 8]; |
| 876 | a.copy_from_slice(&le); |
| 877 | Value::Float(f64::from_le_bytes(a)) |
| 878 | } |
| 879 | 4 => { |
| 880 | let mut a = [0u8; 4]; |
| 881 | a.copy_from_slice(&le); |
| 882 | Value::Float(f32::from_le_bytes(a) as f64) |
| 883 | } |
| 884 | _ => return Err(engine.error(DiagnosticKind::Type, span, "bytes must have a length of 4 or 8")), |
| 885 | } |
| 886 | } |
| 887 | }; |
| 888 | Ok(v) |
| 889 | } |
| 890 | |
| 891 | fn assert_fail(engine: &mut Engine, span: Span, msg: Option<Value>, dflt: String) -> Error<ErrTag> { |
| 892 | match msg.map(Value::symbol_as_str) { |
| 893 | Some(Value::Str(s)) => engine.error(DiagnosticKind::Type, span, fmt!("assertion failed: {}", s)), |
| 894 | _ => engine.error(DiagnosticKind::Type, span, dflt), |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | fn version_part(engine: &mut Engine, span: Span, v: Value, out: &mut Vec<u32>) -> Outcome<()> { |
| 899 | match v { |
| 900 | Value::Int(i) if i >= 0 && i <= u32::MAX as i64 => out.push(i as u32), |
| 901 | Value::Int(i) if i < 0 => return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero")), |
| 902 | Value::Int(_) => return Err(engine.error(DiagnosticKind::Type, span, "number too large")), |
| 903 | Value::Array(a) => for x in a.iter() { |
| 904 | res!(version_part(engine, span, x.clone(), out)); |
| 905 | }, |
| 906 | Value::Version(p) => out.extend(p.iter()), |
| 907 | other => return Err(mismatch(engine, span, "integer or array", &other)), |
| 908 | } |
| 909 | Ok(()) |
| 910 | } |
| 911 | |
| 912 | fn endian(engine: &mut Engine, args: &mut Args) -> Outcome<bool> { |
| 913 | match res!(args.named::<Value>("endian")) { |
| 914 | None => Ok(false), |
| 915 | Some(Value::Str(s)) => match s.as_str() { |
| 916 | "big" => Ok(true), |
| 917 | "little" => Ok(false), |
| 918 | _ => Err(engine.error(DiagnosticKind::Type, args.span, "expected \"big\" or \"little\"")), |
| 919 | }, |
| 920 | Some(other) => Err(mismatch(engine, args.span, "string", &other)), |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | fn int_recv(engine: &mut Engine, args: &mut Args) -> Outcome<i64> { |
| 925 | let v = res!(receiver(args)); |
| 926 | int_of(engine, args.span, v) |
| 927 | } |
| 928 | |
| 929 | fn float_recv(engine: &mut Engine, args: &mut Args) -> Outcome<f64> { |
| 930 | match res!(receiver(args)) { |
| 931 | Value::Float(f) => Ok(f), |
| 932 | other => Err(mismatch(engine, args.span, "float", &other)), |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | fn bytes_recv(engine: &mut Engine, args: &mut Args) -> Outcome<Arc<Vec<u8>>> { |
| 937 | match res!(receiver(args)) { |
| 938 | Value::Bytes(b) => Ok(b), |
| 939 | other => Err(mismatch(engine, args.span, "bytes", &other)), |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | /// A possibly negative index into a sequence of `len`, as Typst resolves it; `None` when out of range. |
| 944 | pub fn locate_index(i: i64, len: usize) -> Option<usize> { |
| 945 | let n = len as i64; |
| 946 | let k = if i < 0 { n.saturating_add(i) } else { i }; |
| 947 | if k >= 0 && k < n { Some(k as usize) } else { None } |
| 948 | } |
| 949 | |
| 950 | /// An error's innermost words, without locations: for a diagnostic raised from another unit's error. |
| 951 | pub fn words(e: &Error<ErrTag>) -> String { e.msgs().last().cloned().unwrap_or_default() } |
| 952 | |
| 953 | /// Resolves a possibly negative index against `len` as Typst's `locate` does: `Ok(None)` when out of |
| 954 | /// range, an error when it lands inside a character (strings only, via `boundary`). |
| 955 | pub fn locate_bound<B: Fn(usize) -> bool>( |
| 956 | engine: &mut Engine, |
| 957 | span: Span, |
| 958 | i: i64, |
| 959 | len: usize, |
| 960 | boundary: &B, |
| 961 | ) |
| 962 | -> Outcome<Option<usize>> |
| 963 | { |
| 964 | let wrapped = if i >= 0 { Some(i) } else { (len as i64).checked_add(i) }; |
| 965 | let resolved = wrapped.filter(|v| *v >= 0 && *v as usize <= len).map(|v| v as usize); |
| 966 | if let Some(k) = resolved { |
| 967 | if !boundary(k) { |
| 968 | return Err(engine.error(DiagnosticKind::Type, span, fmt!("string index {} is not a character boundary", i))); |
| 969 | } |
| 970 | } |
| 971 | Ok(resolved) |
| 972 | } |
| 973 | |
| 974 | /// `slice(start, end, count:)` over a sequence of `len`, as Typst resolves it: `count` counts from the |
| 975 | /// start as written, and an end before the start gives an empty slice. `what` names the sequence in the |
| 976 | /// error ("byte", "string", "array"). |
| 977 | pub fn slice_bounds<B: Fn(usize) -> bool>( |
| 978 | engine: &mut Engine, |
| 979 | args: &mut Args, |
| 980 | len: usize, |
| 981 | what: &str, |
| 982 | boundary: B, |
| 983 | ) |
| 984 | -> Outcome<(usize, usize)> |
| 985 | { |
| 986 | let span = args.span; |
| 987 | let start = match res!(args.eat::<Value>()) { |
| 988 | None => 0, |
| 989 | Some(v) => res!(int_of(engine, span, v)), |
| 990 | }; |
| 991 | let end = match res!(args.eat::<Value>()) { |
| 992 | None | Some(Value::None) => None, |
| 993 | Some(v) => Some(res!(int_of(engine, span, v))), |
| 994 | }; |
| 995 | let count = match res!(args.named::<Value>("count")) { |
| 996 | None | Some(Value::None) => None, |
| 997 | Some(v) => Some(res!(int_of(engine, span, v))), |
| 998 | }; |
| 999 | let end = end.or(count.map(|c| start.saturating_add(c))).unwrap_or(len as i64); |
| 1000 | let s = match res!(locate_bound(engine, span, start, len, &boundary)) { |
| 1001 | Some(k) => k, |
| 1002 | None => return Err(engine.error(DiagnosticKind::Type, span, fmt!("{} index out of bounds (index: {}, len: {})", what, start, len))), |
| 1003 | }; |
| 1004 | let e = match res!(locate_bound(engine, span, end, len, &boundary)) { |
| 1005 | Some(k) => k.max(s), |
| 1006 | None => return Err(engine.error(DiagnosticKind::Type, span, fmt!("{} index out of bounds (index: {}, len: {})", what, end, len))), |
| 1007 | }; |
| 1008 | Ok((s, e)) |
| 1009 | } |
| 1010 | |
| 1011 | fn range(engine: &mut Engine, mut args: Args) -> Outcome<Value> { |
| 1012 | let span = args.span; |
| 1013 | let a = res!(need(engine, &mut args, "end")); |
| 1014 | let a = res!(int_of(engine, span, a)); |
| 1015 | let (start, end) = match res!(args.eat::<Value>()) { |
| 1016 | Some(b) => (a, res!(int_of(engine, span, b))), |
| 1017 | None => (0, a), |
| 1018 | }; |
| 1019 | let step = match res!(args.named::<Value>("step")) { |
| 1020 | None => 1, |
| 1021 | Some(v) => res!(int_of(engine, span, v)), |
| 1022 | }; |
| 1023 | res!(finish(engine, args)); |
| 1024 | if step == 0 { |
| 1025 | return Err(engine.error(DiagnosticKind::Type, span, "number must not be zero")); |
| 1026 | } |
| 1027 | let mut out = Vec::new(); |
| 1028 | let mut x = start; |
| 1029 | while (step > 0 && x < end) || (step < 0 && x > end) { |
| 1030 | res!(engine.burn(span)); |
| 1031 | out.push(Value::Int(x)); |
| 1032 | x = match x.checked_add(step) { |
| 1033 | Some(n) => n, |
| 1034 | None => break, |
| 1035 | }; |
| 1036 | } |
| 1037 | Ok(Value::array(out)) |
| 1038 | } |
| 1039 | |
| 1040 | // Conversions |
| 1041 | |
| 1042 | fn to_int(engine: &mut Engine, span: Span, v: Value) -> Outcome<Value> { |
| 1043 | match v.symbol_as_str() { |
| 1044 | Value::Int(i) => Ok(Value::Int(i)), |
| 1045 | Value::Bool(b) => Ok(Value::Int(b as i64)), |
| 1046 | Value::Decimal(d) => match d.to_i64() { |
| 1047 | Some(i) => Ok(Value::Int(i)), |
| 1048 | None => Err(engine.error(DiagnosticKind::Type, span, "number too large")), |
| 1049 | }, |
| 1050 | Value::Float(f) => { |
| 1051 | let t = f.trunc(); |
| 1052 | if t.is_nan() || t < -9.223372036854776e18 || t >= 9.223372036854776e18 { |
| 1053 | return Err(engine.error(DiagnosticKind::Type, span, "number too large")); |
| 1054 | } |
| 1055 | Ok(Value::Int(t as i64)) |
| 1056 | } |
| 1057 | Value::Str(s) => { |
| 1058 | let t = s.replace('\u{2212}', "-"); |
| 1059 | let (neg, digits) = match t.strip_prefix('-') { |
| 1060 | Some(r) => (true, r), |
| 1061 | None => (false, t.strip_prefix('+').unwrap_or(&t)), |
| 1062 | }; |
| 1063 | if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { |
| 1064 | return Err(engine.error(DiagnosticKind::Type, span, "string contains invalid digits")); |
| 1065 | } |
| 1066 | let mut acc: i64 = 0; |
| 1067 | for b in digits.bytes() { |
| 1068 | let d = (b - b'0') as i64; |
| 1069 | let next = acc.checked_mul(10).and_then(|x| if neg { x.checked_sub(d) } else { x.checked_add(d) }); |
| 1070 | acc = match next { |
| 1071 | Some(n) => n, |
| 1072 | None => { |
| 1073 | let msg = if neg { "integer value is too small" } else { "integer value is too large" }; |
| 1074 | return Err(engine.error_hint(DiagnosticKind::Type, span, msg, |
| 1075 | "value does not fit into a signed 64-bit integer")); |
| 1076 | } |
| 1077 | }; |
| 1078 | } |
| 1079 | Ok(Value::Int(acc)) |
| 1080 | } |
| 1081 | other => Err(mismatch(engine, span, "integer, boolean, float, decimal, or string", &other)), |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | fn to_float(engine: &mut Engine, span: Span, v: Value) -> Outcome<Value> { |
| 1086 | match v.symbol_as_str() { |
| 1087 | Value::Float(f) => Ok(Value::Float(f)), |
| 1088 | Value::Int(i) => Ok(Value::Float(i as f64)), |
| 1089 | Value::Bool(b) => Ok(Value::Float(if b { 1.0 } else { 0.0 })), |
| 1090 | Value::Ratio(r) => Ok(Value::Float(r.0)), |
| 1091 | Value::Decimal(d) => Ok(Value::Float(d.to_f64())), |
| 1092 | Value::Str(s) => { |
| 1093 | let t = s.replace('\u{2212}', "-"); |
| 1094 | match parse_float(&t) { |
| 1095 | Some(f) => Ok(Value::Float(f)), |
| 1096 | None => Err(engine.error(DiagnosticKind::Type, span, fmt!("invalid float: {}", s))), |
| 1097 | } |
| 1098 | } |
| 1099 | other => Err(mismatch(engine, span, "integer, boolean, float, decimal, ratio, or string", &other)), |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | /// Rust's float grammar, which Typst's `float(str)` uses: `inf`, `nan`, `1.`, `.5`, `1e3`. |
| 1104 | fn parse_float(s: &str) -> Option<f64> { |
| 1105 | let body = s.strip_prefix(['+', '-']).unwrap_or(s); |
| 1106 | let lower = body.to_ascii_lowercase(); |
| 1107 | if !(lower == "inf" || lower == "infinity" || lower == "nan") { |
| 1108 | let ok = !body.is_empty() && body.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')); |
| 1109 | if !ok { |
| 1110 | return None; |
| 1111 | } |
| 1112 | } |
| 1113 | s.parse::<f64>().ok() |
| 1114 | } |
| 1115 | |
| 1116 | fn to_str(engine: &mut Engine, span: Span, v: Value, base: Option<Value>) -> Outcome<Value> { |
| 1117 | let base = match base { |
| 1118 | None => None, |
| 1119 | Some(b) => Some(res!(int_of(engine, span, b))), |
| 1120 | }; |
| 1121 | if let Some(b) = base { |
| 1122 | match v { |
| 1123 | Value::Int(i) => { |
| 1124 | if !(2..=36).contains(&b) { |
| 1125 | return Err(engine.error(DiagnosticKind::Type, span, "base must be between 2 and 36")); |
| 1126 | } |
| 1127 | return Ok(Value::str(format_int_with_base(i, b))); |
| 1128 | } |
| 1129 | _ => if b != 10 { |
| 1130 | return Err(engine.error(DiagnosticKind::Type, span, "base is only supported for integers")); |
| 1131 | }, |
| 1132 | } |
| 1133 | } |
| 1134 | let s = match v { |
| 1135 | Value::Int(i) => format_int_with_base(i, 10), |
| 1136 | Value::Float(f) => display_float(f), |
| 1137 | Value::Decimal(d) => d.display(), |
| 1138 | Value::Str(s) => (*s).clone(), |
| 1139 | Value::Label(l) => l.as_str().to_string(), |
| 1140 | Value::Type(t) => type_desc(t).to_string(), |
| 1141 | Value::Version(p) => version_text(&p), |
| 1142 | Value::Symbol(s) => sym::text(&s).to_string(), |
| 1143 | Value::Bytes(b) => match String::from_utf8(b.to_vec()) { |
| 1144 | Ok(s) => s, |
| 1145 | Err(_) => return Err(engine.error(DiagnosticKind::Type, span, "bytes are not valid UTF-8")), |
| 1146 | }, |
| 1147 | other => return Err(mismatch(engine, span, |
| 1148 | "integer, float, decimal, version, bytes, label, type, or string", &other)), |
| 1149 | }; |
| 1150 | Ok(Value::str(s)) |
| 1151 | } |
| 1152 | |
| 1153 | pub const MINUS: char = '\u{2212}'; |
| 1154 | |
| 1155 | /// An integer as `str(n, base:)` prints it, a negative with a typographic minus. |
| 1156 | pub fn format_int_with_base(n: i64, base: i64) -> String { |
| 1157 | if n == 0 { |
| 1158 | return "0".to_string(); |
| 1159 | } |
| 1160 | let neg = n < 0; |
| 1161 | let mut m = (n as i128).unsigned_abs(); |
| 1162 | let b = base as u128; |
| 1163 | let mut digits = Vec::new(); |
| 1164 | while m > 0 { |
| 1165 | let d = (m % b) as u32; |
| 1166 | digits.push(std::char::from_digit(d, base as u32).unwrap_or('?')); |
| 1167 | m /= b; |
| 1168 | } |
| 1169 | let mut s = String::new(); |
| 1170 | if neg { |
| 1171 | s.push(MINUS); |
| 1172 | } |
| 1173 | s.extend(digits.iter().rev()); |
| 1174 | s |
| 1175 | } |
| 1176 | |
| 1177 | /// A float as it is displayed in text (`str(x)`, `[#x]`): no forced separator, a typographic minus, |
| 1178 | /// `NaN` and `∞`. |
| 1179 | pub fn display_float(f: f64) -> String { |
| 1180 | if f.is_nan() { |
| 1181 | return "NaN".to_string(); |
| 1182 | } |
| 1183 | if f.is_infinite() { |
| 1184 | return if f < 0.0 { fmt!("{}∞", MINUS) } else { "∞".to_string() }; |
| 1185 | } |
| 1186 | // Typst prints the magnitude, so a negative zero shows as `0`. |
| 1187 | if f < 0.0 { fmt!("{}{}", MINUS, f.abs()) } else { fmt!("{}", f.abs()) } |
| 1188 | } |
| 1189 | |
| 1190 | pub fn version_text(p: &[u32]) -> String { |
| 1191 | p.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(".") |
| 1192 | } |
| 1193 | |
| 1194 | // Rounding and number text |
| 1195 | |
| 1196 | /// Typst's `round_with_precision`: a no-op where rounding cannot change the value. |
| 1197 | pub fn round_with_precision(value: f64, precision: i16) -> f64 { |
| 1198 | if value.is_infinite() |
| 1199 | || value.is_nan() |
| 1200 | || (precision >= 0 && value.abs() >= (1u64 << 53) as f64) |
| 1201 | || precision >= 15 |
| 1202 | { |
| 1203 | return value; |
| 1204 | } |
| 1205 | if precision < -308 { |
| 1206 | return value * 0.0; |
| 1207 | } |
| 1208 | if precision > 0 { |
| 1209 | let offset = 10f64.powf(precision as f64); |
| 1210 | (value * offset).round() / offset |
| 1211 | } else { |
| 1212 | let offset = 10f64.powf(-(precision as f64)); |
| 1213 | (value / offset).round() * offset |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | /// Typst's `format_float`: optionally rounded, with a decimal separator forced for a bare float's repr. |
| 1218 | pub fn format_float(value: f64, precision: Option<u8>, force_separator: bool, suffix: &str) -> String { |
| 1219 | let v = match precision { |
| 1220 | Some(p) => round_with_precision(value, p as i16), |
| 1221 | None => value, |
| 1222 | }; |
| 1223 | // A unit after a non-finite number is written as a product: `float.inf * 1pt`. |
| 1224 | let times = if suffix.is_empty() { "" } else { " * 1" }; |
| 1225 | if v.is_nan() { |
| 1226 | return fmt!("float.nan{}{}", times, suffix); |
| 1227 | } |
| 1228 | if v.is_infinite() { |
| 1229 | return fmt!("{}float.inf{}{}", if v < 0.0 { "-" } else { "" }, times, suffix); |
| 1230 | } |
| 1231 | if force_separator { |
| 1232 | fmt!("{:?}{}", v, suffix) |
| 1233 | } else { |
| 1234 | fmt!("{}{}", v, suffix) |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | /// A unit-bearing number as `repr` prints it: two decimals at most, no forced separator. |
| 1239 | pub fn format_unit(value: f64, unit: &str) -> String { format_float(value, Some(2), false, unit) } |
| 1240 | |
| 1241 | pub fn repr_float(f: f64) -> String { |
| 1242 | if f.is_nan() { |
| 1243 | "float.nan".to_string() |
| 1244 | } else if f.is_infinite() { |
| 1245 | if f < 0.0 { "-float.inf".to_string() } else { "float.inf".to_string() } |
| 1246 | } else { |
| 1247 | format_float(f, None, true, "") |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | // repr |
| 1252 | |
| 1253 | // An array or dictionary longer than this prints its first items and a count of the rest. |
| 1254 | const REPR_MAX_ITEMS: usize = 40; |
| 1255 | |
| 1256 | /// `repr(value)`, as Typst prints it. |
| 1257 | pub fn repr(v: &Value) -> String { |
| 1258 | match v { |
| 1259 | Value::None => "none".to_string(), |
| 1260 | Value::Auto => "auto".to_string(), |
| 1261 | Value::Bool(b) => b.to_string(), |
| 1262 | Value::Int(i) => i.to_string(), |
| 1263 | Value::Float(f) => repr_float(*f), |
| 1264 | Value::Decimal(d) => fmt!("decimal({})", repr_str(&d.text())), |
| 1265 | Value::Length(l) => repr_length(l), |
| 1266 | Value::Angle(a) => repr_angle(*a), |
| 1267 | Value::Ratio(r) => repr_ratio(*r), |
| 1268 | Value::Relative(r) => fmt!("{} + {}", repr_ratio(r.rel), repr_length(&r.abs)), |
| 1269 | Value::Fraction(f) => repr_fraction(*f), |
| 1270 | Value::Color(c) => color::repr_color(c), |
| 1271 | Value::Gradient(g) => color::repr_gradient(g), |
| 1272 | Value::Tiling(t) => repr_tiling(t), |
| 1273 | Value::Stroke(s) => repr_stroke(s), |
| 1274 | Value::Alignment(a) => repr_alignment(a), |
| 1275 | Value::Direction(d) => direction_name(*d).to_string(), |
| 1276 | Value::Symbol(s) => sym::repr_symbol(s), |
| 1277 | Value::Str(s) => repr_str(s), |
| 1278 | Value::Bytes(b) => fmt!("bytes({})", b.len()), |
| 1279 | Value::Label(l) => repr_label(l), |
| 1280 | Value::Datetime(d) => repr_datetime(d), |
| 1281 | Value::Duration(d) => repr_duration(d), |
| 1282 | Value::Version(p) => fmt!("version{}", pretty_array_like( |
| 1283 | &p.iter().map(|x| x.to_string()).collect::<Vec<_>>(), false)), |
| 1284 | Value::Regex(r) => fmt!("regex({})", repr_str(&r.pattern)), |
| 1285 | Value::Content(c) => repr_content(c), |
| 1286 | Value::Array(a) => { |
| 1287 | let mut parts: Vec<String> = a.iter().take(REPR_MAX_ITEMS).map(repr).collect(); |
| 1288 | if a.len() > REPR_MAX_ITEMS { |
| 1289 | parts.push(fmt!(".. ({} items omitted)", a.len() - REPR_MAX_ITEMS)); |
| 1290 | } |
| 1291 | pretty_array_like(&parts, a.len() == 1) |
| 1292 | } |
| 1293 | Value::Dict(d) => repr_dict(d), |
| 1294 | Value::Func(f) => repr_func(f), |
| 1295 | Value::Args(a) => { |
| 1296 | let parts: Vec<String> = a.items.iter().map(|arg| match &arg.name { |
| 1297 | Some(n) => fmt!("{}: {}", n, repr(&arg.value)), |
| 1298 | None => repr(&arg.value), |
| 1299 | }).collect(); |
| 1300 | fmt!("arguments{}", pretty_array_like(&parts, false)) |
| 1301 | } |
| 1302 | Value::Module(m) if m.name.is_empty() => "<module>".to_string(), |
| 1303 | Value::Module(m) => fmt!("<module {}>", m.name), |
| 1304 | Value::Type(t) => match t { |
| 1305 | Type::None => "type(none)".to_string(), |
| 1306 | Type::Auto => "type(auto)".to_string(), |
| 1307 | other => other.name().to_string(), |
| 1308 | }, |
| 1309 | Value::Styles(_) => "..".to_string(), |
| 1310 | Value::Selector(s) => repr_selector(s), |
| 1311 | Value::Counter(c) => repr_counter(c), |
| 1312 | Value::State(s) => repr_state(s), |
| 1313 | Value::Location(_) => "location(..)".to_string(), |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | pub fn repr_length(l: &Length) -> String { |
| 1318 | match (l.abs == 0.0, l.em == 0.0) { |
| 1319 | (false, false) => fmt!("{} + {}", format_unit(l.abs, "pt"), format_unit(l.em, "em")), |
| 1320 | (true, false) => format_unit(l.em, "em"), |
| 1321 | (_, true) => format_unit(l.abs, "pt"), |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | pub fn repr_angle(a: Angle) -> String { format_unit(a.0.to_degrees(), "deg") } |
| 1326 | |
| 1327 | pub fn repr_ratio(r: Ratio) -> String { format_unit(r.0 * 100.0, "%") } |
| 1328 | |
| 1329 | pub fn repr_fraction(f: Fraction) -> String { format_unit(f.0, "fr") } |
| 1330 | |
| 1331 | pub fn direction_name(d: Direction) -> &'static str { |
| 1332 | match d { |
| 1333 | Direction::Ltr => "ltr", |
| 1334 | Direction::Rtl => "rtl", |
| 1335 | Direction::Ttb => "ttb", |
| 1336 | Direction::Btt => "btt", |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | pub fn halign_name(h: HAlign) -> &'static str { |
| 1341 | match h { |
| 1342 | HAlign::Start => "start", |
| 1343 | HAlign::Left => "left", |
| 1344 | HAlign::Center => "center", |
| 1345 | HAlign::Right => "right", |
| 1346 | HAlign::End => "end", |
| 1347 | } |
| 1348 | } |
| 1349 | |
| 1350 | pub fn valign_name(v: VAlign) -> &'static str { |
| 1351 | match v { |
| 1352 | VAlign::Top => "top", |
| 1353 | VAlign::Horizon => "horizon", |
| 1354 | VAlign::Bottom => "bottom", |
| 1355 | } |
| 1356 | } |
| 1357 | |
| 1358 | fn repr_alignment(a: &Alignment) -> String { |
| 1359 | match (a.x, a.y) { |
| 1360 | (Some(x), Some(y)) => fmt!("{} + {}", halign_name(x), valign_name(y)), |
| 1361 | (Some(x), None) => halign_name(x).to_string(), |
| 1362 | (None, Some(y)) => valign_name(y).to_string(), |
| 1363 | (None, None) => "start".to_string(), |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | /// A string literal as Typst's `repr` writes it. |
| 1368 | pub fn repr_str(s: &str) -> String { |
| 1369 | let mut out = String::with_capacity(s.len() + 2); |
| 1370 | out.push('"'); |
| 1371 | for c in s.chars() { |
| 1372 | match c { |
| 1373 | '\0' => out.push_str("\\u{0}"), |
| 1374 | '\'' => out.push('\''), |
| 1375 | '"' => out.push_str("\\\""), |
| 1376 | '\\' => out.push_str("\\\\"), |
| 1377 | '\n' => out.push_str("\\n"), |
| 1378 | '\r' => out.push_str("\\r"), |
| 1379 | '\t' => out.push_str("\\t"), |
| 1380 | c if is_unprintable(c) => out.push_str(&fmt!("\\u{{{:x}}}", c as u32)), |
| 1381 | c => out.push(c), |
| 1382 | } |
| 1383 | } |
| 1384 | out.push('"'); |
| 1385 | out |
| 1386 | } |
| 1387 | |
| 1388 | /// Would Rust's `escape_debug` (which Typst's `repr` uses) escape the character? Decided from the |
| 1389 | /// Unicode 17 grapheme tables in `fe2o3_text` rather than the toolchain's own, so the answer follows |
| 1390 | /// the Unicode version Typst is built with: controls, format characters, line and paragraph separators, |
| 1391 | /// grapheme extenders (not emoji modifiers), non-ASCII spaces and private use. Unassigned code points |
| 1392 | /// are printed, which Rust would escape; the tables do not say which are unassigned. |
| 1393 | pub fn is_unprintable(c: char) -> bool { |
| 1394 | use oxedyne_fe2o3_text::unicode::lookup; |
| 1395 | use oxedyne_fe2o3_text::unicode::tables::prop::GraphemeClass; |
| 1396 | use oxedyne_fe2o3_text::unicode::tables::seg::{ |
| 1397 | GCB_STARTS, |
| 1398 | GCB_VALS, |
| 1399 | }; |
| 1400 | let u = c as u32; |
| 1401 | if matches!(u, 0x1F3FB..=0x1F3FF) { |
| 1402 | return false; |
| 1403 | } |
| 1404 | let class = lookup::get(&GCB_VALS, lookup::run(&GCB_STARTS, c), GraphemeClass::Other); |
| 1405 | matches!(class, GraphemeClass::Control | GraphemeClass::CR | GraphemeClass::LF |
| 1406 | | GraphemeClass::Extend | GraphemeClass::ZWJ) |
| 1407 | || matches!(u, 0x600..=0x605 | 0x6DD | 0x70F | 0x890..=0x891 | 0x8E2 | 0x110BD | 0x110CD) |
| 1408 | || matches!(u, 0xA0 | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000) |
| 1409 | || matches!(u, 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD) |
| 1410 | } |
| 1411 | |
| 1412 | /// Can `s` be written as a bare identifier (a dict key without quotes)? Typst's own rule: XID_Start or |
| 1413 | /// `_`, then XID_Continue, `_` or `-`. |
| 1414 | pub fn is_ident(s: &str) -> bool { crate::syntax::lexer::is_ident(s) } |
| 1415 | |
| 1416 | fn repr_label(l: &Label) -> String { |
| 1417 | let s = l.as_str(); |
| 1418 | if crate::syntax::lexer::is_valid_label_literal_id(s) { |
| 1419 | fmt!("<{}>", s) |
| 1420 | } else { |
| 1421 | fmt!("label({})", repr_str(s)) |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | fn repr_dict(d: &Dict) -> String { |
| 1426 | if d.is_empty() { |
| 1427 | return "(:)".to_string(); |
| 1428 | } |
| 1429 | let mut parts: Vec<String> = d.iter().take(REPR_MAX_ITEMS).map(|(k, v)| { |
| 1430 | let key = if is_ident(k) { k.to_string() } else { repr_str(k) }; |
| 1431 | fmt!("{}: {}", key, repr(v)) |
| 1432 | }).collect(); |
| 1433 | if d.len() > REPR_MAX_ITEMS { |
| 1434 | parts.push(fmt!(".. ({} pairs omitted)", d.len() - REPR_MAX_ITEMS)); |
| 1435 | } |
| 1436 | pretty_array_like(&parts, false) |
| 1437 | } |
| 1438 | |
| 1439 | fn repr_func(f: &Func) -> String { |
| 1440 | match f { |
| 1441 | Func::Native(n) => n.name().to_string(), |
| 1442 | Func::Element(k) => k.name().to_string(), |
| 1443 | Func::Closure(c) => match c.name() { |
| 1444 | Some(n) => n.to_string(), |
| 1445 | None => "(..) => ..".to_string(), |
| 1446 | }, |
| 1447 | Func::With(_) => "(..) => ..".to_string(), |
| 1448 | #[cfg(feature = "plugin")] |
| 1449 | Func::Plugin(p) => p.name().to_string(), |
| 1450 | } |
| 1451 | } |
| 1452 | |
| 1453 | fn repr_datetime(d: &Datetime) -> String { |
| 1454 | let mut parts = Vec::new(); |
| 1455 | let fields = [ |
| 1456 | ("year", d.year.map(|y| y as i64)), ("month", d.month.map(|x| x as i64)), |
| 1457 | ("day", d.day.map(|x| x as i64)), ("hour", d.hour.map(|x| x as i64)), |
| 1458 | ("minute", d.minute.map(|x| x as i64)), ("second", d.second.map(|x| x as i64)), |
| 1459 | ]; |
| 1460 | for (n, v) in fields { |
| 1461 | if let Some(v) = v { |
| 1462 | parts.push(fmt!("{}: {}", n, v)); |
| 1463 | } |
| 1464 | } |
| 1465 | fmt!("datetime{}", pretty_array_like(&parts, false)) |
| 1466 | } |
| 1467 | |
| 1468 | fn repr_duration(d: &Duration) -> String { |
| 1469 | let total = d.secs.trunc() as i64; |
| 1470 | if total == 0 { |
| 1471 | return "duration()".to_string(); |
| 1472 | } |
| 1473 | let mut rest = total; |
| 1474 | let mut parts = Vec::new(); |
| 1475 | for (n, unit) in [("weeks", 604_800i64), ("days", 86_400), ("hours", 3_600), ("minutes", 60), ("seconds", 1)] { |
| 1476 | let q = rest / unit; |
| 1477 | rest -= q * unit; |
| 1478 | if q != 0 { |
| 1479 | parts.push(fmt!("{}: {}", n, q)); |
| 1480 | } |
| 1481 | } |
| 1482 | fmt!("duration{}", pretty_array_like(&parts, false)) |
| 1483 | } |
| 1484 | |
| 1485 | fn repr_tiling(t: &Tiling) -> String { |
| 1486 | let mut parts = Vec::new(); |
| 1487 | if let Some((w, h)) = t.size { |
| 1488 | parts.push(fmt!("size: ({}, {})", repr_length(&w), repr_length(&h))); |
| 1489 | } |
| 1490 | parts.push(fmt!("spacing: ({}, {})", repr_length(&t.spacing.0), repr_length(&t.spacing.1))); |
| 1491 | parts.push(fmt!("relative: {}", relative_to_repr(t.relative))); |
| 1492 | parts.push(fmt!("body: {}", repr_content(&t.body))); |
| 1493 | fmt!("tiling{}", pretty_array_like(&parts, false)) |
| 1494 | } |
| 1495 | |
| 1496 | pub fn relative_to_repr(r: crate::eval::value::RelativeTo) -> String { |
| 1497 | use crate::eval::value::RelativeTo; |
| 1498 | match r { |
| 1499 | RelativeTo::Auto => "auto".to_string(), |
| 1500 | RelativeTo::SelfBox => repr_str("self"), |
| 1501 | RelativeTo::Parent => repr_str("parent"), |
| 1502 | } |
| 1503 | } |
| 1504 | |
| 1505 | pub fn repr_paint(p: &Paint) -> String { repr(&paint_value(p)) } |
| 1506 | |
| 1507 | fn repr_stroke(s: &Stroke) -> String { |
| 1508 | if s.cap.is_none() && s.join.is_none() && s.dash.is_none() && s.miter_limit.is_none() { |
| 1509 | return match (&s.paint, &s.thickness) { |
| 1510 | (Some(p), Some(t)) => fmt!("{} + {}", repr_length(t), repr_paint(p)), |
| 1511 | (Some(p), None) => repr_paint(p), |
| 1512 | (None, Some(t)) => repr_length(t), |
| 1513 | (None, None) => "1pt + black".to_string(), |
| 1514 | }; |
| 1515 | } |
| 1516 | let mut parts = Vec::new(); |
| 1517 | if let Some(p) = &s.paint { |
| 1518 | parts.push(fmt!("paint: {}", repr_paint(p))); |
| 1519 | } |
| 1520 | if let Some(t) = &s.thickness { |
| 1521 | parts.push(fmt!("thickness: {}", repr_length(t))); |
| 1522 | } |
| 1523 | if let Some(c) = s.cap { |
| 1524 | parts.push(fmt!("cap: {}", repr_str(cap_name(c)))); |
| 1525 | } |
| 1526 | if let Some(j) = s.join { |
| 1527 | parts.push(fmt!("join: {}", repr_str(join_name(j)))); |
| 1528 | } |
| 1529 | if let Some(d) = &s.dash { |
| 1530 | match d { |
| 1531 | None => parts.push("dash: none".to_string()), |
| 1532 | Some(d) => parts.push(fmt!("dash: {}", repr(&dash_value(d)))), |
| 1533 | } |
| 1534 | } |
| 1535 | if let Some(m) = s.miter_limit { |
| 1536 | parts.push(fmt!("miter-limit: {}", repr_float(m))); |
| 1537 | } |
| 1538 | fmt!("({})", parts.join(", ")) |
| 1539 | } |
| 1540 | |
| 1541 | fn repr_selector(s: &Selector) -> String { |
| 1542 | match s { |
| 1543 | Selector::Elem(k, None) => k.name().to_string(), |
| 1544 | Selector::Elem(k, Some(fields)) => { |
| 1545 | let parts: Vec<String> = fields.iter().map(|(id, v)| { |
| 1546 | let name = k.field_spec(*id).map(|f| f.name).unwrap_or("?"); |
| 1547 | fmt!("{}: {}", name, repr(v)) |
| 1548 | }).collect(); |
| 1549 | fmt!("{}.where{}", k.name(), pretty_array_like(&parts, false)) |
| 1550 | } |
| 1551 | Selector::Label(l) => repr_label(l), |
| 1552 | Selector::Text(t) => repr_str(t), |
| 1553 | Selector::Regex(r) => fmt!("regex({})", repr_str(&r.pattern)), |
| 1554 | Selector::Location(_) => "location(..)".to_string(), |
| 1555 | Selector::Or(v) => fmt!("selector.or{}", pretty_array_like( |
| 1556 | &v.iter().map(repr_selector).collect::<Vec<_>>(), false)), |
| 1557 | Selector::And(v) => fmt!("selector.and{}", pretty_array_like( |
| 1558 | &v.iter().map(repr_selector).collect::<Vec<_>>(), false)), |
| 1559 | Selector::Before { selector, end, inclusive } => fmt!("{}.before({}{})", |
| 1560 | repr_selector(selector), repr_selector(end), if *inclusive { "" } else { ", inclusive: false" }), |
| 1561 | Selector::After { selector, start, inclusive } => fmt!("{}.after({}{})", |
| 1562 | repr_selector(selector), repr_selector(start), if *inclusive { "" } else { ", inclusive: false" }), |
| 1563 | } |
| 1564 | } |
| 1565 | |
| 1566 | fn repr_counter(c: &Counter) -> String { |
| 1567 | match &c.key { |
| 1568 | CounterKey::Page => "counter(page)".to_string(), |
| 1569 | CounterKey::Selector(s) => fmt!("counter({})", repr_selector(s)), |
| 1570 | CounterKey::Str(s) => fmt!("counter({})", repr_str(s)), |
| 1571 | } |
| 1572 | } |
| 1573 | |
| 1574 | fn repr_state(s: &State) -> String { fmt!("state({}, {})", repr_str(&s.key), repr(&s.init)) } |
| 1575 | |
| 1576 | /// Content as Typst's `repr` prints it: `[text]`, `[ ]` for a space, `sequence(..)`, and an element as |
| 1577 | /// its name with its set fields in schema order. |
| 1578 | pub fn repr_content(c: &Content) -> String { |
| 1579 | match c { |
| 1580 | Content::Sequence(s) => { |
| 1581 | if s.children.is_empty() { |
| 1582 | "[]".to_string() |
| 1583 | } else { |
| 1584 | let parts: Vec<String> = s.children.iter().map(repr_content).collect(); |
| 1585 | fmt!("sequence{}", pretty_array_like(&parts, false)) |
| 1586 | } |
| 1587 | } |
| 1588 | Content::Styled(s) => fmt!("styled(child: {}, ..)", repr_content(&s.child)), |
| 1589 | Content::Elem(e) => match e.kind { |
| 1590 | // A symbol element reprs as plain content does, as its text in brackets. |
| 1591 | ElemKind::Text | ElemKind::Symbol => match c.field("text").or_else(|| c.get(crate::eval::content::FieldId(0))) { |
| 1592 | Some(Value::Str(t)) => fmt!("[{}]", t), |
| 1593 | _ => "[]".to_string(), |
| 1594 | }, |
| 1595 | ElemKind::Space => "[ ]".to_string(), |
| 1596 | kind => { |
| 1597 | let specs = kind.fields(); |
| 1598 | let mut parts = Vec::new(); |
| 1599 | for (i, spec) in specs.iter().enumerate() { |
| 1600 | let id = crate::eval::content::FieldId(i as u8); |
| 1601 | if let Some((_, v)) = e.fields.iter().find(|(f, _)| *f == id) { |
| 1602 | parts.push(fmt!("{}: {}", spec.name, repr(v))); |
| 1603 | } |
| 1604 | } |
| 1605 | // Fields outside the schema (a unit still filling its table) keep their ids. |
| 1606 | for (id, v) in &e.fields { |
| 1607 | if (id.0 as usize) >= specs.len() { |
| 1608 | parts.push(fmt!("{}: {}", id.0, repr(v))); |
| 1609 | } |
| 1610 | } |
| 1611 | fmt!("{}{}", kind.name(), pretty_array_like(&parts, false)) |
| 1612 | } |
| 1613 | }, |
| 1614 | } |
| 1615 | } |
| 1616 | |
| 1617 | // Pretty printing |
| 1618 | |
| 1619 | const MAX_WIDTH: usize = 50; |
| 1620 | |
| 1621 | /// Joins pieces with commas, one per line once they exceed Typst's fifty-byte width. |
| 1622 | pub fn pretty_comma_list(pieces: &[String], trailing_comma: bool) -> String { |
| 1623 | let len: usize = pieces.iter().map(|s| s.len()).sum::<usize>() + 2 * pieces.len().saturating_sub(1); |
| 1624 | let mut buf = String::new(); |
| 1625 | if len <= MAX_WIDTH { |
| 1626 | buf.push_str(&pieces.join(", ")); |
| 1627 | if trailing_comma { |
| 1628 | buf.push(','); |
| 1629 | } |
| 1630 | } else { |
| 1631 | for p in pieces { |
| 1632 | buf.push_str(p.trim()); |
| 1633 | buf.push_str(",\n"); |
| 1634 | } |
| 1635 | } |
| 1636 | buf |
| 1637 | } |
| 1638 | |
| 1639 | /// A parenthesised list, wrapped and indented as Typst's `repr` wraps arrays, dicts and arguments. |
| 1640 | pub fn pretty_array_like(parts: &[String], trailing_comma: bool) -> String { |
| 1641 | let list = pretty_comma_list(parts, trailing_comma); |
| 1642 | let mut buf = String::from("("); |
| 1643 | if list.contains('\n') { |
| 1644 | buf.push('\n'); |
| 1645 | for (i, line) in list.lines().enumerate() { |
| 1646 | if i > 0 { |
| 1647 | buf.push('\n'); |
| 1648 | } |
| 1649 | buf.push_str(" "); |
| 1650 | buf.push_str(line); |
| 1651 | } |
| 1652 | buf.push('\n'); |
| 1653 | } else { |
| 1654 | buf.push_str(&list); |
| 1655 | } |
| 1656 | buf.push(')'); |
| 1657 | buf |
| 1658 | } |
| 1659 | |
| 1660 | /// Converts a value to content text as Typst displays a value in markup: strings as they are, numbers |
| 1661 | /// with a typographic minus, `none` as nothing. `None` for values that display as themselves (content). |
| 1662 | pub fn display(v: &Value) -> Option<String> { |
| 1663 | let s = match v { |
| 1664 | Value::None => String::new(), |
| 1665 | Value::Str(s) => (**s).clone(), |
| 1666 | Value::Int(i) => format_int_with_base(*i, 10), |
| 1667 | Value::Float(f) => display_float(*f), |
| 1668 | Value::Decimal(d) => d.display(), |
| 1669 | Value::Version(p) => version_text(p), |
| 1670 | Value::Symbol(s) => sym::text(s).to_string(), |
| 1671 | Value::Label(_) | Value::Content(_) => return None, |
| 1672 | other => repr(other), |
| 1673 | }; |
| 1674 | Some(s) |
| 1675 | } |
| 1676 | |
| 1677 | // The bytes a plugin function is given: every argument positional and of type bytes. |
| 1678 | #[cfg(feature = "plugin")] |
| 1679 | fn plugin_args(engine: &mut Engine, args: Args) -> Outcome<Vec<Arc<Vec<u8>>>> { |
| 1680 | let mut out = Vec::with_capacity(args.items.len()); |
| 1681 | for a in args.items { |
| 1682 | if let Some(n) = &a.name { |
| 1683 | return Err(engine.error(DiagnosticKind::Type, a.span, fmt!("unexpected argument: {}", n))); |
| 1684 | } |
| 1685 | match a.value { |
| 1686 | Value::Bytes(b) => out.push(b), |
| 1687 | other => return Err(mismatch(engine, a.value_span, "bytes", &other)), |
| 1688 | } |
| 1689 | } |
| 1690 | Ok(out) |
| 1691 | } |
| 1692 | |
| 1693 | // A plugin's failure as a diagnostic: Typst's message as the runtime words it, and a limit of Austenite's |
| 1694 | // named as a limit. |
| 1695 | #[cfg(feature = "plugin")] |
| 1696 | fn plugin_error(engine: &mut Engine, span: Span, e: Error<ErrTag>) -> Error<ErrTag> { |
| 1697 | let kind = if e.tags().contains(&ErrTag::LimitReached) { DiagnosticKind::Limit } else { DiagnosticKind::Type }; |
| 1698 | let msg = e.msgs().last().cloned().unwrap_or_default(); |
| 1699 | engine.error(kind, span, msg) |
| 1700 | } |
| 1701 | |
| 1702 | /// `p.name(..args)`: runs an exported function of a plugin on its bytes, answering bytes. |
| 1703 | #[cfg(feature = "plugin")] |
| 1704 | pub fn call_plugin(engine: &mut Engine, p: &crate::eval::plugin::PluginFunc, args: Args) -> Outcome<Value> { |
| 1705 | let span = args.span; |
| 1706 | let bytes = res!(plugin_args(engine, args)); |
| 1707 | match engine.caches.plugin_call(p, bytes, engine.plugin_fuel) { |
| 1708 | Ok(out) => Ok(Value::Bytes(out)), |
| 1709 | Err(e) => Err(plugin_error(engine, span, e)), |
| 1710 | } |
| 1711 | } |