1use std::fmt;
8
9use crate::{Type, Value};
10
11const MAX_NESTING: usize = 128;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Span {
24 pub start: usize,
26 pub end: usize,
31}
32
33impl Span {
34 fn new(start: usize, end: usize) -> Span {
35 Span { start, end }
36 }
37
38 fn point(at: usize) -> Span {
42 Span { start: at, end: at }
43 }
44}
45
46impl fmt::Display for Span {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 if self.start == self.end {
49 write!(f, "{}", self.start)
50 } else {
51 write!(f, "{}-{}", self.start, self.end)
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct TextError {
63 pub spans: Vec<Span>,
69 pub reason: String,
71}
72
73impl TextError {
74 fn new(span: Span, reason: impl Into<String>) -> TextError {
75 TextError {
76 spans: vec![span],
77 reason: reason.into(),
78 }
79 }
80}
81
82impl fmt::Display for TextError {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 for (index, span) in self.spans.iter().enumerate() {
85 if index > 0 {
86 f.write_str(",")?;
87 }
88 write!(f, "{span}")?;
89 }
90 write!(f, ":{}", self.reason)
91 }
92}
93
94impl std::error::Error for TextError {}
95
96type TextResult<T> = std::result::Result<T, TextError>;
97
98const CANNOT_INFER: &str = "unable to infer type";
103
104pub fn from_text(text: &str) -> TextResult<(Type, Value)> {
157 let mut parser = Parser::new(text);
158 let node = parser.value()?;
159 let ty = value_type(&node)?;
160 let value = build(&node, &ty)?;
161 parser.expect_end()?;
162 Ok((ty, value))
163}
164
165#[derive(Debug, Clone, PartialEq, Eq)]
168enum Tok {
169 Open(char),
170 Close(char),
171 Comma,
172 Colon,
173 TypeDecl(String),
178 Word(String),
179 Number(String),
180 Str(String),
181 ByteString(Vec<u8>),
182 End,
183}
184
185#[derive(Debug, Clone)]
186struct Token {
187 tok: Tok,
188 span: Span,
189}
190
191struct Lexer<'a> {
192 text: &'a [u8],
193 pos: usize,
194}
195
196impl<'a> Lexer<'a> {
197 fn new(text: &'a str) -> Lexer<'a> {
198 Lexer {
199 text: text.as_bytes(),
200 pos: 0,
201 }
202 }
203
204 fn skip_space(&mut self) {
205 while matches!(self.text.get(self.pos), Some(b' ' | b'\t' | b'\n' | b'\r')) {
206 self.pos += 1;
207 }
208 }
209
210 fn next(&mut self) -> TextResult<Token> {
211 self.skip_space();
212 let start = self.pos;
213 let Some(&c) = self.text.get(start) else {
214 return Ok(Token {
215 tok: Tok::End,
216 span: Span::point(start),
217 });
218 };
219 let tok =
220 match c {
221 b'(' | b'[' | b'{' | b'<' => {
222 self.pos += 1;
223 Tok::Open(c as char)
224 }
225 b')' | b']' | b'}' | b'>' => {
226 self.pos += 1;
227 Tok::Close(c as char)
228 }
229 b',' => {
230 self.pos += 1;
231 Tok::Comma
232 }
233 b':' => {
234 self.pos += 1;
235 Tok::Colon
236 }
237 b'@' => {
238 self.pos += 1;
239 self.declaration();
240 Tok::TypeDecl(self.slice(start + 1, self.pos))
241 }
242 b'\'' | b'"' => return self.string(start, c, false),
243 b'b' if matches!(self.text.get(start + 1), Some(b'\'' | b'"')) => {
244 let quote = self.text[start + 1];
245 self.pos += 1;
246 return self.string(start, quote, true);
247 }
248 b'0'..=b'9' | b'-' | b'+' | b'.' => {
249 self.pos += 1;
250 while self.text.get(self.pos).is_some_and(|b| {
251 b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-')
252 }) {
253 self.pos += 1;
254 }
255 Tok::Number(self.slice(start, self.pos))
256 }
257 b'a'..=b'z' => {
258 while self
259 .text
260 .get(self.pos)
261 .is_some_and(u8::is_ascii_alphanumeric)
262 {
263 self.pos += 1;
264 }
265 Tok::Word(self.slice(start, self.pos))
266 }
267 _ => {
271 self.pos += 1;
272 Tok::Word(self.slice(start, self.pos))
273 }
274 };
275 Ok(Token {
276 tok,
277 span: Span::new(start, self.pos),
278 })
279 }
280
281 fn declaration(&mut self) {
289 let mut depth = 0usize;
290 while let Some(&c) = self.text.get(self.pos) {
291 match c {
292 b' ' | b'\t' | b'\n' | b'\r' | b',' | b':' | b'>' | b']' => break,
293 b')' | b'}' if depth == 0 => break,
294 b')' | b'}' => depth -= 1,
295 b'(' | b'{' => depth += 1,
296 _ => {}
297 }
298 self.pos += 1;
299 }
300 }
301
302 fn string(&mut self, start: usize, quote: u8, bytestring: bool) -> TextResult<Token> {
306 self.pos += 1; let mut raw = Vec::new();
308 loop {
309 let Some(&c) = self.text.get(self.pos) else {
310 self.pos = self.text.len();
311 return Err(TextError::new(
312 Span::new(start, self.pos),
313 "unterminated string constant",
314 ));
315 };
316 self.pos += 1;
317 if c == quote {
318 break;
319 }
320 if c != b'\\' {
321 if c == 0 && !bytestring {
326 return Err(TextError::new(
327 Span::new(self.pos - 1, self.pos),
328 "NUL byte in string constant",
329 ));
330 }
331 raw.push(c);
332 continue;
333 }
334 let Some(&escaped) = self.text.get(self.pos) else {
335 self.pos = self.text.len();
336 return Err(TextError::new(
337 Span::new(start, self.pos),
338 "unterminated string constant",
339 ));
340 };
341 self.pos += 1;
342 match escaped {
343 b'a' => raw.push(0x07),
344 b'b' => raw.push(0x08),
345 b'f' => raw.push(0x0c),
346 b'n' => raw.push(b'\n'),
347 b'r' => raw.push(b'\r'),
348 b't' => raw.push(b'\t'),
349 b'v' => raw.push(0x0b),
350 b'0'..=b'7' if bytestring => {
351 let mut value = u32::from(escaped - b'0');
354 for _ in 0..2 {
355 match self.text.get(self.pos) {
356 Some(&d @ b'0'..=b'7') => {
357 value = value * 8 + u32::from(d - b'0');
358 self.pos += 1;
359 }
360 _ => break,
361 }
362 }
363 raw.push(value as u8);
364 }
365 b'u' if !bytestring => self.unicode_escape(4, &mut raw)?,
366 b'U' if !bytestring => self.unicode_escape(8, &mut raw)?,
367 b'\n' => {}
371 other => raw.push(other),
373 }
374 }
375 let span = Span::new(start, self.pos);
376 if bytestring {
377 if let Some(nul) = raw.iter().position(|&b| b == 0) {
381 raw.truncate(nul);
382 }
383 raw.push(0);
384 return Ok(Token {
385 tok: Tok::ByteString(raw),
386 span,
387 });
388 }
389 match String::from_utf8(raw) {
390 Ok(text) => Ok(Token {
391 tok: Tok::Str(text),
392 span,
393 }),
394 Err(_) => Err(TextError::new(span, "invalid character in string constant")),
395 }
396 }
397
398 fn unicode_escape(&mut self, digits: usize, raw: &mut Vec<u8>) -> TextResult<()> {
404 let start = self.pos;
405 let mut count = 0;
406 while count < digits
407 && self
408 .text
409 .get(start + count)
410 .is_some_and(u8::is_ascii_hexdigit)
411 {
412 count += 1;
413 }
414 let bad = || {
415 TextError::new(
416 Span::new(start, start + count),
417 format!("invalid {digits}-character unicode escape"),
418 )
419 };
420 if count < digits {
421 return Err(bad());
422 }
423 let text = std::str::from_utf8(&self.text[start..start + digits]).map_err(|_| bad())?;
424 let code = u32::from_str_radix(text, 16).map_err(|_| bad())?;
425 let ch = char::from_u32(code)
430 .filter(|&c| c != '\0')
431 .ok_or_else(bad)?;
432 self.pos = start + digits;
433 let mut buf = [0u8; 4];
434 raw.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
435 Ok(())
436 }
437
438 fn slice(&self, start: usize, end: usize) -> String {
439 String::from_utf8_lossy(&self.text[start..end]).into_owned()
440 }
441}
442
443#[derive(Debug, Clone)]
446struct Node {
447 ast: Ast,
448 span: Span,
449}
450
451#[derive(Debug, Clone)]
452enum Ast {
453 Bool(bool),
454 Number(String),
459 Str(String),
460 ByteString(Vec<u8>),
461 Typed(Type, Box<Node>),
463 Maybe(Option<Box<Node>>),
465 Array(Vec<Node>),
466 Dict(Vec<(Node, Node)>),
468 Entry(Box<Node>, Box<Node>),
470 Tuple(Vec<Node>),
471 Variant(Box<Node>),
472}
473
474fn is_keyword_shaped(word: &str) -> bool {
481 let bytes = word.as_bytes();
482 bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1].is_ascii_alphabetic()
483}
484
485fn keyword_type(word: &str) -> Option<Type> {
487 Some(match word {
488 "boolean" => Type::Bool,
489 "byte" => Type::Byte,
490 "int16" => Type::I16,
491 "uint16" => Type::U16,
492 "int32" => Type::I32,
493 "handle" => Type::Handle,
494 "uint32" => Type::U32,
495 "int64" => Type::I64,
496 "uint64" => Type::U64,
497 "double" => Type::Double,
498 "string" => Type::Str,
499 "objectpath" => Type::ObjectPath,
500 "signature" => Type::Signature,
501 _ => return None,
502 })
503}
504
505struct Parser<'a> {
506 lexer: Lexer<'a>,
507 ahead: TextResult<Token>,
511 last_end: usize,
515 depth: usize,
518}
519
520impl<'a> Parser<'a> {
521 fn new(text: &'a str) -> Parser<'a> {
522 let mut lexer = Lexer::new(text);
523 let ahead = lexer.next();
524 Parser {
525 lexer,
526 ahead,
527 last_end: 0,
528 depth: 0,
529 }
530 }
531
532 fn peek(&self) -> Option<&Tok> {
533 self.ahead.as_ref().ok().map(|token| &token.tok)
534 }
535
536 fn ahead_start(&self) -> usize {
540 self.ahead
541 .as_ref()
542 .map_or(self.last_end, |token| token.span.start)
543 }
544
545 fn bump(&mut self) -> TextResult<Token> {
546 let next = self.lexer.next();
547 let token = std::mem::replace(&mut self.ahead, next)?;
548 self.last_end = token.span.end;
549 Ok(token)
550 }
551
552 fn expect_end(&mut self) -> TextResult<()> {
553 match &self.ahead {
554 Ok(token) if token.tok == Tok::End => Ok(()),
555 Ok(token) => Err(TextError::new(
556 Span::point(token.span.start),
557 "expected end of input",
558 )),
559 Err(error) => Err(error.clone()),
560 }
561 }
562
563 fn nested(&mut self) -> TextResult<Node> {
565 self.depth += 1;
566 let node = self.value();
567 self.depth -= 1;
568 node
569 }
570
571 fn value(&mut self) -> TextResult<Node> {
572 if self.depth >= MAX_NESTING {
573 return Err(TextError::new(
574 Span::point(self.ahead_start()),
575 "variant nested too deeply",
576 ));
577 }
578 let token = self.bump()?;
579 let start = token.span.start;
580 match token.tok {
581 Tok::Str(text) => Ok(Node {
582 ast: Ast::Str(text),
583 span: token.span,
584 }),
585 Tok::ByteString(bytes) => Ok(Node {
586 ast: Ast::ByteString(bytes),
587 span: token.span,
588 }),
589 Tok::Number(text) => Ok(Node {
590 ast: Ast::Number(text),
591 span: token.span,
592 }),
593 Tok::TypeDecl(signature) => {
594 let parsed = Type::parse(&signature).ok();
599 let levels = match &parsed {
600 Some(ty) => type_depth(ty),
601 None => match classify_declaration(&signature) {
602 Declaration::Indefinite(levels) => levels,
603 Declaration::Invalid => {
604 return Err(TextError::new(token.span, "invalid type declaration"));
605 }
606 },
607 };
608 if self.depth + levels > MAX_NESTING {
612 return Err(TextError::new(
613 token.span,
614 "type declaration recurses too deeply",
615 ));
616 }
617 let Some(ty) = parsed else {
618 return Err(TextError::new(
619 token.span,
620 "type declarations must be definite",
621 ));
622 };
623 let child = self.nested()?;
624 let end = child.span.end;
625 Ok(Node {
626 ast: Ast::Typed(ty, Box::new(child)),
627 span: Span::new(start, end),
628 })
629 }
630 Tok::Word(word) if is_keyword_shaped(&word) => self.word(&word, token.span),
634 Tok::Open('[') => self.array(start),
635 Tok::Open('{') => self.dict(start),
636 Tok::Open('(') => self.tuple(start),
637 Tok::Open('<') => {
638 let child = self.nested()?;
639 self.close('>', "expected '>' to follow variant value")?;
640 Ok(Node {
641 ast: Ast::Variant(Box::new(child)),
642 span: Span::new(start, self.last_end),
643 })
644 }
645 _ => Err(TextError::new(Span::point(start), "expected value")),
646 }
647 }
648
649 fn word(&mut self, word: &str, span: Span) -> TextResult<Node> {
650 match word {
651 "true" => Ok(Node {
652 ast: Ast::Bool(true),
653 span,
654 }),
655 "false" => Ok(Node {
656 ast: Ast::Bool(false),
657 span,
658 }),
659 "nan" | "inf" => Ok(Node {
662 ast: Ast::Number(word.to_owned()),
663 span,
664 }),
665 "nothing" => Ok(Node {
666 ast: Ast::Maybe(None),
667 span,
668 }),
669 "just" => {
670 let child = self.nested()?;
671 let end = child.span.end;
672 Ok(Node {
673 ast: Ast::Maybe(Some(Box::new(child))),
674 span: Span::new(span.start, end),
675 })
676 }
677 _ => match keyword_type(word) {
678 Some(ty) => {
679 let child = self.nested()?;
680 let end = child.span.end;
681 Ok(Node {
682 ast: Ast::Typed(ty, Box::new(child)),
683 span: Span::new(span.start, end),
684 })
685 }
686 None => Err(TextError::new(span, "unknown keyword")),
687 },
688 }
689 }
690
691 fn array(&mut self, start: usize) -> TextResult<Node> {
692 let mut items = Vec::new();
693 if matches!(self.peek(), Some(Tok::Close(']'))) {
694 self.bump()?;
695 return Ok(Node {
696 ast: Ast::Array(items),
697 span: Span::new(start, self.last_end),
698 });
699 }
700 loop {
701 items.push(self.nested()?);
702 match self.peek() {
703 Some(Tok::Comma) => {
704 self.bump()?;
705 }
706 Some(Tok::Close(']')) => {
707 self.bump()?;
708 break;
709 }
710 _ => {
711 return Err(TextError::new(
712 Span::point(self.ahead_start()),
713 "expected ',' or ']' to follow array element",
714 ));
715 }
716 }
717 }
718 Ok(Node {
719 ast: Ast::Array(items),
720 span: Span::new(start, self.last_end),
721 })
722 }
723
724 fn dict(&mut self, start: usize) -> TextResult<Node> {
725 if matches!(self.peek(), Some(Tok::Close('}'))) {
726 self.bump()?;
727 return Ok(Node {
728 ast: Ast::Dict(Vec::new()),
729 span: Span::new(start, self.last_end),
730 });
731 }
732 let first_key = self.nested()?;
733 if matches!(self.peek(), Some(Tok::Comma)) {
736 self.bump()?;
737 let value = self.nested()?;
738 self.close('}', "expected '}' at end of dictionary entry")?;
739 return Ok(Node {
740 ast: Ast::Entry(Box::new(first_key), Box::new(value)),
741 span: Span::new(start, self.last_end),
742 });
743 }
744 if !matches!(self.peek(), Some(Tok::Colon)) {
745 return Err(TextError::new(
746 Span::point(self.ahead_start()),
747 "expected ':' or ',' to follow dictionary entry key",
748 ));
749 }
750 self.bump()?;
751 let mut entries = vec![(first_key, self.nested()?)];
752 loop {
753 match self.peek() {
754 Some(Tok::Comma) => {
755 self.bump()?;
756 }
757 Some(Tok::Close('}')) => {
758 self.bump()?;
759 break;
760 }
761 _ => {
762 return Err(TextError::new(
763 Span::point(self.ahead_start()),
764 "expected ',' or '}' to follow dictionary entry",
765 ));
766 }
767 }
768 let key = self.nested()?;
769 if !matches!(self.peek(), Some(Tok::Colon)) {
770 return Err(TextError::new(
771 Span::point(self.ahead_start()),
772 "expected ':' to follow dictionary entry key",
773 ));
774 }
775 self.bump()?;
776 entries.push((key, self.nested()?));
777 }
778 Ok(Node {
779 ast: Ast::Dict(entries),
780 span: Span::new(start, self.last_end),
781 })
782 }
783
784 fn tuple(&mut self, start: usize) -> TextResult<Node> {
785 let mut items = Vec::new();
786 if matches!(self.peek(), Some(Tok::Close(')'))) {
787 self.bump()?;
788 return Ok(Node {
789 ast: Ast::Tuple(items),
790 span: Span::new(start, self.last_end),
791 });
792 }
793 items.push(self.nested()?);
796 if !matches!(self.peek(), Some(Tok::Comma)) {
797 return Err(TextError::new(
798 Span::point(self.ahead_start()),
799 "expected ',' after first tuple element",
800 ));
801 }
802 self.bump()?;
803 if matches!(self.peek(), Some(Tok::Close(')'))) {
804 self.bump()?;
805 return Ok(Node {
806 ast: Ast::Tuple(items),
807 span: Span::new(start, self.last_end),
808 });
809 }
810 loop {
811 items.push(self.nested()?);
812 match self.peek() {
813 Some(Tok::Comma) => {
814 self.bump()?;
815 }
816 Some(Tok::Close(')')) => {
817 self.bump()?;
818 break;
819 }
820 _ => {
821 return Err(TextError::new(
822 Span::point(self.ahead_start()),
823 "expected ',' or ')' to follow tuple element",
824 ));
825 }
826 }
827 }
828 Ok(Node {
829 ast: Ast::Tuple(items),
830 span: Span::new(start, self.last_end),
831 })
832 }
833
834 fn close(&mut self, bracket: char, reason: &str) -> TextResult<()> {
835 if matches!(self.peek(), Some(Tok::Close(c)) if *c == bracket) {
836 self.bump()?;
837 return Ok(());
838 }
839 Err(TextError::new(Span::point(self.ahead_start()), reason))
840 }
841}
842
843enum Declaration {
847 Indefinite(usize),
851 Invalid,
853}
854
855const MAX_DECLARATION_DEPTH: usize = crate::de::MAX_VALUE_DEPTH;
862
863fn type_depth(ty: &Type) -> usize {
876 match ty {
877 Type::Maybe(elem) | Type::Array(elem) => 1 + type_depth(elem),
878 Type::Tuple(members) => members
879 .iter()
880 .map(|member| 1 + type_depth(member))
881 .max()
882 .unwrap_or(0),
883 Type::DictEntry(_, value) => 1 + type_depth(value),
884 _ => 1,
885 }
886}
887
888fn classify_declaration(signature: &str) -> Declaration {
892 let bytes = signature.as_bytes();
893 let mut pos = 0;
894 let mut indefinite = false;
895 match scan_declared_type(bytes, &mut pos, 0, &mut indefinite) {
896 Some(levels) if pos == bytes.len() && indefinite => Declaration::Indefinite(levels),
897 _ => Declaration::Invalid,
898 }
899}
900
901fn scan_declared_type(
908 sig: &[u8],
909 pos: &mut usize,
910 depth: usize,
911 indefinite: &mut bool,
912) -> Option<usize> {
913 if depth > MAX_DECLARATION_DEPTH {
914 return None;
915 }
916 let &c = sig.get(*pos)?;
917 *pos += 1;
918 match c {
919 b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
920 | b'g' | b'v' => Some(1),
921 b'r' | b'*' | b'?' => {
922 *indefinite = true;
923 Some(1)
924 }
925 b'm' | b'a' => Some(1 + scan_declared_type(sig, pos, depth + 1, indefinite)?),
926 b'(' => {
927 let mut levels = 0;
928 while sig.get(*pos) != Some(&b')') {
929 let member = scan_declared_type(sig, pos, depth + 1, indefinite)?;
930 levels = levels.max(1 + member);
931 }
932 *pos += 1;
933 Some(levels)
934 }
935 b'{' => {
936 scan_declared_type(sig, pos, depth + 1, indefinite)?;
937 let value = scan_declared_type(sig, pos, depth + 1, indefinite)?;
938 if sig.get(*pos) != Some(&b'}') {
939 return None;
940 }
941 *pos += 1;
942 Some(1 + value)
943 }
944 _ => None,
945 }
946}
947
948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952enum NumberKind {
953 Integer,
954 Double,
955}
956
957fn split_sign(text: &str) -> (bool, &str) {
962 match text.strip_prefix('-') {
963 Some(rest) => (true, rest),
964 None => (false, text),
965 }
966}
967
968fn is_special_double(body: &str) -> bool {
973 matches!(body, "inf" | "infinity" | "nan")
974 || matches!(body.strip_prefix('+'), Some("inf" | "infinity" | "nan"))
975}
976
977fn number_kind(text: &str) -> NumberKind {
984 let (_, body) = split_sign(text);
985 if is_special_double(body) {
986 return NumberKind::Double;
987 }
988 let digits = body.strip_prefix('+').unwrap_or(body);
989 let hex = digits.starts_with("0x") || digits.starts_with("0X");
990 let fractional = if hex {
991 digits.contains('.')
992 } else {
993 digits.contains(['.', 'e'])
994 };
995 if fractional {
996 NumberKind::Double
997 } else {
998 NumberKind::Integer
999 }
1000}
1001
1002struct IntegerScan {
1007 value: u64,
1008 end: usize,
1009 overflow: bool,
1010}
1011
1012fn scan_integer(body: &str) -> IntegerScan {
1018 let bytes = body.as_bytes();
1019 let mut pos = 0;
1020 let mut negate = false;
1021 match bytes.first() {
1022 Some(b'+') => pos = 1,
1023 Some(b'-') => {
1024 negate = true;
1025 pos = 1;
1026 }
1027 _ => {}
1028 }
1029 let (radix, start) = if bytes.get(pos) == Some(&b'0')
1030 && matches!(bytes.get(pos + 1), Some(b'x' | b'X'))
1031 && bytes.get(pos + 2).is_some_and(u8::is_ascii_hexdigit)
1032 {
1033 (16u32, pos + 2)
1034 } else if bytes.get(pos) == Some(&b'0')
1035 && matches!(bytes.get(pos + 1), Some(b'b' | b'B'))
1036 && matches!(bytes.get(pos + 2), Some(b'0' | b'1'))
1037 {
1038 (2, pos + 2)
1039 } else if bytes.get(pos) == Some(&b'0') {
1040 (8, pos)
1041 } else {
1042 (10, pos)
1043 };
1044 let mut end = start;
1045 let mut value: u64 = 0;
1046 let mut overflow = false;
1047 while let Some(digit) = bytes.get(end).and_then(|c| char::from(*c).to_digit(radix)) {
1048 match value
1049 .checked_mul(u64::from(radix))
1050 .and_then(|v| v.checked_add(u64::from(digit)))
1051 {
1052 Some(next) => value = next,
1053 None => overflow = true,
1054 }
1055 end += 1;
1056 }
1057 if end == start {
1058 return IntegerScan {
1059 value: 0,
1060 end: 0,
1061 overflow: false,
1062 };
1063 }
1064 if negate {
1065 value = value.wrapping_neg();
1066 }
1067 IntegerScan {
1068 value,
1069 end,
1070 overflow,
1071 }
1072}
1073
1074fn integer_literal(text: &str, span: Span) -> TextResult<(bool, u64)> {
1076 let (negative, body) = split_sign(text);
1077 let offset = text.len() - body.len();
1078 let scan = scan_integer(body);
1079 if scan.end != body.len() {
1080 let at = span.start + offset + scan.end;
1081 return Err(TextError::new(
1082 Span::new(at, at + 1),
1083 "invalid character in number",
1084 ));
1085 }
1086 if scan.overflow {
1087 return Err(TextError::new(span, "integer too big for any type"));
1088 }
1089 Ok((negative, scan.value))
1090}
1091
1092struct DoubleScan {
1094 value: f64,
1096 end: usize,
1100 exact: bool,
1105}
1106
1107fn scan_double(text: &str) -> DoubleScan {
1109 let bytes = text.as_bytes();
1110 let mut pos = 0;
1111 let mut negative = false;
1112 match bytes.first() {
1113 Some(b'-') => {
1114 negative = true;
1115 pos = 1;
1116 }
1117 Some(b'+') => pos = 1,
1118 _ => {}
1119 }
1120 let signed = |value: f64| if negative { -value } else { value };
1121 let rest = &text[pos..];
1122 for (word, value) in [
1123 ("infinity", f64::INFINITY),
1124 ("inf", f64::INFINITY),
1125 ("nan", f64::NAN),
1126 ] {
1127 if rest.len() >= word.len() && rest[..word.len()].eq_ignore_ascii_case(word) {
1128 return DoubleScan {
1129 value: signed(value),
1130 end: pos + word.len(),
1131 exact: true,
1132 };
1133 }
1134 }
1135 if bytes.get(pos) == Some(&b'0') && matches!(bytes.get(pos + 1), Some(b'x' | b'X')) {
1136 return match scan_hex_double(bytes, pos + 2) {
1137 Some(scan) => DoubleScan {
1138 value: signed(scan.value),
1139 ..scan
1140 },
1141 None => nothing_read(),
1142 };
1143 }
1144 let mut end = pos;
1145 let mut integer = String::new();
1146 while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_digit()) {
1147 integer.push(char::from(c));
1148 end += 1;
1149 }
1150 let mut fraction = String::new();
1151 if bytes.get(end) == Some(&b'.') {
1152 let mut after = end + 1;
1153 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1154 fraction.push(char::from(c));
1155 after += 1;
1156 }
1157 end = after;
1158 }
1159 if integer.is_empty() && fraction.is_empty() {
1160 return nothing_read();
1161 }
1162 let mut exponent = String::new();
1163 if matches!(bytes.get(end), Some(b'e' | b'E')) {
1164 let mut after = end + 1;
1165 if matches!(bytes.get(after), Some(b'+' | b'-')) {
1166 exponent.push(char::from(bytes[after]));
1167 after += 1;
1168 }
1169 let digits = after;
1170 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1171 exponent.push(char::from(c));
1172 after += 1;
1173 }
1174 if after > digits {
1175 end = after;
1176 } else {
1177 exponent.clear();
1178 }
1179 }
1180 if integer.is_empty() {
1181 integer.push('0');
1182 }
1183 if fraction.is_empty() {
1184 fraction.push('0');
1185 }
1186 if exponent.is_empty() {
1187 exponent.push('0');
1188 }
1189 let value: f64 = format!("{integer}.{fraction}e{exponent}")
1190 .parse()
1191 .unwrap_or(f64::INFINITY);
1192 DoubleScan {
1193 value: signed(value),
1194 end,
1195 exact: false,
1196 }
1197}
1198
1199fn nothing_read() -> DoubleScan {
1201 DoubleScan {
1202 value: 0.0,
1203 end: 0,
1204 exact: false,
1205 }
1206}
1207
1208const HEX_MANTISSA_CAP: u128 = (u128::MAX - 15) / 16;
1213
1214fn scan_hex_double(bytes: &[u8], start: usize) -> Option<DoubleScan> {
1220 let mut end = start;
1221 let mut mantissa: u128 = 0;
1222 let mut sticky = false;
1223 let mut digits = 0usize;
1224 let mut shift: i32 = 0;
1225 while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_hexdigit()) {
1226 let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1227 if mantissa <= HEX_MANTISSA_CAP {
1228 mantissa = mantissa * 16 + value;
1229 } else {
1230 shift = shift.saturating_add(4);
1231 sticky |= value != 0;
1232 }
1233 digits += 1;
1234 end += 1;
1235 }
1236 if bytes.get(end) == Some(&b'.') {
1237 let mut after = end + 1;
1238 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_hexdigit()) {
1239 let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1240 if mantissa <= HEX_MANTISSA_CAP {
1241 mantissa = mantissa * 16 + value;
1242 shift = shift.saturating_sub(4);
1243 } else {
1244 sticky |= value != 0;
1245 }
1246 digits += 1;
1247 after += 1;
1248 }
1249 end = after;
1250 }
1251 if digits == 0 {
1252 return None;
1253 }
1254 if matches!(bytes.get(end), Some(b'p' | b'P')) {
1255 let mut after = end + 1;
1256 let mut negative = false;
1257 match bytes.get(after) {
1258 Some(b'-') => {
1259 negative = true;
1260 after += 1;
1261 }
1262 Some(b'+') => after += 1,
1263 _ => {}
1264 }
1265 let first = after;
1266 let mut exponent: i32 = 0;
1267 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1268 exponent = exponent
1269 .saturating_mul(10)
1270 .saturating_add(i32::from(c - b'0'));
1271 after += 1;
1272 }
1273 if after > first {
1274 shift = if negative {
1275 shift.saturating_sub(exponent)
1276 } else {
1277 shift.saturating_add(exponent)
1278 };
1279 end = after;
1280 }
1281 }
1282 let (value, exact) = round_binary(mantissa, sticky, shift);
1283 Some(DoubleScan { value, end, exact })
1284}
1285
1286fn round_binary(mantissa: u128, sticky: bool, shift: i32) -> (f64, bool) {
1293 if mantissa == 0 {
1294 return (0.0, true);
1295 }
1296 let width = i64::from(128 - mantissa.leading_zeros());
1297 let top = i64::from(shift) + width - 1;
1301 let lowest = (top - 52).max(-1074);
1302 let drop = lowest - i64::from(shift);
1303 let (mut significand, inexact) = if drop <= 0 {
1304 (mantissa << (-drop) as u32, sticky)
1306 } else if drop > 128 {
1307 (0u128, true)
1309 } else {
1310 let dropped = drop as u32;
1311 let (kept, rest) = if dropped == 128 {
1312 (0, mantissa)
1313 } else {
1314 (mantissa >> dropped, mantissa & ((1u128 << dropped) - 1))
1315 };
1316 let half = 1u128 << (dropped - 1);
1317 let up = rest > half || (rest == half && (sticky || kept & 1 == 1));
1318 (kept + u128::from(up), rest != 0 || sticky)
1319 };
1320 if significand == 0 {
1321 return (0.0, !inexact);
1322 }
1323 let mut lowest = lowest;
1324 if significand == 1u128 << 53 {
1325 significand >>= 1;
1327 lowest += 1;
1328 }
1329 let bits = if significand < 1u128 << 52 {
1330 significand as u64
1332 } else {
1333 let biased = lowest + 1075;
1334 if biased >= 2047 {
1335 return (f64::INFINITY, false);
1336 }
1337 ((biased as u64) << 52) | ((significand - (1u128 << 52)) as u64)
1338 };
1339 (f64::from_bits(bits), !inexact)
1340}
1341
1342fn double_literal(text: &str, span: Span) -> TextResult<f64> {
1350 let scan = scan_double(text);
1351 if scan.end != text.len() {
1352 let at = span.start + scan.end;
1353 return Err(TextError::new(
1354 Span::new(at, at + 1),
1355 "invalid character in number",
1356 ));
1357 }
1358 let value = scan.value;
1359 let subnormal = value != 0.0 && value.abs() < f64::MIN_POSITIVE;
1360 let (_, body) = split_sign(text);
1361 if !is_special_double(body) && (!value.is_finite() || (subnormal && !scan.exact)) {
1362 return Err(TextError::new(span, "number too big for any type"));
1363 }
1364 Ok(value)
1365}
1366
1367#[derive(Debug, Clone)]
1375enum Guess {
1376 Any(Span),
1377 Int,
1378 Decimal,
1379 StringLit,
1384 Basic(Type),
1385 Variant,
1386 Maybe(Box<Guess>),
1387 Array(Box<Guess>),
1388 Tuple(Vec<Guess>),
1389 Entry(Box<Guess>, Box<Guess>),
1390}
1391
1392impl Guess {
1393 fn of(ty: &Type) -> Guess {
1395 match ty {
1396 Type::Variant => Guess::Variant,
1397 Type::Maybe(elem) => Guess::Maybe(Box::new(Guess::of(elem))),
1398 Type::Array(elem) => Guess::Array(Box::new(Guess::of(elem))),
1399 Type::Tuple(members) => Guess::Tuple(members.iter().map(Guess::of).collect()),
1400 Type::DictEntry(key, value) => {
1401 Guess::Entry(Box::new(Guess::of(key)), Box::new(Guess::of(value)))
1402 }
1403 basic => Guess::Basic(basic.clone()),
1404 }
1405 }
1406}
1407
1408fn is_numeric(ty: &Type) -> bool {
1412 matches!(
1413 ty,
1414 Type::Byte
1415 | Type::I16
1416 | Type::U16
1417 | Type::I32
1418 | Type::U32
1419 | Type::I64
1420 | Type::U64
1421 | Type::Handle
1422 | Type::Double
1423 )
1424}
1425
1426fn unify(left: &Guess, right: &Guess) -> Option<Guess> {
1431 match (left, right) {
1432 (Guess::Any(_), other) | (other, Guess::Any(_)) => Some(other.clone()),
1433 (Guess::Int, Guess::Int) => Some(Guess::Int),
1434 (Guess::Int, Guess::Decimal) | (Guess::Decimal, Guess::Int) => Some(Guess::Decimal),
1435 (Guess::Decimal, Guess::Decimal) => Some(Guess::Decimal),
1436 (Guess::StringLit, Guess::StringLit) => Some(Guess::StringLit),
1437 (Guess::StringLit, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::StringLit)
1438 if matches!(ty, Type::Str | Type::ObjectPath | Type::Signature) =>
1439 {
1440 Some(Guess::Basic(ty.clone()))
1441 }
1442 (Guess::Int, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::Int) if is_numeric(ty) => {
1443 Some(Guess::Basic(ty.clone()))
1444 }
1445 (Guess::Decimal, Guess::Basic(Type::Double))
1446 | (Guess::Basic(Type::Double), Guess::Decimal) => Some(Guess::Basic(Type::Double)),
1447 (Guess::Basic(a), Guess::Basic(b)) if a == b => Some(Guess::Basic(a.clone())),
1448 (Guess::Variant, Guess::Variant) => Some(Guess::Variant),
1449 (Guess::Maybe(a), Guess::Maybe(b)) => Some(Guess::Maybe(Box::new(unify(a, b)?))),
1450 (Guess::Maybe(a), other) | (other, Guess::Maybe(a)) => {
1451 Some(Guess::Maybe(Box::new(unify(a, other)?)))
1452 }
1453 (Guess::Array(a), Guess::Array(b)) => Some(Guess::Array(Box::new(unify(a, b)?))),
1454 (Guess::Tuple(a), Guess::Tuple(b)) if a.len() == b.len() => {
1455 let mut members = Vec::with_capacity(a.len());
1456 for (x, y) in a.iter().zip(b) {
1457 members.push(unify(x, y)?);
1458 }
1459 Some(Guess::Tuple(members))
1460 }
1461 (Guess::Entry(ka, va), Guess::Entry(kb, vb)) => Some(Guess::Entry(
1462 Box::new(unify(ka, kb)?),
1463 Box::new(unify(va, vb)?),
1464 )),
1465 _ => None,
1466 }
1467}
1468
1469fn resolve(guess: &Guess) -> TextResult<Type> {
1474 Ok(match guess {
1475 Guess::Any(span) => return Err(TextError::new(*span, CANNOT_INFER)),
1476 Guess::Int => Type::I32,
1477 Guess::Decimal => Type::Double,
1478 Guess::StringLit => Type::Str,
1479 Guess::Basic(ty) => ty.clone(),
1480 Guess::Variant => Type::Variant,
1481 Guess::Maybe(elem) => Type::maybe(resolve(elem)?),
1482 Guess::Array(elem) => Type::array(resolve(elem)?),
1483 Guess::Tuple(members) => {
1484 Type::tuple(members.iter().map(resolve).collect::<TextResult<_>>()?)
1485 }
1486 Guess::Entry(key, value) => Type::dict_entry(resolve(key)?, resolve(value)?),
1487 })
1488}
1489
1490fn value_type(node: &Node) -> TextResult<Type> {
1496 let guess = infer(node)?;
1497 resolve(&guess).map_err(|error| {
1498 if error.reason == CANNOT_INFER {
1499 TextError::new(node.span, CANNOT_INFER)
1500 } else {
1501 error
1502 }
1503 })
1504}
1505
1506fn cannot_parse(span: Span, ty: &Type) -> TextError {
1507 TextError::new(
1508 span,
1509 format!("can not parse as value of type '{}'", ty.signature()),
1510 )
1511}
1512
1513fn no_common_type(first: Span, other: Span) -> TextError {
1518 TextError {
1519 spans: vec![first, other],
1520 reason: "unable to find a common type".to_owned(),
1521 }
1522}
1523
1524fn infer(node: &Node) -> TextResult<Guess> {
1525 Ok(match &node.ast {
1526 Ast::Bool(_) => Guess::Basic(Type::Bool),
1527 Ast::Number(text) => match number_kind(text) {
1528 NumberKind::Integer => Guess::Int,
1529 NumberKind::Double => Guess::Decimal,
1530 },
1531 Ast::Str(_) => Guess::StringLit,
1532 Ast::ByteString(_) => Guess::Array(Box::new(Guess::Basic(Type::Byte))),
1533 Ast::Typed(ty, _) => Guess::of(ty),
1537 Ast::Maybe(None) => Guess::Maybe(Box::new(Guess::Any(node.span))),
1538 Ast::Maybe(Some(child)) => Guess::Maybe(Box::new(infer(child)?)),
1539 Ast::Array(items) => {
1540 let Some((first, rest)) = items.split_first() else {
1541 return Ok(Guess::Array(Box::new(Guess::Any(node.span))));
1542 };
1543 let mut common = infer(first)?;
1544 for item in rest {
1545 let found = infer(item)?;
1546 common =
1547 unify(&common, &found).ok_or_else(|| no_common_type(first.span, item.span))?;
1548 }
1549 Guess::Array(Box::new(common))
1550 }
1551 Ast::Dict(entries) => {
1552 let Some(((first_key, first_value), rest)) = entries.split_first() else {
1553 return Ok(Guess::Array(Box::new(Guess::Entry(
1554 Box::new(Guess::Any(node.span)),
1555 Box::new(Guess::Any(node.span)),
1556 ))));
1557 };
1558 let mut key = infer(first_key)?;
1559 let value = infer(first_value)?;
1564 for (k, _) in rest {
1565 let found = infer(k)?;
1566 key = unify(&key, &found).ok_or_else(|| no_common_type(first_key.span, k.span))?;
1567 }
1568 check_basic_key(&key, node.span)?;
1569 Guess::Array(Box::new(Guess::Entry(Box::new(key), Box::new(value))))
1570 }
1571 Ast::Entry(key, value) => {
1572 let key = infer(key)?;
1573 check_basic_key(&key, node.span)?;
1574 Guess::Entry(Box::new(key), Box::new(infer(value)?))
1575 }
1576 Ast::Tuple(items) => Guess::Tuple(items.iter().map(infer).collect::<TextResult<_>>()?),
1577 Ast::Variant(child) => {
1578 value_type(child)?;
1580 Guess::Variant
1581 }
1582 })
1583}
1584
1585fn guess_is_basic(guess: &Guess) -> bool {
1591 match guess {
1592 Guess::Int | Guess::Decimal | Guess::StringLit => true,
1593 Guess::Basic(ty) => ty.is_basic(),
1594 _ => false,
1595 }
1596}
1597
1598fn check_basic_key(key: &Guess, span: Span) -> TextResult<()> {
1603 if guess_is_basic(key) {
1604 return Ok(());
1605 }
1606 Err(TextError::new(
1607 span,
1608 "dictionary keys must have basic types",
1609 ))
1610}
1611
1612fn is_object_path(text: &str) -> bool {
1619 if text == "/" {
1620 return true;
1621 }
1622 let Some(rest) = text.strip_prefix('/') else {
1623 return false;
1624 };
1625 !rest.is_empty()
1626 && rest.split('/').all(|element| {
1627 !element.is_empty()
1628 && element
1629 .bytes()
1630 .all(|c| c.is_ascii_alphanumeric() || c == b'_')
1631 })
1632}
1633
1634fn is_signature(text: &str) -> bool {
1639 let bytes = text.as_bytes();
1640 let mut pos = 0;
1641 while pos < bytes.len() {
1642 if !scan_signature_type(bytes, &mut pos, 0) {
1643 return false;
1644 }
1645 }
1646 true
1647}
1648
1649fn scan_signature_type(sig: &[u8], pos: &mut usize, depth: usize) -> bool {
1650 if depth > MAX_DECLARATION_DEPTH {
1651 return false;
1652 }
1653 let Some(&c) = sig.get(*pos) else {
1654 return false;
1655 };
1656 *pos += 1;
1657 match c {
1658 b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
1659 | b'g' | b'v' => true,
1660 b'a' => scan_signature_type(sig, pos, depth + 1),
1661 b'(' => {
1662 while sig.get(*pos) != Some(&b')') {
1663 if !scan_signature_type(sig, pos, depth + 1) {
1664 return false;
1665 }
1666 }
1667 *pos += 1;
1668 true
1669 }
1670 b'{' => {
1671 let key = sig.get(*pos).copied();
1672 if !key.is_some_and(|k| {
1673 matches!(
1674 k,
1675 b'b' | b'y'
1676 | b'n'
1677 | b'q'
1678 | b'i'
1679 | b'u'
1680 | b'x'
1681 | b't'
1682 | b'h'
1683 | b'd'
1684 | b's'
1685 | b'o'
1686 | b'g'
1687 )
1688 }) {
1689 return false;
1690 }
1691 *pos += 1;
1692 if !scan_signature_type(sig, pos, depth + 1) {
1693 return false;
1694 }
1695 if sig.get(*pos) != Some(&b'}') {
1696 return false;
1697 }
1698 *pos += 1;
1699 true
1700 }
1701 _ => false,
1702 }
1703}
1704
1705fn build(node: &Node, ty: &Type) -> TextResult<Value> {
1706 if let Type::Maybe(elem) = ty
1709 && !matches!(node.ast, Ast::Maybe(_) | Ast::Typed(..))
1710 {
1711 return Ok(Value::Maybe(Some(Box::new(build(node, elem)?))));
1712 }
1713 match (&node.ast, ty) {
1714 (Ast::Typed(_, child), _) => build(child, ty),
1715 (Ast::Bool(b), Type::Bool) => Ok(Value::Bool(*b)),
1716 (Ast::Number(text), _) => number_value(text, ty, node.span),
1717 (Ast::Str(text), Type::Str) => Ok(Value::Str(text.clone())),
1718 (Ast::Str(text), Type::ObjectPath) => {
1719 if !is_object_path(text) {
1720 return Err(TextError::new(node.span, "not a valid object path"));
1721 }
1722 Ok(Value::Str(text.clone()))
1723 }
1724 (Ast::Str(text), Type::Signature) => {
1725 if !is_signature(text) {
1726 return Err(TextError::new(node.span, "not a valid signature"));
1727 }
1728 Ok(Value::Str(text.clone()))
1729 }
1730 (Ast::ByteString(bytes), Type::Array(elem)) if **elem == Type::Byte => {
1731 Ok(Value::Bytes(bytes.clone()))
1732 }
1733 (Ast::Maybe(None), Type::Maybe(_)) => Ok(Value::Maybe(None)),
1734 (Ast::Maybe(Some(child)), Type::Maybe(elem)) => {
1735 Ok(Value::Maybe(Some(Box::new(build(child, elem)?))))
1736 }
1737 (Ast::Array(items), Type::Array(elem)) if **elem == Type::Byte => {
1738 let mut bytes = Vec::with_capacity(items.len());
1739 for item in items {
1740 match build(item, elem)? {
1741 Value::Byte(b) => bytes.push(b),
1742 _ => return Err(cannot_parse(item.span, elem)),
1743 }
1744 }
1745 Ok(Value::Bytes(bytes))
1746 }
1747 (Ast::Array(items), Type::Array(elem)) => Ok(Value::Array(
1748 items
1749 .iter()
1750 .map(|item| build(item, elem))
1751 .collect::<TextResult<_>>()?,
1752 )),
1753 (Ast::Dict(entries), Type::Array(elem)) => {
1754 let Type::DictEntry(key_ty, value_ty) = &**elem else {
1755 return Err(cannot_parse(node.span, ty));
1756 };
1757 let mut items = Vec::with_capacity(entries.len());
1758 for (key, value) in entries {
1759 items.push(Value::Tuple(vec![
1760 build(key, key_ty)?,
1761 build(value, value_ty)?,
1762 ]));
1763 }
1764 Ok(Value::Array(items))
1765 }
1766 (Ast::Entry(key, value), Type::DictEntry(key_ty, value_ty)) => Ok(Value::Tuple(vec![
1767 build(key, key_ty)?,
1768 build(value, value_ty)?,
1769 ])),
1770 (Ast::Tuple(items), Type::Tuple(members)) if items.len() == members.len() => {
1771 Ok(Value::Tuple(
1772 items
1773 .iter()
1774 .zip(members)
1775 .map(|(item, member)| build(item, member))
1776 .collect::<TextResult<_>>()?,
1777 ))
1778 }
1779 (Ast::Variant(child), Type::Variant) => {
1780 let child_ty = value_type(child)?;
1781 let value = build(child, &child_ty)?;
1782 Ok(Value::variant(child_ty, value))
1783 }
1784 _ => Err(cannot_parse(node.span, ty)),
1785 }
1786}
1787
1788fn number_value(text: &str, ty: &Type, span: Span) -> TextResult<Value> {
1794 if matches!(ty, Type::Double) {
1795 return Ok(Value::double(double_literal(text, span)?));
1796 }
1797 if !is_numeric(ty) {
1798 return Err(cannot_parse(span, ty));
1799 }
1800 let (negative, magnitude) = integer_literal(text, span)?;
1801 let value = if negative {
1802 -i128::from(magnitude)
1803 } else {
1804 i128::from(magnitude)
1805 };
1806 let range = || {
1807 TextError::new(
1808 span,
1809 format!("number out of range for type '{}'", ty.signature()),
1810 )
1811 };
1812 Ok(match ty {
1813 Type::Byte => Value::Byte(u8::try_from(value).map_err(|_| range())?),
1814 Type::I16 => Value::I16(i16::try_from(value).map_err(|_| range())?),
1815 Type::U16 => Value::U16(u16::try_from(value).map_err(|_| range())?),
1816 Type::I32 | Type::Handle => Value::I32(i32::try_from(value).map_err(|_| range())?),
1817 Type::U32 => Value::U32(u32::try_from(value).map_err(|_| range())?),
1818 Type::I64 => Value::I64(i64::try_from(value).map_err(|_| range())?),
1819 Type::U64 => Value::U64(u64::try_from(value).map_err(|_| range())?),
1820 _ => return Err(cannot_parse(span, ty)),
1821 })
1822}
1823
1824#[cfg(test)]
1825mod tests {
1826 use super::*;
1827 use crate::{to_bytes, to_text};
1828
1829 fn round(text: &str) -> String {
1835 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1836 to_bytes(&ty, &value).unwrap_or_else(|e| panic!("{text}: {e:?}"));
1838 to_text(&ty, &value).unwrap()
1839 }
1840
1841 fn refuse(text: &str) -> String {
1842 from_text(text)
1843 .map(|(ty, _)| ty.signature())
1844 .expect_err(&format!("{text} was accepted"))
1845 .to_string()
1846 }
1847
1848 fn double(text: &str) -> f64 {
1850 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1851 assert_eq!(ty.signature(), "d", "type of {text}");
1852 match value {
1853 Value::Double(bits) => f64::from_bits(bits),
1854 other => panic!("{text}: {other:?}"),
1855 }
1856 }
1857
1858 #[test]
1862 fn reads_the_forms_the_tool_accepts() {
1863 let cases: &[(&str, &str)] = &[
1864 ("'a string'", "'a string'"),
1865 ("\"double quoted\"", "'double quoted'"),
1866 ("uint32 42", "uint32 42"),
1867 ("42", "42"),
1868 ("-42", "-42"),
1869 ("+42", "42"),
1870 ("int64 -5", "int64 -5"),
1871 ("@x 5", "int64 5"),
1872 ("uint64 99", "uint64 99"),
1873 ("byte 0x41", "byte 0x41"),
1874 ("true", "true"),
1875 ("false", "false"),
1876 ("1.5", "1.5"),
1877 ("0.1", "0.10000000000000001"),
1878 ("1.0", "1.0"),
1879 ("1e3", "1000.0"),
1880 ("-0.0", "-0.0"),
1881 ("1.7976931348623157e308", "1.7976931348623157e+308"),
1882 ("int16 -5", "int16 -5"),
1883 ("uint16 5", "uint16 5"),
1884 ("handle 5", "handle 5"),
1885 ("objectpath '/a/b'", "objectpath '/a/b'"),
1886 ("objectpath '/'", "objectpath '/'"),
1887 ("objectpath '/a_b'", "objectpath '/a_b'"),
1888 ("objectpath '/A/9'", "objectpath '/A/9'"),
1889 ("signature 'ay'", "signature 'ay'"),
1890 ("signature ''", "signature ''"),
1891 ("signature 'ii'", "signature 'ii'"),
1892 ("signature '{sv}'", "signature '{sv}'"),
1893 ("@o '/a/b'", "objectpath '/a/b'"),
1894 ("@g 'ay'", "signature 'ay'"),
1895 ("['a','b']", "['a', 'b']"),
1896 ("@as ['a','b']", "['a', 'b']"),
1897 ("@ay [1,2,3]", "[byte 0x01, 0x02, 0x03]"),
1898 ("b'bytes'", "b'bytes'"),
1899 ("b\"double\"", "b'double'"),
1900 ("{'x': 'y'}", "{'x': 'y'}"),
1901 ("@a{ss} {'x': 'y'}", "{'x': 'y'}"),
1902 ("('a', 5)", "('a', 5)"),
1903 ("<'nested variant'>", "<'nested variant'>"),
1904 ("<<'x'>>", "<<'x'>>"),
1905 ("@v <'x'>", "<'x'>"),
1906 ("@ms 'just'", "@ms 'just'"),
1907 ("@ms nothing", "@ms nothing"),
1908 ("just 'x'", "@ms 'x'"),
1909 ("@mi 5", "@mi 5"),
1910 ("@mu 7", "@mu 7"),
1911 ("'a=b'", "'a=b'"),
1912 ("[2, 1.5]", "[2.0, 1.5]"),
1913 ("[1.5, 2]", "[1.5, 2.0]"),
1914 ("[[1],[2]]", "[[1], [2]]"),
1915 ("{'a': 1, 'b': 2}", "{'a': 1, 'b': 2}"),
1916 ("{1: 'a'}", "{1: 'a'}"),
1917 ("[@ms 'a', 'b']", "[@ms 'a', 'b']"),
1918 ("['a', @ms 'b']", "[@ms 'a', 'b']"),
1919 ("[nothing, 'a']", "[@ms nothing, 'a']"),
1920 ("[just 'a', nothing]", "[@ms 'a', nothing]"),
1921 ("@(si) ('a', 5)", "('a', 5)"),
1922 ("@ai []", "@ai []"),
1923 ("@as []", "@as []"),
1924 ("@a{sv} {}", "@a{sv} {}"),
1925 ("@aai [[], []]", "[@ai [], []]"),
1926 ("[b'x', b'y']", "[b'x', b'y']"),
1927 ("[@o '/a', '/b']", "[objectpath '/a', '/b']"),
1928 ("@ao ['/a','/b']", "[objectpath '/a', '/b']"),
1929 ("'\\x41'", "'x41'"),
1930 ("'a\\'b'", "\"a'b\""),
1931 ("\"a'b\"", "\"a'b\""),
1932 ("'\\''", "\"'\""),
1933 (" 42 ", "42"),
1934 ("@i 42", "42"),
1935 ("@au [1,2]", "[uint32 1, 2]"),
1936 ("[<'a'>, <5>]", "[<'a'>, <5>]"),
1937 ("0x41", "65"),
1938 ("017", "15"),
1939 ("(1,)", "(1,)"),
1940 ("()", "()"),
1941 ("[1,2,3]", "[1, 2, 3]"),
1942 ("{'a', 5}", "{'a', 5}"),
1943 ("'a\\0b'", "'a0b'"),
1944 ("'a\\tb'", "'a\\tb'"),
1945 ("'\\u00e9'", "'é'"),
1946 ("b'\\u0000'", "b'u0000'"),
1949 ("b'a\\u0000b'", "b'au0000b'"),
1950 ("b'a\0b'", "b'a'"),
1953 ];
1954 for (input, expected) in cases {
1955 assert_eq!(round(input), *expected, "reading {input}");
1956 }
1957 }
1958
1959 #[test]
1964 fn reads_the_numeric_literals_the_tool_accepts() {
1965 let cases: &[(&str, &str)] = &[
1966 ("0b101", "5"),
1968 ("0B101", "5"),
1969 ("0b0", "0"),
1970 ("byte 0b11111111", "byte 0xff"),
1971 ("@t 0b1", "uint64 1"),
1972 ("0xe", "14"),
1974 ("0xE", "14"),
1975 ("0x1e5", "485"),
1976 ("-0x1", "-1"),
1977 ("+0x10", "16"),
1978 ("0x1.8p1", "3.0"),
1979 ("@d 0x1.8p1", "3.0"),
1980 ("@d 0x10", "16.0"),
1981 ("@t 0xFFFFFFFFFFFFFFFF", "uint64 18446744073709551615"),
1982 ("@d 017", "17.0"),
1984 ("double 0777", "777.0"),
1985 ("@d 08", "8.0"),
1986 ("@d 1E3", "1000.0"),
1987 ("double 1E3", "1000.0"),
1988 ("-", "0"),
1991 ("@i -", "0"),
1992 ("@y -", "byte 0x00"),
1993 ("@t -", "uint64 0"),
1994 ("-+5", "-5"),
1995 ("nan", "nan"),
1997 ("-nan", "-nan"),
1998 ("inf", "inf"),
1999 ("-inf", "-inf"),
2000 ("+inf", "inf"),
2001 ("+nan", "nan"),
2002 ("-infinity", "-inf"),
2003 ("double nan", "nan"),
2004 ("double inf", "inf"),
2005 ("@d nan", "nan"),
2006 ("just nan", "@md nan"),
2007 ("[1, nan]", "[1.0, nan]"),
2008 ("[nan, 1]", "[nan, 1.0]"),
2009 ("1e-400", "0.0"),
2012 ("-1e-400", "-0.0"),
2013 ("0.0e-400", "0.0"),
2014 ("2.2250738585072014e-308", "2.2250738585072014e-308"),
2015 ("1.", "1.0"),
2018 (".5", "0.5"),
2019 ("5.", "5.0"),
2020 ("-.5", "-0.5"),
2021 ("1.e3", "1000.0"),
2022 ];
2023 for (input, expected) in cases {
2024 assert_eq!(round(input), *expected, "reading {input}");
2025 }
2026 }
2027
2028 #[test]
2032 fn a_binary_exponent_out_of_range_is_clamped() {
2033 assert_eq!(round("0x0.0p-2147483645"), "0.0");
2034 assert_eq!(round("0x0.0p-9999999999"), "0.0");
2035 assert_eq!(round("0x1.0p-2147483645"), "0.0");
2036 assert_eq!(round("0x0.0p2147483647"), "0.0");
2037 }
2038
2039 #[test]
2044 fn reads_the_hexadecimal_doubles_the_tool_stores() {
2045 let cases: &[(&str, f64)] = &[
2046 ("@d 0x1.8p1", 3.0),
2047 ("@d 0x1p1023", 8.98846567431158e307),
2048 ("@d 0x1.fffffffffffff7ffffffffp1023", f64::MAX),
2049 ("@d 0x1.00000000000008p0", 1.0),
2050 (
2054 "@d 0xffffffffffffffffffffffffffffffffffffffffp0",
2055 1.461501637330903e48,
2056 ),
2057 ("@d 0x1.0000000000000000000000000000000000001p0", 1.0),
2058 ("@d 0x1000000000000000000000000000000000000p-140", 16.0),
2059 ("@d 0x1000000000000000000000000000000000001p-140", 16.0),
2060 (
2061 "@d 0x123456789abcdef123456789abcdef123456789abcdefp-100",
2062 8.596805828370696e22,
2063 ),
2064 ("@d 0x1p-1023", f64::from_bits(0x0008_0000_0000_0000)),
2066 ("@d 0x1p-1074", f64::from_bits(1)),
2067 ("@d 0x2p-1074", f64::from_bits(2)),
2068 ("@d 0x3p-1074", f64::from_bits(3)),
2069 ("@d 0x1.8p-1073", f64::from_bits(3)),
2070 ("@d -0x1p-1074", -f64::from_bits(1)),
2071 ("@d 0x1.000001p-1030", f64::from_bits(0x0000_1000_0010_0000)),
2072 ("@d 0x1.fffffffffffffffp-1023", f64::MIN_POSITIVE),
2074 ("@d 0x1.fffffffffffff8p-1023", f64::MIN_POSITIVE),
2075 ("@d 0x1p-1075", 0.0),
2078 ("@d 0x0.8p-1074", 0.0),
2079 ("@d 0x8000000000000000000000000000000000000000p-1234", 0.0),
2080 ("@d 0x1p-2000", 0.0),
2081 ("@d 0x1p-9999999999", 0.0),
2082 ("@d -0x1p-1075", -0.0),
2083 ("@d 0x0p2147483647", 0.0),
2084 ("@d 0x0p99999999999999999999", 0.0),
2085 ];
2086 for (input, expected) in cases {
2087 assert_eq!(
2088 double(input).to_bits(),
2089 expected.to_bits(),
2090 "reading {input}"
2091 );
2092 }
2093 }
2094
2095 #[test]
2102 fn refuses_the_hexadecimal_doubles_the_tool_refuses() {
2103 let cases: &[(&str, &str)] = &[
2104 ("@d 0x1.8p-1074", "3-14:number too big for any type"),
2107 ("@d 0x1.8p-1075", "3-14:number too big for any type"),
2108 (
2109 "@d 0x1.0000000000001p-1030",
2110 "3-26:number too big for any type",
2111 ),
2112 (
2113 "@d 0x1.0000000000000001p-1030",
2114 "3-29:number too big for any type",
2115 ),
2116 (
2117 "@d 0x1.0000000000000000001p-1075",
2118 "3-32:number too big for any type",
2119 ),
2120 (
2121 "@d 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1330",
2122 "3-80:number too big for any type",
2123 ),
2124 ("@d 0x1p1024", "3-11:number too big for any type"),
2126 ("@d 0x2p1023", "3-11:number too big for any type"),
2127 ("@d -0x1p1024", "3-12:number too big for any type"),
2128 (
2129 "@d 0x1.fffffffffffff8p1023",
2130 "3-26:number too big for any type",
2131 ),
2132 ("@d 0x1p2147483647", "3-17:number too big for any type"),
2133 (
2134 "@d 0x1p99999999999999999999",
2135 "3-27:number too big for any type",
2136 ),
2137 ];
2138 for (input, expected) in cases {
2139 assert_eq!(refuse(input), *expected, "refusing {input}");
2140 }
2141 }
2142
2143 #[test]
2149 fn refuses_what_the_tool_refuses_in_its_own_words() {
2150 let cases: &[(&str, &str)] = &[
2151 ("[]", "0-2:unable to infer type"),
2152 ("", "0:expected value"),
2153 ("garbage syntax (((", "0-7:unknown keyword"),
2154 (
2155 "uint32 99999999999999999999",
2156 "7-27:integer too big for any type",
2157 ),
2158 ("'unterminated", "0-13:unterminated string constant"),
2159 ("(1,2", "4:expected ',' or ')' to follow tuple element"),
2160 ("{'a':}", "5:expected value"),
2161 ("nothing", "0-7:unable to infer type"),
2162 ("@i 'str'", "3-8:can not parse as value of type 'i'"),
2163 ("3000000000", "0-10:number out of range for type 'i'"),
2164 (
2165 "9223372036854775807",
2166 "0-19:number out of range for type 'i'",
2167 ),
2168 (
2169 "18446744073709551615",
2170 "0-20:number out of range for type 'i'",
2171 ),
2172 ("99999999999999999999", "0-20:integer too big for any type"),
2173 ("uint32 -1", "7-9:number out of range for type 'u'"),
2174 ("uint32 4294967296", "7-17:number out of range for type 'u'"),
2175 ("byte 256", "5-8:number out of range for type 'y'"),
2176 ("0o17", "1-2:invalid character in number"),
2177 ("['a', 5]", "1-4,6-7:unable to find a common type"),
2178 (
2179 "{'a': 'b', 'c': 5}",
2180 "16-17:can not parse as value of type 's'",
2181 ),
2182 ("42 43", "3:expected end of input"),
2183 ("true false", "5:expected end of input"),
2184 ("@u", "2:expected value"),
2185 ("@", "0-1:invalid type declaration"),
2186 ("[,]", "1:expected value"),
2187 ("{}", "0-2:unable to infer type"),
2188 (
2189 "{'a'}",
2190 "4:expected ':' or ',' to follow dictionary entry key",
2191 ),
2192 ("(,)", "1:expected value"),
2193 ("@b 1", "3-4:can not parse as value of type 'b'"),
2194 ("B", "0:expected value"),
2195 ("_x", "0:expected value"),
2196 ("Foo", "0:expected value"),
2197 ("uint32x", "0-7:unknown keyword"),
2198 ("x1", "0:expected value"),
2199 ("a", "0:expected value"),
2200 ("%", "0:expected value"),
2201 ("=x", "0:expected value"),
2202 ("trueX", "0-5:unknown keyword"),
2203 ("TRUE", "0:expected value"),
2204 ("aB", "0-2:unknown keyword"),
2205 ("a_b", "0:expected value"),
2206 ("byte0x41", "0-8:unknown keyword"),
2207 ("just1", "0-5:unknown keyword"),
2208 ("ju st", "0-2:unknown keyword"),
2209 ("{[1]: 'a'}", "0-10:dictionary keys must have basic types"),
2210 ("(1)", "2:expected ',' after first tuple element"),
2212 ("('a')", "4:expected ',' after first tuple element"),
2213 ("((1))", "3:expected ',' after first tuple element"),
2214 ("((1,))", "5:expected ',' after first tuple element"),
2215 ("@(i) (1)", "7:expected ',' after first tuple element"),
2216 ("(((1),2),3)", "4:expected ',' after first tuple element"),
2217 ("(1 2)", "3:expected ',' after first tuple element"),
2218 ("(1,2,)", "5:expected value"),
2219 ("(1,2 3)", "5:expected ',' or ')' to follow tuple element"),
2220 ("1E3", "1-2:invalid character in number"),
2223 ("1E+3", "1-2:invalid character in number"),
2224 ("1E", "1-2:invalid character in number"),
2225 ("1d", "1-2:invalid character in number"),
2226 ("0x1p3", "3-4:invalid character in number"),
2227 ("5e-324", "0-6:number too big for any type"),
2230 ("1e-310", "0-6:number too big for any type"),
2231 ("1e-308", "0-6:number too big for any type"),
2232 ("1e400", "0-5:number too big for any type"),
2233 ("-1e400", "0-6:number too big for any type"),
2234 ("1.7976931348623157e309", "0-22:number too big for any type"),
2235 ("@d 5e-324", "3-9:number too big for any type"),
2236 ("1.5.5", "3-4:invalid character in number"),
2238 ("1..5", "2-3:invalid character in number"),
2239 ("1e", "1-2:invalid character in number"),
2240 ("1e+", "1-2:invalid character in number"),
2241 ("1.5e", "3-4:invalid character in number"),
2242 ("+", "0-1:invalid character in number"),
2243 ("++5", "0-1:invalid character in number"),
2244 ("+-5", "0-1:invalid character in number"),
2245 ("--5", "0-3:number out of range for type 'i'"),
2246 ("0xg", "1-2:invalid character in number"),
2247 ("0b12", "3-4:invalid character in number"),
2248 ("0b102", "4-5:invalid character in number"),
2249 ("0b1e1", "1-2:invalid character in number"),
2250 ("-INF", "1-2:invalid character in number"),
2251 ("+INFINITY", "0-1:invalid character in number"),
2252 ("infinity", "0-8:unknown keyword"),
2253 ("nan5", "0-4:unknown keyword"),
2254 ("nan(0x1)", "3:expected end of input"),
2255 ("byte nan", "5-6:invalid character in number"),
2257 ("@i nan", "3-4:invalid character in number"),
2258 ("uint64 nan", "7-8:invalid character in number"),
2259 ("byte 1.5", "6-7:invalid character in number"),
2260 ("uint32 1.5", "8-9:invalid character in number"),
2261 ("@x 1.5", "4-5:invalid character in number"),
2262 ("int32 1e3", "7-8:invalid character in number"),
2263 ("@d 0b101", "4-5:invalid character in number"),
2264 ("@d -", "3-4:invalid character in number"),
2265 (
2268 "int64 -9223372036854775809",
2269 "6-26:number out of range for type 'x'",
2270 ),
2271 (
2272 "-18446744073709551615",
2273 "0-21:number out of range for type 'i'",
2274 ),
2275 ("18446744073709551616", "0-20:integer too big for any type"),
2276 ("objectpath 'notapath'", "11-21:not a valid object path"),
2278 ("objectpath ''", "11-13:not a valid object path"),
2279 ("objectpath '/a/'", "11-16:not a valid object path"),
2280 ("objectpath '//'", "11-15:not a valid object path"),
2281 ("objectpath '/a-b'", "11-17:not a valid object path"),
2282 ("@o 'bad'", "3-8:not a valid object path"),
2283 ("signature 'zz'", "10-14:not a valid signature"),
2284 ("signature 'a'", "10-13:not a valid signature"),
2285 ("signature 'ms'", "10-14:not a valid signature"),
2286 ("signature 'r'", "10-13:not a valid signature"),
2287 ("signature '{vs}'", "10-16:not a valid signature"),
2288 ("@g 'zz'", "3-7:not a valid signature"),
2289 ("@z 5", "0-2:invalid type declaration"),
2293 ("@r 5", "0-2:type declarations must be definite"),
2294 ("@* 5", "0-2:type declarations must be definite"),
2295 ("@? 5", "0-2:type declarations must be definite"),
2296 ("@** 5", "0-3:invalid type declaration"),
2297 ("@i5", "0-3:invalid type declaration"),
2298 ("@ii", "0-3:invalid type declaration"),
2299 ("@m", "0-2:invalid type declaration"),
2300 ("@i(5)", "0-5:invalid type declaration"),
2301 ("@i[5]", "0-4:invalid type declaration"),
2302 ("@i)", "2:expected value"),
2303 ("@i,", "2:expected value"),
2304 ("@as [1]", "5-6:can not parse as value of type 's'"),
2306 ("@ab [1]", "5-6:can not parse as value of type 'b'"),
2307 ("@ai [1,'a']", "7-10:can not parse as value of type 'i'"),
2308 ("@as ['a', 5]", "10-11:can not parse as value of type 's'"),
2309 (
2310 "@a{ss} {'a': 5}",
2311 "13-14:can not parse as value of type 's'",
2312 ),
2313 (
2314 "@a{sv} {'a': 1}",
2315 "13-14:can not parse as value of type 'v'",
2316 ),
2317 ("@av [1]", "5-6:can not parse as value of type 'v'"),
2318 ("@ai 5", "4-5:can not parse as value of type 'ai'"),
2319 ("@i []", "3-5:can not parse as value of type 'i'"),
2320 ("@as [nothing]", "5-12:can not parse as value of type 's'"),
2321 ("[[]]", "0-4:unable to infer type"),
2324 ("just []", "0-7:unable to infer type"),
2325 ("just nothing", "0-12:unable to infer type"),
2326 ("just just nothing", "0-17:unable to infer type"),
2327 ("('a', [])", "0-9:unable to infer type"),
2328 ("[nothing]", "0-9:unable to infer type"),
2329 ("[nothing, nothing]", "0-18:unable to infer type"),
2330 ("{'a': nothing}", "0-14:unable to infer type"),
2331 ("[[[]]]", "0-6:unable to infer type"),
2332 ("[[], []]", "0-8:unable to infer type"),
2333 ("nothing 5", "0-7:unable to infer type"),
2334 ("nothing nothing", "0-7:unable to infer type"),
2335 ("[<[]>]", "2-4:unable to infer type"),
2336 ("<just nothing>", "1-13:unable to infer type"),
2337 ("{nothing: 1}", "0-12:dictionary keys must have basic types"),
2339 ("{{}: 'a'}", "0-9:dictionary keys must have basic types"),
2340 ("{<1>: 'a'}", "0-10:dictionary keys must have basic types"),
2341 ("{'a': 1, 2: 'b'}", "1-4,9-10:unable to find a common type"),
2344 ("{1: 'a', 'b': 2}", "1-2,9-12:unable to find a common type"),
2345 (
2346 "{'a': 'b', 5: 'c'}",
2347 "1-4,11-12:unable to find a common type",
2348 ),
2349 (
2350 "{'a': 1, 'b': 2, 'c': 'x'}",
2351 "22-25:can not parse as value of type 'i'",
2352 ),
2353 ("<1 2>", "3:expected '>' to follow variant value"),
2355 ("{'a', 5, 6}", "7:expected '}' at end of dictionary entry"),
2356 (
2357 "{'a': 1 'b': 2}",
2358 "8:expected ',' or '}' to follow dictionary entry",
2359 ),
2360 ("[1 2]", "3:expected ',' or ']' to follow array element"),
2361 ("'\\uZZZZ'", "3:invalid 4-character unicode escape"),
2363 ("'\\u'", "3:invalid 4-character unicode escape"),
2364 ("'\\u12'", "3-5:invalid 4-character unicode escape"),
2365 ("'\\u00'", "3-5:invalid 4-character unicode escape"),
2366 ("'\\U110000'", "3-9:invalid 8-character unicode escape"),
2367 ("'\\U0001'", "3-7:invalid 8-character unicode escape"),
2368 ("'\\u0000'", "3-7:invalid 4-character unicode escape"),
2372 ("'\\U00000000'", "3-11:invalid 8-character unicode escape"),
2373 ("'a\\u0000b'", "4-8:invalid 4-character unicode escape"),
2374 ("'ab\\u0000'", "5-9:invalid 4-character unicode escape"),
2375 ("'\\u0000x'", "3-7:invalid 4-character unicode escape"),
2376 ("@s '\\u0000'", "6-10:invalid 4-character unicode escape"),
2377 ("@o '/a\\u0000b'", "8-12:invalid 4-character unicode escape"),
2378 (
2379 "objectpath '\\u0000'",
2380 "14-18:invalid 4-character unicode escape",
2381 ),
2382 ("@g '\\u0000'", "6-10:invalid 4-character unicode escape"),
2383 (
2384 "signature 'a\\u0000y'",
2385 "14-18:invalid 4-character unicode escape",
2386 ),
2387 ("{'\\u0000': 1}", "4-8:invalid 4-character unicode escape"),
2388 (
2389 "{'a': '\\u0000'}",
2390 "9-13:invalid 4-character unicode escape",
2391 ),
2392 (
2393 "['a', '\\u0000']",
2394 "9-13:invalid 4-character unicode escape",
2395 ),
2396 ("<'\\u0000'>", "4-8:invalid 4-character unicode escape"),
2397 ("@ms '\\u0000'", "7-11:invalid 4-character unicode escape"),
2398 ("('\\u0000',)", "4-8:invalid 4-character unicode escape"),
2399 ("'\\ud800'", "3-7:invalid 4-character unicode escape"),
2401 ("'\\U0000d800'", "3-11:invalid 8-character unicode escape"),
2402 ("'\\U00110000'", "3-11:invalid 8-character unicode escape"),
2403 ("'a\0b'", "2-3:NUL byte in string constant"),
2407 ("'\0'", "1-2:NUL byte in string constant"),
2408 ("@o '/a\0b'", "6-7:NUL byte in string constant"),
2409 ("{'\0': 1}", "2-3:NUL byte in string constant"),
2410 ];
2411 for (input, expected) in cases {
2412 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2413 }
2414 }
2415
2416 #[test]
2422 fn a_dictionary_reads_its_values_against_the_first_entry() {
2423 let cases: &[(&str, &str)] = &[
2424 ("{'a': 1, 'b': uint32 2}", "{'a': 1, 'b': 2}"),
2427 ("{'a': uint32 2, 'b': 1}", "{'a': uint32 2, 'b': 1}"),
2428 ("{'a': 1.5, 'b': 1}", "{'a': 1.5, 'b': 1.0}"),
2429 ("{'a': 0x1.8p1, 'b': 1}", "{'a': 3.0, 'b': 1.0}"),
2430 ("{'a': 1.5, 'b': 1E3}", "{'a': 1.5, 'b': 1000.0}"),
2431 ("{'a': just 'y', 'b': 'x'}", "{'a': @ms 'y', 'b': 'x'}"),
2433 ("{'a': just 2, 'b': 1}", "{'a': @mi 2, 'b': 1}"),
2434 (
2435 "{'a': @ms nothing, 'b': 'x'}",
2436 "{'a': @ms nothing, 'b': 'x'}",
2437 ),
2438 ("{'a': just 1, 'b': nothing}", "{'a': @mi 1, 'b': nothing}"),
2439 ("{'a': [1], 'b': []}", "{'a': [1], 'b': []}"),
2441 ("{'a': {'d': 2}, 'c': {}}", "{'a': {'d': 2}, 'c': {}}"),
2442 ("{'a': <1>, 'b': <'x'>}", "{'a': <1>, 'b': <'x'>}"),
2443 (
2445 "{'a': 1, 'b': 2, 'c': uint32 3}",
2446 "{'a': 1, 'b': 2, 'c': 3}",
2447 ),
2448 (
2449 "{'a': uint32 1, 'b': 2, 'c': 3}",
2450 "{'a': uint32 1, 'b': 2, 'c': 3}",
2451 ),
2452 ("{1: 'a', 2.5: 'b'}", "{1.0: 'a', 2.5: 'b'}"),
2455 ("{2.5: 'a', 1: 'b'}", "{2.5: 'a', 1.0: 'b'}"),
2456 ];
2457 for (input, expected) in cases {
2458 assert_eq!(round(input), *expected, "reading {input}");
2459 }
2460 }
2461
2462 #[test]
2469 fn a_declaration_under_a_driven_type_gives_up_its_type() {
2470 let cases: &[(&str, &str)] = &[
2471 ("@as [@o '/a']", "['/a']"),
2472 ("@as [@ms 'a']", "['a']"),
2473 ("@ai [@u 5]", "[5]"),
2474 ("@ao ['/a', @s '/b']", "[objectpath '/a', '/b']"),
2475 ("@a{ss} {'a': @o '/b'}", "{'a': '/b'}"),
2476 ("{'a': 'x', 'b': @o '/y'}", "{'a': 'x', 'b': '/y'}"),
2477 (
2478 "{'a': 'x', 'b': @o 'notapath'}",
2479 "{'a': 'x', 'b': 'notapath'}",
2480 ),
2481 ("{'a': 'x', 'b': @g 'ii'}", "{'a': 'x', 'b': 'ii'}"),
2482 ("{'a': 'x', 'b': @ms 'y'}", "{'a': 'x', 'b': 'y'}"),
2483 ("{'a': 1, 'b': @mi 2}", "{'a': 1, 'b': 2}"),
2484 (
2485 "{'a': @g 'ii', 'b': 'x'}",
2486 "{'a': signature 'ii', 'b': 'x'}",
2487 ),
2488 ];
2489 for (input, expected) in cases {
2490 assert_eq!(round(input), *expected, "reading {input}");
2491 }
2492 let refusals: &[(&str, &str)] = &[
2494 ("@as [@i 5]", "8-9:can not parse as value of type 's'"),
2495 ("@ai [@d 1.5]", "9-10:invalid character in number"),
2496 (
2497 "{'a': 1, 'b': @s 'x'}",
2498 "17-20:can not parse as value of type 'i'",
2499 ),
2500 (
2501 "{'a': 1, 'b': @b true}",
2502 "17-21:can not parse as value of type 'i'",
2503 ),
2504 (
2505 "{'a': true, 'b': @i 1}",
2506 "20-21:can not parse as value of type 'b'",
2507 ),
2508 ("{'a': 1, 'b': @d 1.5}", "18-19:invalid character in number"),
2509 (
2510 "{'a': 'x', 'b': @ms nothing}",
2511 "20-27:can not parse as value of type 's'",
2512 ),
2513 (
2514 "{'a': 1, 'b': uint32 4294967296}",
2515 "21-31:number out of range for type 'i'",
2516 ),
2517 ];
2518 for (input, expected) in refusals {
2519 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2520 }
2521 }
2522
2523 #[test]
2531 fn refuses_a_dictionary_value_against_the_settled_type() {
2532 let cases: &[(&str, &str)] = &[
2533 ("{'a': 1, 'b': 1.5}", "15-16:invalid character in number"),
2535 (
2536 "{'a': 1, 'b': 0x1.8p1}",
2537 "17-18:invalid character in number",
2538 ),
2539 ("{'a': 1, 'b': 1e3}", "15-16:invalid character in number"),
2540 (
2541 "{'a': 1, 'b': 2, 'c': 1.5}",
2542 "23-24:invalid character in number",
2543 ),
2544 (
2546 "{'a': 'x', 'b': just 'y'}",
2547 "16-24:can not parse as value of type 's'",
2548 ),
2549 (
2550 "{'a': 'y', 'b': nothing}",
2551 "16-23:can not parse as value of type 's'",
2552 ),
2553 (
2554 "{'a': 1, 'b': just 2}",
2555 "14-20:can not parse as value of type 'i'",
2556 ),
2557 (
2558 "{'a': 1, 'b': 2, 'c': nothing}",
2559 "22-29:can not parse as value of type 'i'",
2560 ),
2561 (
2562 "{'a': 'x', 'b': 'y', 'c': just 'z'}",
2563 "26-34:can not parse as value of type 's'",
2564 ),
2565 (
2567 "{'a': (1,2), 'b': ('x','y')}",
2568 "19-22:can not parse as value of type 'i'",
2569 ),
2570 (
2571 "{'a': ('x','y'), 'b': (1,2)}",
2572 "23-24:can not parse as value of type 's'",
2573 ),
2574 (
2575 "{'a': [1], 'b': ['x']}",
2576 "17-20:can not parse as value of type 'i'",
2577 ),
2578 (
2579 "{'a': {'x': 1}, 'b': {'y': 'z'}}",
2580 "27-30:can not parse as value of type 'i'",
2581 ),
2582 ("{'a': @o '/y', 'b': 'x'}", "20-23:not a valid object path"),
2583 (
2584 "{'a': @o '/z', 'b': 'x', 'c': 'y'}",
2585 "20-23:not a valid object path",
2586 ),
2587 (
2588 "{'a': byte 1, 'b': 256}",
2589 "19-22:number out of range for type 'y'",
2590 ),
2591 (
2592 "{'a': 1, 'b': 99999999999999999999}",
2593 "14-34:integer too big for any type",
2594 ),
2595 (
2599 "{'a': 1, 'b': ['x', 5]}",
2600 "14-22:can not parse as value of type 'i'",
2601 ),
2602 (
2603 "{'a': 1, 'b': {[1]: 'a'}}",
2604 "14-24:can not parse as value of type 'i'",
2605 ),
2606 (
2607 "{'a': 1, 'b': <[]>}",
2608 "14-18:can not parse as value of type 'i'",
2609 ),
2610 (
2611 "{'a': 1, 'b': {'y': 'z'}}",
2612 "14-24:can not parse as value of type 'i'",
2613 ),
2614 (
2615 "{'a': 5, 'b': []}",
2616 "14-16:can not parse as value of type 'i'",
2617 ),
2618 (
2619 "{'a': [1], 'b': 'x'}",
2620 "16-19:can not parse as value of type 'ai'",
2621 ),
2622 (
2623 "{'a': <1>, 'b': 'x'}",
2624 "16-19:can not parse as value of type 'v'",
2625 ),
2626 (
2627 "{'a': 'x', 'b': b'y'}",
2628 "16-20:can not parse as value of type 's'",
2629 ),
2630 (
2631 "{'a': b'x', 'b': 'y'}",
2632 "17-20:can not parse as value of type 'ay'",
2633 ),
2634 ("{'a': <1>, 'b': <[]>}", "17-19:unable to infer type"),
2636 ("{'a': nothing, 'b': 'y'}", "0-24:unable to infer type"),
2639 (
2640 "{'a': nothing, 'b': 2, 'c': 3}",
2641 "0-30:unable to infer type",
2642 ),
2643 ("{'a': [], 'b': [1]}", "0-19:unable to infer type"),
2644 ("{'a': [], 'b': 5}", "0-17:unable to infer type"),
2645 ("{'a': [], 'b': 5, 'c': 6}", "0-25:unable to infer type"),
2646 ("{'a': [], 'b': ['x', 5]}", "0-24:unable to infer type"),
2647 ("{'a': {}, 'c': {'d': 2}}", "0-24:unable to infer type"),
2648 ("{'q': {'a': [], 'b': 5}}", "0-24:unable to infer type"),
2649 ("[{'a': [], 'b': 5}]", "0-19:unable to infer type"),
2650 ("({'a': [], 'b': 5},)", "0-20:unable to infer type"),
2651 ("just {'a': [], 'b': 5}", "0-22:unable to infer type"),
2652 ("<{'a': [], 'b': 5}>", "1-18:unable to infer type"),
2653 (
2656 "{[1]: [], 'b': 5}",
2657 "1-4,10-13:unable to find a common type",
2658 ),
2659 (
2660 "{'a': [], [1]: 5}",
2661 "1-4,10-13:unable to find a common type",
2662 ),
2663 ("{'a': 1, @u 2: 3}", "1-4,9-13:unable to find a common type"),
2664 ("{@o '/a': 1, 'b': 2}", "13-16:not a valid object path"),
2665 ("{'a': 1, @o '/b': 2}", "1-4:not a valid object path"),
2666 ];
2667 for (input, expected) in cases {
2668 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2669 }
2670 }
2671
2672 #[test]
2677 fn a_bytestring_ends_at_its_first_nul() {
2678 let cases: &[(&str, &[u8])] = &[
2679 (r"b'\0'", &[0]),
2680 (r"b''", &[0]),
2681 (r"b'\400'", &[0]),
2682 (r"b'\0001'", &[0]),
2683 (r"b'\0\0'", &[0]),
2684 (r"b'a\0b'", &[b'a', 0]),
2685 (r"b'a\0'", &[b'a', 0]),
2686 (r"b'\101'", &[b'A', 0]),
2687 ("b'bytes'", b"bytes\0"),
2688 ];
2689 for (input, expected) in cases {
2690 let (ty, value) = from_text(input).unwrap_or_else(|e| panic!("{input}: {e}"));
2691 assert_eq!(ty.signature(), "ay", "type of {input}");
2692 assert_eq!(
2693 value,
2694 Value::Bytes((*expected).to_vec()),
2695 "value of {input}"
2696 );
2697 }
2698 }
2699
2700 #[test]
2705 fn a_backslash_before_a_line_feed_continues_the_line() {
2706 assert_eq!(round("'a\\\nb'"), "'ab'");
2707 assert_eq!(round("'\\\n'"), "''");
2708 assert_eq!(round("'a\\\n'"), "'a'");
2709 assert_eq!(round("'a\\\n\\\nb'"), "'ab'");
2710 assert_eq!(round("'a\\\\\nb'"), "'a\\\\\\nb'");
2712 assert_eq!(round("'a\\\n\nb'"), "'a\\nb'");
2714 let (ty, value) = from_text("b'a\\\nb'").expect("the bytestring reads");
2715 assert_eq!(ty.signature(), "ay");
2716 assert_eq!(value, Value::Bytes(b"ab\0".to_vec()));
2717 }
2718
2719 #[test]
2725 fn refuses_the_level_past_the_nesting_cap() {
2726 for (open, close) in [("[", "]"), ("(", ",)"), ("<", ">")] {
2730 for depth in [125usize, 126, 127] {
2731 let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2732 assert!(
2733 from_text(&text).is_ok(),
2734 "depth {depth} of {open} was refused"
2735 );
2736 }
2737 for depth in [128usize, 129, 200] {
2738 let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2739 assert_eq!(
2740 refuse(&text),
2741 "128:variant nested too deeply",
2742 "depth {depth} of {open}"
2743 );
2744 }
2745 }
2746 assert!(from_text(&format!("{}5", "just ".repeat(127))).is_ok());
2748 assert!(from_text(&format!("{}5", "@i ".repeat(127))).is_ok());
2749 assert!(from_text(&format!("{}5", "uint32 ".repeat(127))).is_ok());
2750 for text in [
2751 format!("{}5", "just ".repeat(128)),
2752 format!("{}5", "@i ".repeat(128)),
2753 format!("{}5", "uint32 ".repeat(128)),
2754 ] {
2755 assert!(
2756 refuse(&text).ends_with("variant nested too deeply"),
2757 "{text}"
2758 );
2759 }
2760 }
2761
2762 #[test]
2768 fn a_signature_value_takes_129_levels() {
2769 let arrays = |count: usize| "a".repeat(count);
2770 for count in [0usize, 1, 65, 127, 128] {
2771 for text in [
2772 format!("signature '{}y'", arrays(count)),
2773 format!("@g '{}y'", arrays(count)),
2774 ] {
2775 assert!(from_text(&text).is_ok(), "{count} arrays was refused");
2776 }
2777 }
2778 assert_eq!(
2779 refuse(&format!("signature '{}y'", arrays(129))),
2780 "10-142:not a valid signature"
2781 );
2782 assert_eq!(
2783 refuse(&format!("@g '{}y'", arrays(129))),
2784 "3-135:not a valid signature"
2785 );
2786 let deep = format!(
2789 "{}signature '{}y'{}",
2790 "[".repeat(100),
2791 arrays(128),
2792 "]".repeat(100)
2793 );
2794 assert!(from_text(&deep).is_ok());
2795 }
2796
2797 #[test]
2807 fn a_declaration_takes_128_levels_from_where_it_stands() {
2808 let arrays = |count: usize| "a".repeat(count);
2809 for text in [
2810 format!("@{}y []", arrays(127)),
2811 format!("@{}() []", arrays(128)),
2812 format!("@{}(y) []", arrays(126)),
2813 format!("@{}(()) []", arrays(127)),
2814 format!("@{}{{sy}} []", arrays(126)),
2815 format!("@{}{{s()}} []", arrays(127)),
2816 format!("@{}(y()) []", arrays(126)),
2817 format!("@{}((y)y) []", arrays(125)),
2818 format!("[@{}y []]", arrays(126)),
2819 format!("[[@{}y []]]", arrays(125)),
2820 ] {
2821 assert!(from_text(&text).is_ok(), "{text} was refused");
2822 }
2823 let deep = "type declaration recurses too deeply";
2824 let invalid = "invalid type declaration";
2825 let indefinite = "type declarations must be definite";
2826 let cases: &[(String, String)] = &[
2827 (format!("@{}y []", arrays(128)), format!("0-130:{deep}")),
2828 (format!("@{}y []", arrays(129)), format!("0-131:{invalid}")),
2829 (format!("@{}(y) []", arrays(127)), format!("0-131:{deep}")),
2830 (format!("@{}() []", arrays(129)), format!("0-132:{invalid}")),
2831 (
2832 format!("@{}{{sy}} []", arrays(127)),
2833 format!("0-132:{deep}"),
2834 ),
2835 (
2836 format!("@{}(()) []", arrays(128)),
2837 format!("0-133:{invalid}"),
2838 ),
2839 (format!("@{}(y()) []", arrays(127)), format!("0-133:{deep}")),
2840 (
2841 format!("@{}((y)y) []", arrays(126)),
2842 format!("0-133:{deep}"),
2843 ),
2844 (format!("@{}r 5", arrays(66)), format!("0-68:{indefinite}")),
2846 (
2847 format!("@{}r 5", arrays(127)),
2848 format!("0-129:{indefinite}"),
2849 ),
2850 (format!("@{}r 5", arrays(128)), format!("0-130:{deep}")),
2851 (format!("@{}r 5", arrays(129)), format!("0-131:{invalid}")),
2852 (
2853 format!("@{}* 5", arrays(127)),
2854 format!("0-129:{indefinite}"),
2855 ),
2856 (format!("@{}* 5", arrays(128)), format!("0-130:{deep}")),
2857 (
2858 format!("@{}(r) 5", arrays(126)),
2859 format!("0-130:{indefinite}"),
2860 ),
2861 (format!("@{}(r) 5", arrays(127)), format!("0-131:{deep}")),
2862 (format!("[@{}y []]", arrays(127)), format!("1-130:{deep}")),
2864 (format!("[[@{}y []]]", arrays(126)), format!("2-130:{deep}")),
2865 ];
2866 for (text, expected) in cases {
2867 assert_eq!(refuse(text), *expected, "refusing {text}");
2868 }
2869 }
2870
2871 #[test]
2875 fn a_fault_in_the_value_stands_ahead_of_trailing_input() {
2876 let cases: &[(&str, &str)] = &[
2877 ("@i 'x' 5", "3-6:can not parse as value of type 'i'"),
2878 ("3000000000 5", "0-10:number out of range for type 'i'"),
2879 ("@d 5e-324 5", "3-9:number too big for any type"),
2880 ("objectpath 'bad' 5", "11-16:not a valid object path"),
2881 ("nothing 5", "0-7:unable to infer type"),
2882 ("(1) 5", "2:expected ',' after first tuple element"),
2883 ("42 43", "3:expected end of input"),
2885 ("nan(0x1)", "3:expected end of input"),
2886 ];
2887 for (input, expected) in cases {
2888 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2889 }
2890 }
2891
2892 #[test]
2898 fn deep_nesting_does_not_overflow_the_stack() {
2899 for text in [
2900 "[".repeat(50_000),
2901 format!("{}1{}", "[".repeat(50_000), "]".repeat(50_000)),
2902 format!("{}1{}", "(".repeat(50_000), ")".repeat(50_000)),
2903 format!("{}1{}", "<".repeat(50_000), ">".repeat(50_000)),
2904 format!("{}1", "just ".repeat(50_000)),
2905 format!("{}1{}", "{'a': ".repeat(20_000), "}".repeat(20_000)),
2906 format!("{}5", "@i ".repeat(50_000)),
2907 format!("@{}i 5", "a".repeat(50_000)),
2908 ] {
2909 assert!(from_text(&text).is_err(), "{:.20} was accepted", text);
2910 }
2911 }
2912
2913 #[test]
2918 fn the_printers_output_reads_back() {
2919 let cases = [
2920 "nan",
2921 "-nan",
2922 "inf",
2923 "-inf",
2924 "1.5",
2925 "-0.0",
2926 "0.10000000000000001",
2927 "1.7976931348623157e+308",
2928 "uint32 42",
2929 "byte 0x41",
2930 "@ms nothing",
2931 "b'bytes'",
2932 "{'x': 'y'}",
2933 "('a', 5)",
2934 "<'x'>",
2935 "objectpath '/a/b'",
2936 "signature 'ay'",
2937 "(1,)",
2938 "[byte 0x01, 0x02]",
2939 "@a{sv} {}",
2940 "[@ms 'a', nothing]",
2941 "{'a', 5}",
2942 "int64 -5",
2943 "handle 5",
2944 "'a\\ab'",
2948 "'a\\bb'",
2949 "'a\\fb'",
2950 "'a\\nb'",
2951 "'a\\rb'",
2952 "'a\\tb'",
2953 "'a\\vb'",
2954 "'a\\\\b'",
2955 "'a\\u001bb'",
2956 "'a\\u007fb'",
2957 "\"a'b\"",
2958 "'a\"b'",
2959 "\"a'\\\"b\"",
2960 "'héllo'",
2961 "b'a\\tb'",
2964 "b'a\\nb'",
2965 "b'a\\rb'",
2966 "b'a\\bb'",
2967 "b'a\\fb'",
2968 "b'a\\vb'",
2969 "b'a\\\\b'",
2970 "b'a\\\"b'",
2971 "b\"a'b\"",
2972 "b\"a'\\\"b\"",
2973 "b'\\377'",
2974 "b'h\\303\\251'",
2975 "@mmi 5",
2979 "@mmi just nothing",
2980 "@mmi nothing",
2981 "@mmmi just just nothing",
2982 "@mmmi just nothing",
2983 "@mmmmi just just just nothing",
2984 "@mms just nothing",
2985 "@mmv just nothing",
2986 "@mmv <5>",
2987 "@mmay just nothing",
2988 "@mm() just nothing",
2989 "@mammi [just nothing]",
2990 "[@mmi just nothing, nothing, 5]",
2991 "[@mmmi just just nothing, just nothing, nothing, 5]",
2992 "{'a': @mmi just nothing, 'b': nothing, 'c': 5}",
2993 "{'a', @mmi just nothing}",
2994 "(@mmi just nothing,)",
2995 "(@mmi just nothing, @mmi nothing, @mmi 5)",
2996 ];
2997 for text in cases {
2998 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
2999 let printed = to_text(&ty, &value).unwrap();
3000 assert_eq!(printed, text, "printing {text}");
3001 let (again_ty, again_value) =
3002 from_text(&printed).unwrap_or_else(|e| panic!("{printed}: {e}"));
3003 assert_eq!(again_ty, ty, "type of {text}");
3004 assert_eq!(again_value, value, "value of {text}");
3005 }
3006 let printed = to_text(&Type::Double, &Value::double(f64::from_bits(1))).unwrap();
3009 assert_eq!(printed, "4.9406564584124654e-324");
3010 assert_eq!(
3011 refuse(&printed),
3012 "0-23:number too big for any type",
3013 "the subnormal the printer writes"
3014 );
3015 }
3016
3017 #[test]
3024 fn every_maybe_chain_the_printer_writes_reads_back() {
3025 let leaves: &[(&str, Value)] = &[
3026 ("i", Value::I32(5)),
3027 ("s", Value::Str("x".into())),
3028 ("v", Value::variant(Type::I32, Value::I32(5))),
3029 ("ay", Value::Bytes(vec![0x01])),
3030 ("()", Value::Tuple(Vec::new())),
3031 ("ai", Value::Array(vec![Value::I32(1)])),
3032 (
3033 "(is)",
3034 Value::Tuple(vec![Value::I32(1), Value::Str("x".into())]),
3035 ),
3036 (
3037 "a{si}",
3038 Value::Array(vec![Value::Tuple(vec![
3039 Value::Str("k".into()),
3040 Value::I32(1),
3041 ])]),
3042 ),
3043 ];
3044 for (element, leaf) in leaves {
3045 for depth in 1..=4usize {
3046 let signature = format!("{}{element}", "m".repeat(depth));
3047 let ty = Type::parse(&signature).unwrap();
3048 for set in 0..=depth {
3049 let mut value = if set == depth {
3050 leaf.clone()
3051 } else {
3052 Value::Maybe(None)
3053 };
3054 for _ in 0..set {
3055 value = Value::Maybe(Some(Box::new(value)));
3056 }
3057 let printed = to_text(&ty, &value).unwrap();
3058 let (again_ty, again_value) = from_text(&printed)
3059 .unwrap_or_else(|e| panic!("{signature} set {set}: {printed}: {e}"));
3060 assert_eq!(again_ty, ty, "type of {printed}");
3061 assert_eq!(again_value, value, "value of {printed}");
3062 }
3063 }
3064 }
3065 }
3066
3067 #[test]
3071 fn serializes_in_host_byte_order() {
3072 let (ty, value) = from_text("uint32 42").unwrap();
3073 assert_eq!(ty.signature(), "u");
3074 assert_eq!(to_bytes(&ty, &value).unwrap(), 42u32.to_le_bytes());
3075 let (ty, value) = from_text("1.5").unwrap();
3076 assert_eq!(ty.signature(), "d");
3077 assert_eq!(to_bytes(&ty, &value).unwrap(), 1.5f64.to_le_bytes());
3078 }
3079}