1mod list;
4mod map;
5mod str;
6
7pub use list::ListData;
8pub use map::{MapData, MapEntries};
9pub use str::StrValue;
10
11use serde::{Deserialize, Serialize};
12use std::sync::Arc;
13
14#[non_exhaustive]
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
21pub enum Ty {
22 Unit,
24 Int,
26 Float,
28 Bool,
30 Str,
32 Identity,
34 List(Box<Ty>),
36 Map(Box<Ty>, Box<Ty>),
38 Option(Box<Ty>),
40 Struct(String),
42 Enum(String),
44 Fn(Vec<Ty>, Box<Ty>),
46}
47
48pub const MAX_TYPE_DEPTH: u32 = 32;
52
53pub(crate) const MAX_VALUE_DEPTH: u32 = 64;
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct TypeDecl {
59 pub name: String,
61 pub kind: TypeKind,
63}
64
65#[non_exhaustive]
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum TypeKind {
69 Struct {
71 fields: Vec<(String, Ty)>,
73 },
74 Enum {
76 variants: Vec<VariantDecl>,
78 },
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct VariantDecl {
84 pub name: String,
86 pub args: Vec<Ty>,
88}
89
90impl TypeDecl {
91 pub fn signature(&self) -> String {
93 match &self.kind {
94 TypeKind::Struct { fields } => {
95 let parts: Vec<String> = fields
96 .iter()
97 .map(|(n, t)| format!("{n}: {}", t.name()))
98 .collect();
99 if parts.is_empty() {
100 "struct {}".to_string()
101 } else {
102 format!("struct {{ {} }}", parts.join(", "))
103 }
104 }
105 TypeKind::Enum { variants } => {
106 let parts: Vec<String> = variants
107 .iter()
108 .map(|v| {
109 if v.args.is_empty() {
110 v.name.clone()
111 } else {
112 let a: Vec<String> = v.args.iter().map(Ty::name).collect();
113 format!("{}({})", v.name, a.join(", "))
114 }
115 })
116 .collect();
117 format!("enum {{ {} }}", parts.join(", "))
118 }
119 }
120 }
121
122 pub(crate) fn used_types(&self) -> Vec<&str> {
124 let mut out = Vec::new();
125 match &self.kind {
126 TypeKind::Struct { fields } => {
127 fields.iter().for_each(|(_, t)| t.collect_user(&mut out))
128 }
129 TypeKind::Enum { variants } => variants
130 .iter()
131 .flat_map(|v| &v.args)
132 .for_each(|t| t.collect_user(&mut out)),
133 }
134 out
135 }
136}
137
138pub fn find_type<'a>(types: &'a [TypeDecl], name: &str) -> Option<&'a TypeDecl> {
140 types.iter().find(|t| t.name == name)
141}
142
143pub(crate) fn short_type_name(name: &str) -> &str {
145 name.rsplit('.').next().unwrap_or(name)
146}
147
148impl Ty {
149 pub fn name(&self) -> String {
151 match self {
152 Ty::Unit => "()".to_string(),
153 Ty::Int => "int".to_string(),
154 Ty::Float => "float".to_string(),
155 Ty::Bool => "bool".to_string(),
156 Ty::Str => "str".to_string(),
157 Ty::Identity => "Identity".to_string(),
158 Ty::List(t) => format!("list<{}>", t.name()),
159 Ty::Map(k, v) => format!("map<{}, {}>", k.name(), v.name()),
160 Ty::Option(t) => format!("Option<{}>", t.name()),
161 Ty::Struct(n) | Ty::Enum(n) => n.clone(),
162 Ty::Fn(params, ret) => {
163 let ps: Vec<String> = params.iter().map(Ty::name).collect();
164 format!("fn({}) -> {}", ps.join(", "), ret.name())
165 }
166 }
167 }
168
169 pub fn contains_fn(&self) -> bool {
173 match self {
174 Ty::Fn(..) => true,
175 Ty::List(t) | Ty::Option(t) => t.contains_fn(),
176 Ty::Map(k, v) => k.contains_fn() || v.contains_fn(),
177 _ => false,
178 }
179 }
180
181 pub fn default_in(&self, types: &[TypeDecl]) -> Value {
186 match self {
187 Ty::Unit => Value::Unit,
188 Ty::Int => Value::Int(0),
189 Ty::Float => Value::Float(0.0),
190 Ty::Bool => Value::Bool(false),
191 Ty::Str => Value::Str(String::new().into()),
192 Ty::Identity => Value::Identity(Arc::default()),
193 Ty::List(_) => Value::List(ListData::new()),
194 Ty::Map(..) => Value::Map(MapData::new()),
195 Ty::Option(_) => Value::Option(None),
196 Ty::Fn(..) => Value::Unit,
198 Ty::Struct(n) | Ty::Enum(n) => match find_type(types, n).map(|d| &d.kind) {
199 Some(TypeKind::Struct { fields }) => Value::Struct(Arc::new(StructValue {
200 ty: n.clone().into(),
201 fields: fields
202 .iter()
203 .map(|(f, t)| (f.clone(), t.default_in(types)))
204 .collect::<Vec<_>>(),
205 })),
206 Some(TypeKind::Enum { variants }) => match variants.first() {
207 Some(v) => Value::Enum(Arc::new(EnumValue {
208 ty: n.clone().into(),
209 variant: v.name.clone().into(),
210 args: v
211 .args
212 .iter()
213 .map(|t| t.default_in(types))
214 .collect::<Vec<_>>(),
215 })),
216 None => Value::Unit,
217 },
218 None => Value::Unit,
219 },
220 }
221 }
222
223 pub fn depth_in(&self, types: &[TypeDecl]) -> u32 {
226 self.depth_rec(types, 0)
227 }
228
229 fn depth_rec(&self, types: &[TypeDecl], from: u32) -> u32 {
231 if from > MAX_TYPE_DEPTH {
232 return from;
233 }
234 match self {
235 Ty::List(t) | Ty::Option(t) => 1 + t.depth_rec(types, from + 1),
236 Ty::Map(k, v) => {
237 1 + k
238 .depth_rec(types, from + 1)
239 .max(v.depth_rec(types, from + 1))
240 }
241 Ty::Fn(params, ret) => {
242 1 + params
243 .iter()
244 .chain(std::iter::once(&**ret))
245 .map(|t| t.depth_rec(types, from + 1))
246 .max()
247 .unwrap_or(0)
248 }
249 Ty::Struct(n) | Ty::Enum(n) => {
250 let inner = match find_type(types, n).map(|d| &d.kind) {
251 Some(TypeKind::Struct { fields }) => fields
252 .iter()
253 .map(|(_, t)| t.depth_rec(types, from + 1))
254 .max()
255 .unwrap_or(0),
256 Some(TypeKind::Enum { variants }) => variants
257 .iter()
258 .flat_map(|v| &v.args)
259 .map(|t| t.depth_rec(types, from + 1))
260 .max()
261 .unwrap_or(0),
262 None => 0,
263 };
264 1 + inner
265 }
266 _ => 1,
267 }
268 }
269
270 pub(crate) fn collect_user<'a>(&'a self, out: &mut Vec<&'a str>) {
272 match self {
273 Ty::List(t) | Ty::Option(t) => t.collect_user(out),
274 Ty::Map(k, v) => {
275 k.collect_user(out);
276 v.collect_user(out);
277 }
278 Ty::Fn(params, ret) => {
279 params.iter().for_each(|t| t.collect_user(out));
280 ret.collect_user(out);
281 }
282 Ty::Struct(n) | Ty::Enum(n) => out.push(n),
283 _ => {}
284 }
285 }
286
287 pub fn is_key_in(&self, types: &[TypeDecl]) -> bool {
291 self.key_rec(types, 0)
292 }
293
294 fn key_rec(&self, types: &[TypeDecl], from: u32) -> bool {
296 if from > MAX_TYPE_DEPTH {
297 return false;
298 }
299 match self {
300 Ty::Int | Ty::Str | Ty::Bool | Ty::Identity => true,
301 Ty::Struct(n) | Ty::Enum(n) => match find_type(types, n).map(|d| &d.kind) {
302 Some(TypeKind::Struct { fields }) => {
303 fields.iter().all(|(_, t)| t.key_rec(types, from + 1))
304 }
305 Some(TypeKind::Enum { variants }) => variants
306 .iter()
307 .flat_map(|v| &v.args)
308 .all(|t| t.key_rec(types, from + 1)),
309 None => false,
310 },
311 _ => false,
312 }
313 }
314}
315
316#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
318pub struct Identity {
319 pub id: String,
321 pub name: String,
323}
324
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327pub struct StructValue {
328 pub ty: Arc<str>,
330 pub fields: Vec<(String, Value)>,
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336pub struct EnumValue {
337 pub ty: Arc<str>,
339 pub variant: Arc<str>,
341 pub args: Vec<Value>,
343}
344
345#[non_exhaustive]
350#[derive(Clone, Serialize, Deserialize)]
351pub enum Value {
352 Unit,
354 Int(i64),
356 Float(f64),
358 Bool(bool),
360 Str(StrValue),
362 Identity(Arc<Identity>),
364 List(ListData),
366 Map(MapData),
368 Option(Option<Box<Value>>),
370 Struct(Arc<StructValue>),
373 Enum(Arc<EnumValue>),
376 #[serde(skip)]
379 Fn(Arc<FnValue>),
380}
381
382#[derive(Debug, Clone, PartialEq)]
384pub struct FnValue {
385 pub(crate) f: u32,
387 pub(crate) captures: Box<[Value]>,
389}
390
391impl std::fmt::Debug for Value {
393 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394 match self {
395 Value::Unit => f.write_str("Unit"),
396 Value::Int(n) => f.debug_tuple("Int").field(n).finish(),
397 Value::Float(x) => f.debug_tuple("Float").field(x).finish(),
398 Value::Bool(b) => f.debug_tuple("Bool").field(b).finish(),
399 Value::Str(s) => f.debug_tuple("Str").field(s).finish(),
400 Value::Identity(i) => f.debug_tuple("Identity").field(i).finish(),
401 Value::List(items) => f.debug_tuple("List").field(items).finish(),
402 Value::Map(entries) => f.debug_tuple("Map").field(entries).finish(),
403 Value::Option(v) => f.debug_tuple("Option").field(v).finish(),
404 Value::Struct(st) => f
405 .debug_struct("Struct")
406 .field("ty", &st.ty)
407 .field("fields", &st.fields)
408 .finish(),
409 Value::Enum(e) => f
410 .debug_struct("Enum")
411 .field("ty", &e.ty)
412 .field("variant", &e.variant)
413 .field("args", &e.args)
414 .finish(),
415 Value::Fn(fv) => f.debug_tuple("Fn").field(&fv.f).finish(),
416 }
417 }
418}
419
420impl PartialEq for Value {
421 fn eq(&self, other: &Self) -> bool {
422 match (self, other) {
423 (Value::Unit, Value::Unit) => true,
424 (Value::Int(a), Value::Int(b)) => a == b,
425 (Value::Float(a), Value::Float(b)) => a == b,
426 (Value::Bool(a), Value::Bool(b)) => a == b,
427 (Value::Str(a), Value::Str(b)) => a == b,
428 (Value::Identity(a), Value::Identity(b)) => a == b,
429 (Value::List(a), Value::List(b)) => a == b,
430 (Value::Map(a), Value::Map(b)) => a == b,
431 (Value::Option(a), Value::Option(b)) => a == b,
432 (Value::Struct(a), Value::Struct(b)) => a == b,
433 (Value::Enum(a), Value::Enum(b)) => a == b,
434 (Value::Fn(a), Value::Fn(b)) => Arc::ptr_eq(a, b),
436 _ => false,
437 }
438 }
439}
440
441pub(crate) fn finite_float(x: f64) -> Option<f64> {
443 if !x.is_finite() {
444 None
445 } else if x == 0.0 {
446 Some(0.0)
447 } else {
448 Some(x)
449 }
450}
451
452pub(crate) fn float_text(x: f64) -> String {
454 let mut s = x.to_string();
455 if !s.contains('.') {
456 s.push_str(".0");
457 }
458 s
459}
460
461impl Value {
462 pub(crate) fn normalized(self) -> Option<Value> {
465 Some(match self {
466 Value::Float(x) => Value::Float(finite_float(x)?),
467 Value::List(items) => Value::List(
468 items
469 .into_vec()
470 .into_iter()
471 .map(Value::normalized)
472 .collect::<Option<Vec<_>>>()?
473 .into(),
474 ),
475 Value::Map(entries) => Value::Map(MapData::from_pairs(
476 entries
477 .into_entries()
478 .into_iter()
479 .map(|(k, v)| Some((k.normalized()?, v.normalized()?)))
480 .collect::<Option<Vec<_>>>()?,
481 )),
482 Value::Option(Some(v)) => Value::Option(Some(Box::new((*v).normalized()?))),
483 Value::Struct(st) => {
484 let StructValue { ty, fields } = Arc::unwrap_or_clone(st);
485 Value::Struct(Arc::new(StructValue {
486 ty,
487 fields: fields
488 .into_iter()
489 .map(|(n, v)| Some((n, v.normalized()?)))
490 .collect::<Option<Vec<_>>>()?,
491 }))
492 }
493 Value::Enum(e) => {
494 let EnumValue { ty, variant, args } = Arc::unwrap_or_clone(e);
495 Value::Enum(Arc::new(EnumValue {
496 ty,
497 variant,
498 args: args
499 .into_iter()
500 .map(Value::normalized)
501 .collect::<Option<Vec<_>>>()?,
502 }))
503 }
504 other => other,
505 })
506 }
507
508 pub fn ty(&self) -> Ty {
511 match self {
512 Value::Unit => Ty::Unit,
513 Value::Int(_) => Ty::Int,
514 Value::Float(_) => Ty::Float,
515 Value::Bool(_) => Ty::Bool,
516 Value::Str(_) => Ty::Str,
517 Value::Identity(_) => Ty::Identity,
518 Value::List(items) => Ty::List(Box::new(items.first().map_or(Ty::Unit, Value::ty))),
519 Value::Map(entries) => Ty::Map(
520 Box::new(entries.entries().next().map_or(Ty::Unit, |(k, _)| k.ty())),
521 Box::new(entries.entries().next().map_or(Ty::Unit, |(_, v)| v.ty())),
522 ),
523 Value::Option(inner) => {
524 Ty::Option(Box::new(inner.as_deref().map_or(Ty::Unit, Value::ty)))
525 }
526 Value::Struct(st) => Ty::Struct(st.ty.to_string()),
527 Value::Enum(e) => Ty::Enum(e.ty.to_string()),
528 Value::Fn(_) => Ty::Fn(Vec::new(), Box::new(Ty::Unit)),
530 }
531 }
532
533 pub fn matches(&self, ty: &Ty) -> bool {
536 self.matches_in(ty, &[])
537 }
538
539 pub fn matches_in(&self, ty: &Ty, types: &[TypeDecl]) -> bool {
542 match (self, ty) {
543 (Value::Unit, Ty::Unit)
544 | (Value::Int(_), Ty::Int)
545 | (Value::Float(_), Ty::Float)
546 | (Value::Bool(_), Ty::Bool)
547 | (Value::Str(_), Ty::Str)
548 | (Value::Identity(_), Ty::Identity) => true,
549 (Value::List(items), Ty::List(t)) => items.iter().all(|v| v.matches_in(t, types)),
550 (Value::Map(entries), Ty::Map(kt, vt)) => entries
551 .iter()
552 .all(|(k, v)| k.matches_in(kt, types) && v.matches_in(vt, types)),
553 (Value::Option(None), Ty::Option(_)) | (Value::Fn(_), Ty::Fn(..)) => true,
554 (Value::Option(Some(v)), Ty::Option(t)) => v.matches_in(t, types),
555 (Value::Struct(st), Ty::Struct(tn)) => {
556 let StructValue { ty: vn, fields } = &**st;
557 **vn == **tn
558 && match find_type(types, tn).map(|d| &d.kind) {
559 Some(TypeKind::Struct { fields: decl }) => {
560 decl.len() == fields.len()
561 && decl.iter().zip(fields.iter()).all(|((dn, dt), (fnm, fv))| {
562 dn == fnm && fv.matches_in(dt, types)
563 })
564 }
565 Some(_) => false,
566 None => true,
567 }
568 }
569 (Value::Enum(e), Ty::Enum(tn)) => {
570 let EnumValue {
571 ty: vn,
572 variant,
573 args,
574 } = &**e;
575 **vn == **tn
576 && match find_type(types, tn).map(|d| &d.kind) {
577 Some(TypeKind::Enum { variants }) => variants
578 .iter()
579 .find(|v| *v.name == **variant)
580 .is_some_and(|v| {
581 v.args.len() == args.len()
582 && v.args
583 .iter()
584 .zip(args.iter())
585 .all(|(t, a)| a.matches_in(t, types))
586 }),
587 Some(_) => false,
588 None => true,
589 }
590 }
591 _ => false,
592 }
593 }
594
595 pub fn depth(&self) -> u32 {
597 match self {
598 Value::List(items) => 1 + items.iter().map(Value::depth).max().unwrap_or(0),
599 Value::Map(entries) => {
600 1 + entries
601 .iter()
602 .map(|(k, v)| k.depth().max(v.depth()))
603 .max()
604 .unwrap_or(0)
605 }
606 Value::Option(Some(v)) => 1 + v.depth(),
607 Value::Struct(st) => 1 + st.fields.iter().map(|(_, v)| v.depth()).max().unwrap_or(0),
608 Value::Enum(e) => 1 + e.args.iter().map(Value::depth).max().unwrap_or(0),
609 _ => 1,
610 }
611 }
612
613 #[inline]
616 pub fn approx_bytes(&self) -> usize {
617 match self {
618 Value::Unit | Value::Int(_) | Value::Float(_) | Value::Bool(_) => 8,
619 _ => self.approx_bytes_composite(),
620 }
621 }
622
623 #[inline(never)]
625 fn approx_bytes_composite(&self) -> usize {
626 match self {
627 Value::Unit | Value::Int(_) | Value::Float(_) | Value::Bool(_) => 8,
628 Value::Str(s) => 24 + s.len(),
629 Value::Identity(i) => 48 + i.id.len() + i.name.len(),
630 Value::List(items) => 24 + items.content_bytes(),
632 Value::Map(entries) => 24 + entries.content_bytes(),
633 Value::Option(None) => 8,
634 Value::Option(Some(v)) => 8 + v.approx_bytes(),
635 Value::Struct(st) => {
636 24 + st
637 .fields
638 .iter()
639 .map(|(_, v)| v.approx_bytes())
640 .sum::<usize>()
641 }
642 Value::Enum(e) => 24 + e.args.iter().map(Value::approx_bytes).sum::<usize>(),
643 Value::Fn(fv) => 24 + fv.captures.iter().map(Value::approx_bytes).sum::<usize>(),
644 }
645 }
646
647 pub fn to_text(&self) -> String {
649 self.render(false)
650 }
651
652 pub fn to_repl_text(&self) -> String {
656 self.render(true)
657 }
658
659 fn render(&self, repl: bool) -> String {
661 match self {
662 Value::Unit => String::new(),
663 Value::Int(n) => n.to_string(),
664 Value::Float(x) => float_text(*x),
665 Value::Bool(b) => b.to_string(),
666 Value::Str(s) if repl => quoted_text(s),
667 Value::Str(s) => s.to_string(),
668 Value::Identity(i) if repl => format!(
669 "Identity {{ id: {}, name: {} }}",
670 quoted_text(&i.id),
671 quoted_text(&i.name)
672 ),
673 Value::Identity(i) => i.name.clone(),
674 Value::List(items) => {
675 let parts: Vec<String> = items.iter().map(|v| v.render(repl)).collect();
676 format!("[{}]", parts.join(", "))
677 }
678 Value::Map(entries) => {
679 if entries.is_empty() {
680 return "map {}".to_string();
681 }
682 let parts: Vec<String> = entries
683 .iter()
684 .map(|(k, v)| format!("{}: {}", k.render(repl), v.render(repl)))
685 .collect();
686 format!("map {{ {} }}", parts.join(", "))
687 }
688 Value::Option(None) => "None".to_string(),
689 Value::Option(Some(v)) => format!("Some({})", v.render(repl)),
690 Value::Struct(st) => {
691 let StructValue { ty, fields } = &**st;
692 let parts: Vec<String> = fields
693 .iter()
694 .map(|(n, v)| format!("{n}: {}", v.render(repl)))
695 .collect();
696 if parts.is_empty() {
697 format!("{} {{ }}", short_type_name(ty))
698 } else {
699 format!("{} {{ {} }}", short_type_name(ty), parts.join(", "))
700 }
701 }
702 Value::Enum(e) => {
703 let EnumValue { ty, variant, args } = &**e;
704 if args.is_empty() {
705 format!("{}.{variant}", short_type_name(ty))
706 } else {
707 let parts: Vec<String> = args.iter().map(|v| v.render(repl)).collect();
708 format!("{}.{variant}({})", short_type_name(ty), parts.join(", "))
709 }
710 }
711 Value::Fn(_) => "<fn>".to_string(),
712 }
713 }
714}
715
716fn quoted_text(s: &str) -> String {
718 let mut out = String::with_capacity(s.len() + 2);
719 out.push('"');
720 for c in s.chars() {
721 match c {
722 '"' => out.push_str("\\\""),
723 '\\' => out.push_str("\\\\"),
724 '\n' => out.push_str("\\n"),
725 '\t' => out.push_str("\\t"),
726 '$' => out.push_str("\\$"),
727 c => out.push(c),
728 }
729 }
730 out.push('"');
731 out
732}
733
734impl Value {
735 pub(crate) fn key_repr(&self) -> String {
738 let mut out = String::new();
739 self.key_repr_into(&mut out);
740 out
741 }
742
743 fn key_repr_into(&self, out: &mut String) {
745 use std::fmt::Write;
746 match self {
747 Value::Int(n) => {
748 let _ = write!(out, "i{n};");
749 }
750 Value::Bool(b) => out.push_str(if *b { "b1;" } else { "b0;" }),
751 Value::Str(t) => {
752 let _ = write!(out, "s{}:{t};", t.len());
753 }
754 Value::Identity(i) => {
755 let _ = write!(out, "I{}:{}{}:{};", i.id.len(), i.id, i.name.len(), i.name);
756 }
757 Value::Struct(st) => {
758 let StructValue { ty, fields } = &**st;
759 let _ = write!(out, "S{}:{ty}(", ty.len());
760 for (_, v) in fields.iter() {
761 v.key_repr_into(out);
762 }
763 out.push_str(");");
764 }
765 Value::Enum(e) => {
766 let EnumValue { ty, variant, args } = &**e;
767 let _ = write!(out, "E{}:{ty}{}:{variant}(", ty.len(), variant.len());
768 for a in args.iter() {
769 a.key_repr_into(out);
770 }
771 out.push_str(");");
772 }
773 other => {
775 let t = other.to_text();
776 let _ = write!(out, "?{}:{t};", t.len());
777 }
778 }
779 }
780}
781
782#[cfg(test)]
783mod tests {
784 use super::*;
785
786 #[test]
787 fn values_are_checked_against_expected_type_including_nesting() {
788 let list = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())].into());
789 assert!(list.matches(&Ty::List(Box::new(Ty::Str))));
790 assert!(!list.matches(&Ty::List(Box::new(Ty::Int))));
791 assert!(!list.matches(&Ty::Str));
792 assert!(Value::List(vec![].into()).matches(&Ty::List(Box::new(Ty::Int))));
794 let some = Value::Option(Some(Box::new(Value::Identity(Arc::new(
795 Identity::default(),
796 )))));
797 assert!(some.matches(&Ty::Option(Box::new(Ty::Identity))));
798 assert!(Value::Option(None).matches(&Ty::Option(Box::new(Ty::Int))));
799 assert!(!some.matches(&Ty::Option(Box::new(Ty::Str))));
800 }
801
802 #[test]
803 fn display_form_quotes_and_escapes_nested_strings() {
804 let list = Value::List(vec![Value::Str("お面".into()), Value::Str("a\"b".into())].into());
805 assert_eq!(list.to_text(), "[お面, a\"b]");
806 assert_eq!(list.to_repl_text(), "[\"お面\", \"a\\\"b\"]");
807 let s = Value::Str("x\\y\n\t$1".into());
808 assert_eq!(s.to_repl_text(), "\"x\\\\y\\n\\t\\$1\"");
809 let some = Value::Option(Some(Box::new(Value::Str("a".into()))));
810 assert_eq!(some.to_repl_text(), "Some(\"a\")");
811 assert_eq!(Value::Int(-3).to_repl_text(), "-3");
812 assert_eq!(Value::Float(3.0).to_repl_text(), "3.0");
813 let id = Value::Identity(Arc::new(Identity {
814 id: "案内人".into(),
815 name: "リオン".into(),
816 }));
817 assert_eq!(id.to_text(), "リオン");
818 assert_eq!(
819 id.to_repl_text(),
820 "Identity { id: \"案内人\", name: \"リオン\" }"
821 );
822 }
823
824 #[test]
825 fn type_names_use_script_notation() {
826 assert_eq!(Ty::Identity.name(), "Identity");
827 assert_eq!(Ty::List(Box::new(Ty::Str)).name(), "list<str>");
828 assert_eq!(Ty::Option(Box::new(Ty::Int)).name(), "Option<int>");
829 }
830
831 #[test]
832 fn values_round_trip_through_postcard_including_identity() {
833 let id = Identity {
834 id: "案内人".into(),
835 name: "案内人".into(),
836 };
837 let bytes = postcard::to_allocvec(&id).unwrap();
838 let back: Identity = postcard::from_bytes(&bytes).unwrap();
839 assert_eq!(back, id);
840 }
841}