Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/value.rs

20.7 KiB, 23 runs

created by r1870400018:63516, 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// U0 owns this file. Every heap payload is behind an `Arc`, so a `Value` clones in constant time;
2// mutate through `Arc::make_mut` (copy on write). Equality and ordering are Typst's and live in `ops.rs`,
3// which is why `Value` does not derive `PartialEq`.
4
5use crate::eval::args::Args;
6use crate::eval::content::Content;
7use crate::eval::func::Func;
8use crate::eval::lib::decimal::Decimal;
9use crate::eval::lib::foundations::{
10 as_func,
11 func_refusal,
12};
13use crate::eval::intro::{
14 Counter,
15 State,
16};
17use crate::eval::locate::Location;
18use crate::eval::scope::Scope;
19use crate::eval::select::Selector;
20use crate::eval::styles::Styles;
21
22use oxedyne_fe2o3_core::prelude::*;
23use oxedyne_fe2o3_text::regex::Regex;
24
25use std::collections::HashMap;
26use std::sync::Arc;
27
28#[derive(Clone, Debug, Default)]
29pub enum Value {
30 #[default]
31 None,
32 Auto,
33 Bool(bool),
34 Int(i64),
35 Float(f64),
36 Decimal(Decimal),
37 Length(Length),
38 Angle(Angle),
39 Ratio(Ratio),
40 Relative(Relative),
41 Fraction(Fraction),
42 Color(Color),
43 Gradient(Arc<Gradient>),
44 Tiling(Arc<Tiling>),
45 Stroke(Arc<Stroke>),
46 Alignment(Alignment),
47 Direction(Direction),
48 Symbol(Symbol),
49 Str(Arc<String>),
50 Bytes(Arc<Vec<u8>>),
51 Label(Label),
52 Datetime(Datetime),
53 Duration(Duration),
54 Version(Arc<Vec<u32>>),
55 Regex(Arc<RegexValue>),
56 Content(Content),
57 Array(Arc<Vec<Value>>),
58 Dict(Arc<Dict>),
59 Func(Func),
60 Args(Arc<Args>),
61 Module(Arc<Module>),
62 Type(Type),
63 Styles(Styles),
64 Selector(Arc<Selector>),
65 Counter(Arc<Counter>),
66 State(Arc<State>),
67 Location(Location),
68}
69
70/// The type of a value, itself a value (`type(1) == int`) and, for most types, a constructor.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
72pub enum Type {
73 None,
74 Auto,
75 Bool,
76 Int,
77 Float,
78 Decimal,
79 Length,
80 Angle,
81 Ratio,
82 Relative,
83 Fraction,
84 Color,
85 Gradient,
86 Tiling,
87 Stroke,
88 Alignment,
89 Direction,
90 Symbol,
91 Str,
92 Bytes,
93 Label,
94 Datetime,
95 Duration,
96 Version,
97 Regex,
98 Content,
99 Array,
100 Dict,
101 Func,
102 Args,
103 Module,
104 Type,
105 Styles,
106 Selector,
107 Counter,
108 State,
109 Location,
110}
111
112impl Type {
113 // Every type, Typst's registry of them, in the order they are declared.
114 pub const ALL: [Type; 37] = [
115 Type::None, Type::Auto, Type::Bool, Type::Int, Type::Float, Type::Decimal, Type::Length, Type::Angle,
116 Type::Ratio, Type::Relative, Type::Fraction, Type::Color, Type::Gradient, Type::Tiling, Type::Stroke,
117 Type::Alignment, Type::Direction, Type::Symbol, Type::Str, Type::Bytes, Type::Label, Type::Datetime,
118 Type::Duration, Type::Version, Type::Regex, Type::Content, Type::Array, Type::Dict, Type::Func,
119 Type::Args, Type::Module, Type::Type, Type::Styles, Type::Selector, Type::Counter, Type::State,
120 Type::Location,
121 ];
122
123 /// The type a name stands for, in either spelling: `int` or `integer`, `relative` or `relative length`.
124 pub fn from_name(name: &str) -> Option<Type> {
125 Self::ALL.iter().copied().find(|t| t.name() == name || t.long_name() == name)
126 }
127
128 /// The name `repr(type(x))` prints.
129 pub fn name(self) -> &'static str {
130 match self {
131 Type::None => "none",
132 Type::Auto => "auto",
133 Type::Bool => "bool",
134 Type::Int => "int",
135 Type::Float => "float",
136 Type::Decimal => "decimal",
137 Type::Length => "length",
138 Type::Angle => "angle",
139 Type::Ratio => "ratio",
140 Type::Relative => "relative",
141 Type::Fraction => "fraction",
142 Type::Color => "color",
143 Type::Gradient => "gradient",
144 Type::Tiling => "tiling",
145 Type::Stroke => "stroke",
146 Type::Alignment => "alignment",
147 Type::Direction => "direction",
148 Type::Symbol => "symbol",
149 Type::Str => "str",
150 Type::Bytes => "bytes",
151 Type::Label => "label",
152 Type::Datetime => "datetime",
153 Type::Duration => "duration",
154 Type::Version => "version",
155 Type::Regex => "regex",
156 Type::Content => "content",
157 Type::Array => "array",
158 Type::Dict => "dictionary",
159 Type::Func => "function",
160 Type::Args => "arguments",
161 Type::Module => "module",
162 Type::Type => "type",
163 Type::Styles => "styles",
164 Type::Selector => "selector",
165 Type::Counter => "counter",
166 Type::State => "state",
167 Type::Location => "location",
168 }
169 }
170
171 /// The name `str(type(x))` prints and error messages use: `integer` where `repr` says `int`.
172 pub fn long_name(self) -> &'static str {
173 match self {
174 Type::Bool => "boolean",
175 Type::Int => "integer",
176 Type::Str => "string",
177 Type::Relative => "relative length",
178 other => other.name(),
179 }
180 }
181}
182
183impl Value {
184 pub fn ty(&self) -> Type {
185 match self {
186 Value::None => Type::None,
187 Value::Auto => Type::Auto,
188 Value::Bool(_) => Type::Bool,
189 Value::Int(_) => Type::Int,
190 Value::Float(_) => Type::Float,
191 Value::Decimal(_) => Type::Decimal,
192 Value::Length(_) => Type::Length,
193 Value::Angle(_) => Type::Angle,
194 Value::Ratio(_) => Type::Ratio,
195 Value::Relative(_) => Type::Relative,
196 Value::Fraction(_) => Type::Fraction,
197 Value::Color(_) => Type::Color,
198 Value::Gradient(_) => Type::Gradient,
199 Value::Tiling(_) => Type::Tiling,
200 Value::Stroke(_) => Type::Stroke,
201 Value::Alignment(_) => Type::Alignment,
202 Value::Direction(_) => Type::Direction,
203 Value::Symbol(_) => Type::Symbol,
204 Value::Str(_) => Type::Str,
205 Value::Bytes(_) => Type::Bytes,
206 Value::Label(_) => Type::Label,
207 Value::Datetime(_) => Type::Datetime,
208 Value::Duration(_) => Type::Duration,
209 Value::Version(_) => Type::Version,
210 Value::Regex(_) => Type::Regex,
211 Value::Content(_) => Type::Content,
212 Value::Array(_) => Type::Array,
213 Value::Dict(_) => Type::Dict,
214 Value::Func(_) => Type::Func,
215 Value::Args(_) => Type::Args,
216 Value::Module(_) => Type::Module,
217 Value::Type(_) => Type::Type,
218 Value::Styles(_) => Type::Styles,
219 Value::Selector(_) => Type::Selector,
220 Value::Counter(_) => Type::Counter,
221 Value::State(_) => Type::State,
222 Value::Location(_) => Type::Location,
223 }
224 }
225
226 pub fn str<S: Into<String>>(s: S) -> Self { Value::Str(Arc::new(s.into())) }
227
228 pub fn array(v: Vec<Value>) -> Self { Value::Array(Arc::new(v)) }
229
230 pub fn dict(d: Dict) -> Self { Value::Dict(Arc::new(d)) }
231
232 /// The string a value casts to where Typst expects a `str`: a string itself, or the text of a symbol with
233 /// its modifiers applied (`sym.arrow.r` is "→"). No other type casts.
234 pub fn str_cast(&self) -> Option<Arc<String>> {
235 match self {
236 Value::Str(s) => Some(s.clone()),
237 Value::Symbol(s) => Some(Arc::new(crate::eval::lib::sym::text(s).to_string())),
238 _ => None,
239 }
240 }
241
242 /// A symbol as the string it casts to, any other value unchanged: for a `match` where a string is one of
243 /// several types a parameter takes, as in `bytes`.
244 pub fn symbol_as_str(self) -> Value {
245 match self {
246 Value::Symbol(_) => match self.str_cast() {
247 Some(s) => Value::Str(s),
248 None => self,
249 },
250 other => other,
251 }
252 }
253
254 pub fn is_none(&self) -> bool { matches!(self, Value::None) }
255
256 pub fn is_auto(&self) -> bool { matches!(self, Value::Auto) }
257
258 /// Casts to `T`, the error naming the expected and the found type.
259 pub fn cast<T: FromValue>(self) -> Outcome<T> { T::from_value(self) }
260}
261
262// Units
263
264/// A length whose `em` part stays unresolved until realisation knows the font size, as in Typst. The
265/// conversion to [`crate::ir::Sp`] happens at the flow boundary.
266#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
267pub struct Length {
268 pub abs: f64, // points
269 pub em: f64, // multiples of the font size
270}
271
272impl Length {
273 pub fn pt(abs: f64) -> Self { Self { abs, em: 0.0 } }
274 pub fn em(em: f64) -> Self { Self { abs: 0.0, em } }
275 pub fn zero() -> Self { Self::default() }
276
277 /// The absolute length at a font size, in points.
278 pub fn resolve(&self, font_size_pt: f64) -> f64 { self.abs + self.em * font_size_pt }
279}
280
281#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
282pub struct Angle(pub f64); // radians
283
284#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
285pub struct Ratio(pub f64); // 1.0 is 100%
286
287#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
288pub struct Fraction(pub f64); // 1.0 is 1fr
289
290/// `50% + 1em`: a ratio of the containing size plus a length.
291#[derive(Clone, Copy, Debug, Default, PartialEq)]
292pub struct Relative {
293 pub rel: Ratio,
294 pub abs: Length,
295}
296
297impl Relative {
298 /// The absolute length against a containing size and a font size, both in points.
299 pub fn resolve(&self, whole_pt: f64, font_size_pt: f64) -> f64 {
300 self.rel.0 * whole_pt + self.abs.resolve(font_size_pt)
301 }
302}
303
304// Colour and paint
305
306#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
307pub enum ColorSpace {
308 Luma,
309 Oklab,
310 Oklch,
311 LinearRgb,
312 Rgb,
313 Cmyk,
314 Hsl,
315 Hsv,
316}
317
318/// A colour in the space it was written in, so `repr`, `components` and `mix` round-trip as Typst's
319/// do. Components are in the space's own order and range (percentages as 0..=1, hue in degrees); `alpha`
320/// is 0..=1 and absent for cmyk. Conversion to [`fe2o3_graphics::colour::Rgba`] is `lib/color.rs` (U3).
321#[derive(Clone, Copy, Debug, PartialEq)]
322pub struct Color {
323 pub space: ColorSpace,
324 pub c: [f32; 4],
325 pub alpha: f32,
326}
327
328#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
329pub enum RelativeTo {
330 Auto,
331 SelfBox, // "self"
332 Parent,
333}
334
335#[derive(Clone, Debug, PartialEq)]
336pub enum GradientKind {
337 Linear { angle: Angle },
338 Radial { center: (Ratio, Ratio), radius: Ratio, focal_center: (Ratio, Ratio), focal_radius: Ratio },
339 Conic { center: (Ratio, Ratio), angle: Angle },
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub struct Gradient {
344 pub kind: GradientKind,
345 pub stops: Vec<(Color, Ratio)>,
346 pub space: ColorSpace, // the space interpolation runs in
347 pub relative: RelativeTo,
348}
349
350#[derive(Clone, Debug)]
351pub struct Tiling {
352 pub body: Content,
353 pub size: Option<(Length, Length)>, // None: auto, the body's own size
354 pub spacing: (Length, Length),
355 pub relative: RelativeTo,
356}
357
358#[derive(Clone, Debug)]
359pub enum Paint {
360 Color(Color),
361 Gradient(Arc<Gradient>),
362 Tiling(Arc<Tiling>),
363}
364
365#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
366pub enum LineCap {
367 Butt,
368 Round,
369 Square,
370}
371
372#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
373pub enum LineJoin {
374 Miter,
375 Round,
376 Bevel,
377}
378
379#[derive(Clone, Copy, Debug, PartialEq)]
380pub enum DashItem {
381 Len(Length),
382 Dot,
383}
384
385#[derive(Clone, Debug, PartialEq)]
386pub struct Dash {
387 pub array: Vec<DashItem>,
388 pub phase: Length,
389}
390
391/// A stroke as written: every part optional, because `set` folds partial strokes onto one another
392/// (`stroke: red` then `stroke: 2pt` gives a red 2pt stroke). `dash: Some(None)` is an explicit solid.
393#[derive(Clone, Debug, Default)]
394pub struct Stroke {
395 pub paint: Option<Paint>,
396 pub thickness: Option<Length>,
397 pub cap: Option<LineCap>,
398 pub join: Option<LineJoin>,
399 pub dash: Option<Option<Dash>>,
400 pub miter_limit: Option<f64>,
401}
402
403// Layout vocabulary
404
405#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
406pub enum HAlign {
407 Start,
408 Left,
409 Center,
410 Right,
411 End,
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
415pub enum VAlign {
416 Top,
417 Horizon,
418 Bottom,
419}
420
421/// `left`, `top`, or `left + top`: either axis may be absent.
422#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
423pub struct Alignment {
424 pub x: Option<HAlign>,
425 pub y: Option<VAlign>,
426}
427
428#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
429pub enum Direction {
430 Ltr,
431 Rtl,
432 Ttb,
433 Btt,
434}
435
436// Text-ish values
437
438#[derive(Clone, Debug)]
439pub enum SymVariants {
440 Single(&'static str),
441 Static(&'static [(&'static str, &'static str)]), // (dot-joined modifiers, text), the default first
442 Runtime(Arc<Vec<(String, String)>>), // from `symbol(...)`
443}
444
445/// A symbol and the modifiers applied so far (`arrow.r.long` is `arrow` with "r.long").
446#[derive(Clone, Debug)]
447pub struct Symbol {
448 pub variants: SymVariants,
449 pub modifiers: Arc<String>,
450}
451
452#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
453pub struct Label(pub Arc<str>);
454
455impl Label {
456 pub fn new(s: &str) -> Self { Label(Arc::from(s)) }
457 pub fn as_str(&self) -> &str { &self.0 }
458}
459
460/// A compiled `regex(...)`: the pattern as written, for `repr` and equality, and the `fe2o3_text` engine.
461#[derive(Clone, Debug)]
462pub struct RegexValue {
463 pub pattern: String,
464 pub re: Regex,
465}
466
467impl RegexValue {
468 pub fn new(pattern: &str) -> Outcome<Self> {
469 let re = res!(Regex::new(pattern));
470 Ok(Self { pattern: pattern.to_string(), re })
471 }
472}
473
474/// A date, a time, or both, each part present or absent as Typst's `datetime` allows.
475#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
476pub struct Datetime {
477 pub year: Option<i32>,
478 pub month: Option<u8>,
479 pub day: Option<u8>,
480 pub hour: Option<u8>,
481 pub minute: Option<u8>,
482 pub second: Option<u8>,
483}
484
485#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
486pub struct Duration {
487 pub secs: f64,
488}
489
490// Collections
491
492/// An insertion-ordered dictionary: Typst iterates a dict in the order keys were first inserted.
493#[derive(Clone, Debug, Default)]
494pub struct Dict {
495 entries: Vec<(Arc<str>, Value)>,
496 index: HashMap<Arc<str>, usize>,
497}
498
499impl Dict {
500 pub fn new() -> Self { Self::default() }
501
502 pub fn len(&self) -> usize { self.entries.len() }
503
504 pub fn is_empty(&self) -> bool { self.entries.is_empty() }
505
506 pub fn get(&self, key: &str) -> Option<&Value> {
507 self.index.get(key).and_then(|i| self.entries.get(*i)).map(|(_, v)| v)
508 }
509
510 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
511 match self.index.get(key) {
512 Some(i) => self.entries.get_mut(*i).map(|(_, v)| v),
513 None => None,
514 }
515 }
516
517 pub fn contains(&self, key: &str) -> bool { self.index.contains_key(key) }
518
519 /// Inserts or replaces; a replaced key keeps its original position, as in Typst.
520 pub fn insert(&mut self, key: &str, value: Value) {
521 match self.index.get(key) {
522 Some(i) => {
523 if let Some(e) = self.entries.get_mut(*i) {
524 e.1 = value;
525 }
526 }
527 None => {
528 let k: Arc<str> = Arc::from(key);
529 self.index.insert(k.clone(), self.entries.len());
530 self.entries.push((k, value));
531 }
532 }
533 }
534
535 pub fn remove(&mut self, key: &str) -> Option<Value> {
536 let i = match self.index.remove(key) {
537 Some(i) => i,
538 None => return None,
539 };
540 let (_, v) = self.entries.remove(i);
541 for j in self.index.values_mut() {
542 if *j > i {
543 *j -= 1;
544 }
545 }
546 Some(v)
547 }
548
549 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
550 self.entries.iter().map(|(k, v)| (&**k, v))
551 }
552
553 pub fn keys(&self) -> impl Iterator<Item = &str> {
554 self.entries.iter().map(|(k, _)| &**k)
555 }
556}
557
558/// An evaluated module: `import`'s result and `sym`/`calc`'s shape.
559#[derive(Clone, Debug)]
560pub struct Module {
561 pub name: Arc<String>,
562 pub scope: Scope,
563 pub content: Content, // the module's markup, what `include` yields
564}
565
566impl Module {
567 pub fn new<S: Into<String>>(name: S, scope: Scope) -> Self {
568 Self { name: Arc::new(name.into()), scope, content: Content::empty() }
569 }
570}
571
572// Casting
573
574pub trait FromValue: Sized {
575 fn from_value(v: Value) -> Outcome<Self>;
576}
577
578pub trait IntoValue {
579 fn into_value(self) -> Value;
580}
581
582fn mismatch(expected: &str, found: &Value) -> Error<ErrTag> {
583 err!("expected {}, found {}", expected, found.ty().long_name(); Input, Mismatch)
584}
585
586impl FromValue for Value {
587 fn from_value(v: Value) -> Outcome<Self> { Ok(v) }
588}
589
590impl FromValue for bool {
591 fn from_value(v: Value) -> Outcome<Self> {
592 match v {
593 Value::Bool(b) => Ok(b),
594 other => Err(mismatch("boolean", &other)),
595 }
596 }
597}
598
599impl FromValue for i64 {
600 fn from_value(v: Value) -> Outcome<Self> {
601 match v {
602 Value::Int(i) => Ok(i),
603 other => Err(mismatch("integer", &other)),
604 }
605 }
606}
607
608impl FromValue for usize {
609 fn from_value(v: Value) -> Outcome<Self> {
610 match v {
611 Value::Int(i) if i >= 0 => Ok(i as usize),
612 Value::Int(i) => Err(err!("number must be at least zero, found {}", i; Input, Range)),
613 other => Err(mismatch("integer", &other)),
614 }
615 }
616}
617
618impl FromValue for f64 {
619 fn from_value(v: Value) -> Outcome<Self> {
620 match v {
621 Value::Int(i) => Ok(i as f64),
622 Value::Float(f) => Ok(f),
623 other => Err(mismatch("float", &other)),
624 }
625 }
626}
627
628impl FromValue for String {
629 fn from_value(v: Value) -> Outcome<Self> {
630 match v.str_cast() {
631 Some(s) => Ok((*s).clone()),
632 None => Err(mismatch("string", &v)),
633 }
634 }
635}
636
637impl FromValue for Arc<String> {
638 fn from_value(v: Value) -> Outcome<Self> {
639 match v.str_cast() {
640 Some(s) => Ok(s),
641 None => Err(mismatch("string", &v)),
642 }
643 }
644}
645
646impl FromValue for Label {
647 fn from_value(v: Value) -> Outcome<Self> {
648 match v {
649 Value::Label(l) => Ok(l),
650 other => Err(mismatch("label", &other)),
651 }
652 }
653}
654
655impl FromValue for Length {
656 fn from_value(v: Value) -> Outcome<Self> {
657 match v {
658 Value::Length(l) => Ok(l),
659 other => Err(mismatch("length", &other)),
660 }
661 }
662}
663
664impl FromValue for Relative {
665 fn from_value(v: Value) -> Outcome<Self> {
666 match v {
667 Value::Relative(r) => Ok(r),
668 Value::Length(l) => Ok(Relative { rel: Ratio(0.0), abs: l }),
669 Value::Ratio(r) => Ok(Relative { rel: r, abs: Length::zero() }),
670 other => Err(mismatch("relative length", &other)),
671 }
672 }
673}
674
675impl FromValue for Color {
676 fn from_value(v: Value) -> Outcome<Self> {
677 match v {
678 Value::Color(c) => Ok(c),
679 other => Err(mismatch("color", &other)),
680 }
681 }
682}
683
684impl FromValue for Alignment {
685 fn from_value(v: Value) -> Outcome<Self> {
686 match v {
687 Value::Alignment(a) => Ok(a),
688 other => Err(mismatch("alignment", &other)),
689 }
690 }
691}
692
693impl FromValue for Func {
694 fn from_value(v: Value) -> Outcome<Self> {
695 match as_func(&v) {
696 Some(f) => Ok(f),
697 None => Err(err!("{}", func_refusal(&v); Input, Mismatch)),
698 }
699 }
700}
701
702impl FromValue for Vec<Value> {
703 fn from_value(v: Value) -> Outcome<Self> {
704 match v {
705 Value::Array(a) => Ok((*a).clone()),
706 other => Err(mismatch("array", &other)),
707 }
708 }
709}
710
711impl FromValue for Dict {
712 fn from_value(v: Value) -> Outcome<Self> {
713 match v {
714 Value::Dict(d) => Ok((*d).clone()),
715 other => Err(mismatch("dictionary", &other)),
716 }
717 }
718}
719
720/// Content accepts what Typst displays as content: content itself, a string, a symbol, a number, `none`.
721impl FromValue for Content {
722 fn from_value(v: Value) -> Outcome<Self> {
723 match v {
724 Value::Content(c) => Ok(c),
725 Value::None => Ok(Content::empty()),
726 Value::Str(s) => Ok(Content::text(&s)),
727 Value::Int(i) => Ok(Content::text(&fmt!("{}", i))),
728 Value::Symbol(s) => Ok(Content::symbol(&crate::eval::ops::symbol_text(&s))),
729 other => Err(mismatch("content", &other)),
730 }
731 }
732}
733
734impl<T: FromValue> FromValue for Option<T> {
735 fn from_value(v: Value) -> Outcome<Self> {
736 match v {
737 Value::None => Ok(None),
738 other => Ok(Some(res!(T::from_value(other)))),
739 }
740 }
741}
742
743impl IntoValue for Value {
744 fn into_value(self) -> Value { self }
745}
746
747impl IntoValue for bool {
748 fn into_value(self) -> Value { Value::Bool(self) }
749}
750
751impl IntoValue for i64 {
752 fn into_value(self) -> Value { Value::Int(self) }
753}
754
755impl IntoValue for f64 {
756 fn into_value(self) -> Value { Value::Float(self) }
757}
758
759impl IntoValue for String {
760 fn into_value(self) -> Value { Value::str(self) }
761}
762
763impl IntoValue for &str {
764 fn into_value(self) -> Value { Value::str(self) }
765}
766
767impl IntoValue for Content {
768 fn into_value(self) -> Value { Value::Content(self) }
769}
770
771impl IntoValue for Length {
772 fn into_value(self) -> Value { Value::Length(self) }
773}
774
775impl IntoValue for Label {
776 fn into_value(self) -> Value { Value::Label(self) }
777}
778
779impl IntoValue for Func {
780 fn into_value(self) -> Value { Value::Func(self) }
781}
782
783impl IntoValue for Vec<Value> {
784 fn into_value(self) -> Value { Value::array(self) }
785}
786
787impl IntoValue for Dict {
788 fn into_value(self) -> Value { Value::dict(self) }
789}
790
791impl<T: IntoValue> IntoValue for Option<T> {
792 fn into_value(self) -> Value {
793 match self {
794 Some(v) => v.into_value(),
795 None => Value::None,
796 }
797 }
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803
804 // An exhaustive match, so a type added to the enum fails here until `Type::ALL` holds it.
805 fn slot(t: Type) -> usize {
806 match t {
807 Type::None => 0, Type::Auto => 1, Type::Bool => 2, Type::Int => 3, Type::Float => 4,
808 Type::Decimal => 5, Type::Length => 6, Type::Angle => 7, Type::Ratio => 8, Type::Relative => 9,
809 Type::Fraction => 10, Type::Color => 11, Type::Gradient => 12, Type::Tiling => 13, Type::Stroke => 14,
810 Type::Alignment => 15, Type::Direction => 16, Type::Symbol => 17, Type::Str => 18, Type::Bytes => 19,
811 Type::Label => 20, Type::Datetime => 21, Type::Duration => 22, Type::Version => 23, Type::Regex => 24,
812 Type::Content => 25, Type::Array => 26, Type::Dict => 27, Type::Func => 28, Type::Args => 29,
813 Type::Module => 30, Type::Type => 31, Type::Styles => 32, Type::Selector => 33, Type::Counter => 34,
814 Type::State => 35, Type::Location => 36,
815 }
816 }
817
818 #[test]
819 fn every_type_is_in_the_registry_once_and_found_by_either_name() {
820 for (i, t) in Type::ALL.iter().enumerate() {
821 assert_eq!(slot(*t), i, "{:?} sits at its declared place in Type::ALL", t);
822 assert_eq!(Type::from_name(t.name()), Some(*t), "{:?} by its repr name", t);
823 assert_eq!(Type::from_name(t.long_name()), Some(*t), "{:?} by its message name", t);
824 }
825 assert_eq!(Type::from_name("integer"), Some(Type::Int));
826 assert_eq!(Type::from_name("relative length"), Some(Type::Relative));
827 assert_eq!(Type::from_name("nonesuch"), None);
828 assert_eq!(Type::from_name(""), None);
829 }
830}