1use std::fmt;
26
27use crate::{Type, Value};
28
29const MAX_NESTING: usize = 128;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Span {
37 pub start: usize,
39 pub end: usize,
42}
43
44impl Span {
45 fn new(start: usize, end: usize) -> Span {
46 Span { start, end }
47 }
48
49 fn point(at: usize) -> Span {
52 Span { start: at, end: at }
53 }
54}
55
56impl fmt::Display for Span {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 if self.start == self.end {
59 write!(f, "{}", self.start)
60 } else {
61 write!(f, "{}-{}", self.start, self.end)
62 }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct TextError {
71 pub spans: Vec<Span>,
76 pub reason: String,
78}
79
80impl TextError {
81 fn new(span: Span, reason: impl Into<String>) -> TextError {
82 TextError {
83 spans: vec![span],
84 reason: reason.into(),
85 }
86 }
87}
88
89impl fmt::Display for TextError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 for (index, span) in self.spans.iter().enumerate() {
92 if index > 0 {
93 f.write_str(",")?;
94 }
95 write!(f, "{span}")?;
96 }
97 write!(f, ":{}", self.reason)
98 }
99}
100
101impl std::error::Error for TextError {}
102
103type TextResult<T> = std::result::Result<T, TextError>;
104
105const CANNOT_INFER: &str = "unable to infer type";
108
109pub fn from_text(text: &str) -> TextResult<(Type, Value)> {
115 let mut parser = Parser::new(text);
116 let node = parser.value()?;
117 let ty = value_type(&node)?;
118 let value = build(&node, &ty)?;
119 parser.expect_end()?;
120 Ok((ty, value))
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
126enum Tok {
127 Open(char),
128 Close(char),
129 Comma,
130 Colon,
131 TypeDecl(String),
134 Word(String),
135 Number(String),
136 Str(String),
137 ByteString(Vec<u8>),
138 End,
139}
140
141#[derive(Debug, Clone)]
142struct Token {
143 tok: Tok,
144 span: Span,
145}
146
147struct Lexer<'a> {
148 text: &'a [u8],
149 pos: usize,
150}
151
152impl<'a> Lexer<'a> {
153 fn new(text: &'a str) -> Lexer<'a> {
154 Lexer {
155 text: text.as_bytes(),
156 pos: 0,
157 }
158 }
159
160 fn skip_space(&mut self) {
161 while matches!(self.text.get(self.pos), Some(b' ' | b'\t' | b'\n' | b'\r')) {
162 self.pos += 1;
163 }
164 }
165
166 fn next(&mut self) -> TextResult<Token> {
167 self.skip_space();
168 let start = self.pos;
169 let Some(&c) = self.text.get(start) else {
170 return Ok(Token {
171 tok: Tok::End,
172 span: Span::point(start),
173 });
174 };
175 let tok =
176 match c {
177 b'(' | b'[' | b'{' | b'<' => {
178 self.pos += 1;
179 Tok::Open(c as char)
180 }
181 b')' | b']' | b'}' | b'>' => {
182 self.pos += 1;
183 Tok::Close(c as char)
184 }
185 b',' => {
186 self.pos += 1;
187 Tok::Comma
188 }
189 b':' => {
190 self.pos += 1;
191 Tok::Colon
192 }
193 b'@' => {
194 self.pos += 1;
195 self.declaration();
196 Tok::TypeDecl(self.slice(start + 1, self.pos))
197 }
198 b'\'' | b'"' => return self.string(start, c, false),
199 b'b' if matches!(self.text.get(start + 1), Some(b'\'' | b'"')) => {
200 let quote = self.text[start + 1];
201 self.pos += 1;
202 return self.string(start, quote, true);
203 }
204 b'0'..=b'9' | b'-' | b'+' | b'.' => {
205 self.pos += 1;
206 while self.text.get(self.pos).is_some_and(|b| {
207 b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-')
208 }) {
209 self.pos += 1;
210 }
211 Tok::Number(self.slice(start, self.pos))
212 }
213 b'a'..=b'z' => {
214 while self
215 .text
216 .get(self.pos)
217 .is_some_and(u8::is_ascii_alphanumeric)
218 {
219 self.pos += 1;
220 }
221 Tok::Word(self.slice(start, self.pos))
222 }
223 _ => {
226 self.pos += 1;
227 Tok::Word(self.slice(start, self.pos))
228 }
229 };
230 Ok(Token {
231 tok,
232 span: Span::new(start, self.pos),
233 })
234 }
235
236 fn declaration(&mut self) {
241 let mut depth = 0usize;
242 while let Some(&c) = self.text.get(self.pos) {
243 match c {
244 b' ' | b'\t' | b'\n' | b'\r' | b',' | b':' | b'>' | b']' => break,
245 b')' | b'}' if depth == 0 => break,
246 b')' | b'}' => depth -= 1,
247 b'(' | b'{' => depth += 1,
248 _ => {}
249 }
250 self.pos += 1;
251 }
252 }
253
254 fn string(&mut self, start: usize, quote: u8, bytestring: bool) -> TextResult<Token> {
257 self.pos += 1; let mut raw = Vec::new();
259 loop {
260 let Some(&c) = self.text.get(self.pos) else {
261 self.pos = self.text.len();
262 return Err(TextError::new(
263 Span::new(start, self.pos),
264 "unterminated string constant",
265 ));
266 };
267 self.pos += 1;
268 if c == quote {
269 break;
270 }
271 if c != b'\\' {
272 if c == 0 && !bytestring {
276 return Err(TextError::new(
277 Span::new(self.pos - 1, self.pos),
278 "NUL byte in string constant",
279 ));
280 }
281 raw.push(c);
282 continue;
283 }
284 let Some(&escaped) = self.text.get(self.pos) else {
285 self.pos = self.text.len();
286 return Err(TextError::new(
287 Span::new(start, self.pos),
288 "unterminated string constant",
289 ));
290 };
291 self.pos += 1;
292 match escaped {
293 b'a' => raw.push(0x07),
294 b'b' => raw.push(0x08),
295 b'f' => raw.push(0x0c),
296 b'n' => raw.push(b'\n'),
297 b'r' => raw.push(b'\r'),
298 b't' => raw.push(b'\t'),
299 b'v' => raw.push(0x0b),
300 b'0'..=b'7' if bytestring => {
301 let mut value = u32::from(escaped - b'0');
303 for _ in 0..2 {
304 match self.text.get(self.pos) {
305 Some(&d @ b'0'..=b'7') => {
306 value = value * 8 + u32::from(d - b'0');
307 self.pos += 1;
308 }
309 _ => break,
310 }
311 }
312 raw.push(value as u8);
313 }
314 b'u' if !bytestring => self.unicode_escape(4, &mut raw)?,
315 b'U' if !bytestring => self.unicode_escape(8, &mut raw)?,
316 b'\n' => {}
320 other => raw.push(other),
322 }
323 }
324 let span = Span::new(start, self.pos);
325 if bytestring {
326 if let Some(nul) = raw.iter().position(|&b| b == 0) {
330 raw.truncate(nul);
331 }
332 raw.push(0);
333 return Ok(Token {
334 tok: Tok::ByteString(raw),
335 span,
336 });
337 }
338 match String::from_utf8(raw) {
339 Ok(text) => Ok(Token {
340 tok: Tok::Str(text),
341 span,
342 }),
343 Err(_) => Err(TextError::new(span, "invalid character in string constant")),
344 }
345 }
346
347 fn unicode_escape(&mut self, digits: usize, raw: &mut Vec<u8>) -> TextResult<()> {
351 let start = self.pos;
352 let mut count = 0;
353 while count < digits
354 && self
355 .text
356 .get(start + count)
357 .is_some_and(u8::is_ascii_hexdigit)
358 {
359 count += 1;
360 }
361 let bad = || {
362 TextError::new(
363 Span::new(start, start + count),
364 format!("invalid {digits}-character unicode escape"),
365 )
366 };
367 if count < digits {
368 return Err(bad());
369 }
370 let text = std::str::from_utf8(&self.text[start..start + digits]).map_err(|_| bad())?;
371 let code = u32::from_str_radix(text, 16).map_err(|_| bad())?;
372 let ch = char::from_u32(code)
378 .filter(|&c| c != '\0')
379 .ok_or_else(bad)?;
380 self.pos = start + digits;
381 let mut buf = [0u8; 4];
382 raw.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
383 Ok(())
384 }
385
386 fn slice(&self, start: usize, end: usize) -> String {
387 String::from_utf8_lossy(&self.text[start..end]).into_owned()
388 }
389}
390
391#[derive(Debug, Clone)]
394struct Node {
395 ast: Ast,
396 span: Span,
397}
398
399#[derive(Debug, Clone)]
400enum Ast {
401 Bool(bool),
402 Number(String),
405 Str(String),
406 ByteString(Vec<u8>),
407 Typed(Type, Box<Node>),
409 Maybe(Option<Box<Node>>),
411 Array(Vec<Node>),
412 Dict(Vec<(Node, Node)>),
414 Entry(Box<Node>, Box<Node>),
416 Tuple(Vec<Node>),
417 Variant(Box<Node>),
418}
419
420fn is_keyword_shaped(word: &str) -> bool {
424 let bytes = word.as_bytes();
425 bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1].is_ascii_alphabetic()
426}
427
428fn keyword_type(word: &str) -> Option<Type> {
430 Some(match word {
431 "boolean" => Type::Bool,
432 "byte" => Type::Byte,
433 "int16" => Type::I16,
434 "uint16" => Type::U16,
435 "int32" => Type::I32,
436 "handle" => Type::Handle,
437 "uint32" => Type::U32,
438 "int64" => Type::I64,
439 "uint64" => Type::U64,
440 "double" => Type::Double,
441 "string" => Type::Str,
442 "objectpath" => Type::ObjectPath,
443 "signature" => Type::Signature,
444 _ => return None,
445 })
446}
447
448struct Parser<'a> {
449 lexer: Lexer<'a>,
450 ahead: TextResult<Token>,
453 last_end: usize,
455 depth: usize,
458}
459
460impl<'a> Parser<'a> {
461 fn new(text: &'a str) -> Parser<'a> {
462 let mut lexer = Lexer::new(text);
463 let ahead = lexer.next();
464 Parser {
465 lexer,
466 ahead,
467 last_end: 0,
468 depth: 0,
469 }
470 }
471
472 fn peek(&self) -> Option<&Tok> {
473 self.ahead.as_ref().ok().map(|token| &token.tok)
474 }
475
476 fn ahead_start(&self) -> usize {
479 self.ahead
480 .as_ref()
481 .map_or(self.last_end, |token| token.span.start)
482 }
483
484 fn bump(&mut self) -> TextResult<Token> {
485 let next = self.lexer.next();
486 let token = std::mem::replace(&mut self.ahead, next)?;
487 self.last_end = token.span.end;
488 Ok(token)
489 }
490
491 fn expect_end(&mut self) -> TextResult<()> {
492 match &self.ahead {
493 Ok(token) if token.tok == Tok::End => Ok(()),
494 Ok(token) => Err(TextError::new(
495 Span::point(token.span.start),
496 "expected end of input",
497 )),
498 Err(error) => Err(error.clone()),
499 }
500 }
501
502 fn nested(&mut self) -> TextResult<Node> {
504 self.depth += 1;
505 let node = self.value();
506 self.depth -= 1;
507 node
508 }
509
510 fn value(&mut self) -> TextResult<Node> {
511 if self.depth >= MAX_NESTING {
512 return Err(TextError::new(
513 Span::point(self.ahead_start()),
514 "variant nested too deeply",
515 ));
516 }
517 let token = self.bump()?;
518 let start = token.span.start;
519 match token.tok {
520 Tok::Str(text) => Ok(Node {
521 ast: Ast::Str(text),
522 span: token.span,
523 }),
524 Tok::ByteString(bytes) => Ok(Node {
525 ast: Ast::ByteString(bytes),
526 span: token.span,
527 }),
528 Tok::Number(text) => Ok(Node {
529 ast: Ast::Number(text),
530 span: token.span,
531 }),
532 Tok::TypeDecl(signature) => {
533 let parsed = Type::parse(&signature).ok();
537 let levels = match &parsed {
538 Some(ty) => type_depth(ty),
539 None => match classify_declaration(&signature) {
540 Declaration::Indefinite(levels) => levels,
541 Declaration::Invalid => {
542 return Err(TextError::new(token.span, "invalid type declaration"));
543 }
544 },
545 };
546 if self.depth + levels > MAX_NESTING {
550 return Err(TextError::new(
551 token.span,
552 "type declaration recurses too deeply",
553 ));
554 }
555 let Some(ty) = parsed else {
556 return Err(TextError::new(
557 token.span,
558 "type declarations must be definite",
559 ));
560 };
561 let child = self.nested()?;
562 let end = child.span.end;
563 Ok(Node {
564 ast: Ast::Typed(ty, Box::new(child)),
565 span: Span::new(start, end),
566 })
567 }
568 Tok::Word(word) if is_keyword_shaped(&word) => self.word(&word, token.span),
571 Tok::Open('[') => self.array(start),
572 Tok::Open('{') => self.dict(start),
573 Tok::Open('(') => self.tuple(start),
574 Tok::Open('<') => {
575 let child = self.nested()?;
576 self.close('>', "expected '>' to follow variant value")?;
577 Ok(Node {
578 ast: Ast::Variant(Box::new(child)),
579 span: Span::new(start, self.last_end),
580 })
581 }
582 _ => Err(TextError::new(Span::point(start), "expected value")),
583 }
584 }
585
586 fn word(&mut self, word: &str, span: Span) -> TextResult<Node> {
587 match word {
588 "true" => Ok(Node {
589 ast: Ast::Bool(true),
590 span,
591 }),
592 "false" => Ok(Node {
593 ast: Ast::Bool(false),
594 span,
595 }),
596 "nan" | "inf" => Ok(Node {
599 ast: Ast::Number(word.to_owned()),
600 span,
601 }),
602 "nothing" => Ok(Node {
603 ast: Ast::Maybe(None),
604 span,
605 }),
606 "just" => {
607 let child = self.nested()?;
608 let end = child.span.end;
609 Ok(Node {
610 ast: Ast::Maybe(Some(Box::new(child))),
611 span: Span::new(span.start, end),
612 })
613 }
614 _ => match keyword_type(word) {
615 Some(ty) => {
616 let child = self.nested()?;
617 let end = child.span.end;
618 Ok(Node {
619 ast: Ast::Typed(ty, Box::new(child)),
620 span: Span::new(span.start, end),
621 })
622 }
623 None => Err(TextError::new(span, "unknown keyword")),
624 },
625 }
626 }
627
628 fn array(&mut self, start: usize) -> TextResult<Node> {
629 let mut items = Vec::new();
630 if matches!(self.peek(), Some(Tok::Close(']'))) {
631 self.bump()?;
632 return Ok(Node {
633 ast: Ast::Array(items),
634 span: Span::new(start, self.last_end),
635 });
636 }
637 loop {
638 items.push(self.nested()?);
639 match self.peek() {
640 Some(Tok::Comma) => {
641 self.bump()?;
642 }
643 Some(Tok::Close(']')) => {
644 self.bump()?;
645 break;
646 }
647 _ => {
648 return Err(TextError::new(
649 Span::point(self.ahead_start()),
650 "expected ',' or ']' to follow array element",
651 ));
652 }
653 }
654 }
655 Ok(Node {
656 ast: Ast::Array(items),
657 span: Span::new(start, self.last_end),
658 })
659 }
660
661 fn dict(&mut self, start: usize) -> TextResult<Node> {
662 if matches!(self.peek(), Some(Tok::Close('}'))) {
663 self.bump()?;
664 return Ok(Node {
665 ast: Ast::Dict(Vec::new()),
666 span: Span::new(start, self.last_end),
667 });
668 }
669 let first_key = self.nested()?;
670 if matches!(self.peek(), Some(Tok::Comma)) {
673 self.bump()?;
674 let value = self.nested()?;
675 self.close('}', "expected '}' at end of dictionary entry")?;
676 return Ok(Node {
677 ast: Ast::Entry(Box::new(first_key), Box::new(value)),
678 span: Span::new(start, self.last_end),
679 });
680 }
681 if !matches!(self.peek(), Some(Tok::Colon)) {
682 return Err(TextError::new(
683 Span::point(self.ahead_start()),
684 "expected ':' or ',' to follow dictionary entry key",
685 ));
686 }
687 self.bump()?;
688 let mut entries = vec![(first_key, self.nested()?)];
689 loop {
690 match self.peek() {
691 Some(Tok::Comma) => {
692 self.bump()?;
693 }
694 Some(Tok::Close('}')) => {
695 self.bump()?;
696 break;
697 }
698 _ => {
699 return Err(TextError::new(
700 Span::point(self.ahead_start()),
701 "expected ',' or '}' to follow dictionary entry",
702 ));
703 }
704 }
705 let key = self.nested()?;
706 if !matches!(self.peek(), Some(Tok::Colon)) {
707 return Err(TextError::new(
708 Span::point(self.ahead_start()),
709 "expected ':' to follow dictionary entry key",
710 ));
711 }
712 self.bump()?;
713 entries.push((key, self.nested()?));
714 }
715 Ok(Node {
716 ast: Ast::Dict(entries),
717 span: Span::new(start, self.last_end),
718 })
719 }
720
721 fn tuple(&mut self, start: usize) -> TextResult<Node> {
722 let mut items = Vec::new();
723 if matches!(self.peek(), Some(Tok::Close(')'))) {
724 self.bump()?;
725 return Ok(Node {
726 ast: Ast::Tuple(items),
727 span: Span::new(start, self.last_end),
728 });
729 }
730 items.push(self.nested()?);
733 if !matches!(self.peek(), Some(Tok::Comma)) {
734 return Err(TextError::new(
735 Span::point(self.ahead_start()),
736 "expected ',' after first tuple element",
737 ));
738 }
739 self.bump()?;
740 if matches!(self.peek(), Some(Tok::Close(')'))) {
741 self.bump()?;
742 return Ok(Node {
743 ast: Ast::Tuple(items),
744 span: Span::new(start, self.last_end),
745 });
746 }
747 loop {
748 items.push(self.nested()?);
749 match self.peek() {
750 Some(Tok::Comma) => {
751 self.bump()?;
752 }
753 Some(Tok::Close(')')) => {
754 self.bump()?;
755 break;
756 }
757 _ => {
758 return Err(TextError::new(
759 Span::point(self.ahead_start()),
760 "expected ',' or ')' to follow tuple element",
761 ));
762 }
763 }
764 }
765 Ok(Node {
766 ast: Ast::Tuple(items),
767 span: Span::new(start, self.last_end),
768 })
769 }
770
771 fn close(&mut self, bracket: char, reason: &str) -> TextResult<()> {
772 if matches!(self.peek(), Some(Tok::Close(c)) if *c == bracket) {
773 self.bump()?;
774 return Ok(());
775 }
776 Err(TextError::new(Span::point(self.ahead_start()), reason))
777 }
778}
779
780enum Declaration {
784 Indefinite(usize),
787 Invalid,
789}
790
791const MAX_DECLARATION_DEPTH: usize = crate::de::MAX_VALUE_DEPTH;
795
796fn type_depth(ty: &Type) -> usize {
806 match ty {
807 Type::Maybe(elem) | Type::Array(elem) => 1 + type_depth(elem),
808 Type::Tuple(members) => members
809 .iter()
810 .map(|member| 1 + type_depth(member))
811 .max()
812 .unwrap_or(0),
813 Type::DictEntry(_, value) => 1 + type_depth(value),
814 _ => 1,
815 }
816}
817
818fn classify_declaration(signature: &str) -> Declaration {
821 let bytes = signature.as_bytes();
822 let mut pos = 0;
823 let mut indefinite = false;
824 match scan_declared_type(bytes, &mut pos, 0, &mut indefinite) {
825 Some(levels) if pos == bytes.len() && indefinite => Declaration::Indefinite(levels),
826 _ => Declaration::Invalid,
827 }
828}
829
830fn scan_declared_type(
835 sig: &[u8],
836 pos: &mut usize,
837 depth: usize,
838 indefinite: &mut bool,
839) -> Option<usize> {
840 if depth > MAX_DECLARATION_DEPTH {
841 return None;
842 }
843 let &c = sig.get(*pos)?;
844 *pos += 1;
845 match c {
846 b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
847 | b'g' | b'v' => Some(1),
848 b'r' | b'*' | b'?' => {
849 *indefinite = true;
850 Some(1)
851 }
852 b'm' | b'a' => Some(1 + scan_declared_type(sig, pos, depth + 1, indefinite)?),
853 b'(' => {
854 let mut levels = 0;
855 while sig.get(*pos) != Some(&b')') {
856 let member = scan_declared_type(sig, pos, depth + 1, indefinite)?;
857 levels = levels.max(1 + member);
858 }
859 *pos += 1;
860 Some(levels)
861 }
862 b'{' => {
863 scan_declared_type(sig, pos, depth + 1, indefinite)?;
864 let value = scan_declared_type(sig, pos, depth + 1, indefinite)?;
865 if sig.get(*pos) != Some(&b'}') {
866 return None;
867 }
868 *pos += 1;
869 Some(1 + value)
870 }
871 _ => None,
872 }
873}
874
875#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879enum NumberKind {
880 Integer,
881 Double,
882}
883
884fn split_sign(text: &str) -> (bool, &str) {
888 match text.strip_prefix('-') {
889 Some(rest) => (true, rest),
890 None => (false, text),
891 }
892}
893
894fn is_special_double(body: &str) -> bool {
897 matches!(body, "inf" | "infinity" | "nan")
898 || matches!(body.strip_prefix('+'), Some("inf" | "infinity" | "nan"))
899}
900
901fn number_kind(text: &str) -> NumberKind {
906 let (_, body) = split_sign(text);
907 if is_special_double(body) {
908 return NumberKind::Double;
909 }
910 let digits = body.strip_prefix('+').unwrap_or(body);
911 let hex = digits.starts_with("0x") || digits.starts_with("0X");
912 let fractional = if hex {
913 digits.contains('.')
914 } else {
915 digits.contains(['.', 'e'])
916 };
917 if fractional {
918 NumberKind::Double
919 } else {
920 NumberKind::Integer
921 }
922}
923
924struct IntegerScan {
927 value: u64,
928 end: usize,
929 overflow: bool,
930}
931
932fn scan_integer(body: &str) -> IntegerScan {
936 let bytes = body.as_bytes();
937 let mut pos = 0;
938 let mut negate = false;
939 match bytes.first() {
940 Some(b'+') => pos = 1,
941 Some(b'-') => {
942 negate = true;
943 pos = 1;
944 }
945 _ => {}
946 }
947 let (radix, start) = if bytes.get(pos) == Some(&b'0')
948 && matches!(bytes.get(pos + 1), Some(b'x' | b'X'))
949 && bytes.get(pos + 2).is_some_and(u8::is_ascii_hexdigit)
950 {
951 (16u32, pos + 2)
952 } else if bytes.get(pos) == Some(&b'0')
953 && matches!(bytes.get(pos + 1), Some(b'b' | b'B'))
954 && matches!(bytes.get(pos + 2), Some(b'0' | b'1'))
955 {
956 (2, pos + 2)
957 } else if bytes.get(pos) == Some(&b'0') {
958 (8, pos)
959 } else {
960 (10, pos)
961 };
962 let mut end = start;
963 let mut value: u64 = 0;
964 let mut overflow = false;
965 while let Some(digit) = bytes.get(end).and_then(|c| char::from(*c).to_digit(radix)) {
966 match value
967 .checked_mul(u64::from(radix))
968 .and_then(|v| v.checked_add(u64::from(digit)))
969 {
970 Some(next) => value = next,
971 None => overflow = true,
972 }
973 end += 1;
974 }
975 if end == start {
976 return IntegerScan {
977 value: 0,
978 end: 0,
979 overflow: false,
980 };
981 }
982 if negate {
983 value = value.wrapping_neg();
984 }
985 IntegerScan {
986 value,
987 end,
988 overflow,
989 }
990}
991
992fn integer_literal(text: &str, span: Span) -> TextResult<(bool, u64)> {
994 let (negative, body) = split_sign(text);
995 let offset = text.len() - body.len();
996 let scan = scan_integer(body);
997 if scan.end != body.len() {
998 let at = span.start + offset + scan.end;
999 return Err(TextError::new(
1000 Span::new(at, at + 1),
1001 "invalid character in number",
1002 ));
1003 }
1004 if scan.overflow {
1005 return Err(TextError::new(span, "integer too big for any type"));
1006 }
1007 Ok((negative, scan.value))
1008}
1009
1010struct DoubleScan {
1012 value: f64,
1014 end: usize,
1016 exact: bool,
1019}
1020
1021fn scan_double(text: &str) -> DoubleScan {
1023 let bytes = text.as_bytes();
1024 let mut pos = 0;
1025 let mut negative = false;
1026 match bytes.first() {
1027 Some(b'-') => {
1028 negative = true;
1029 pos = 1;
1030 }
1031 Some(b'+') => pos = 1,
1032 _ => {}
1033 }
1034 let signed = |value: f64| if negative { -value } else { value };
1035 let rest = &text[pos..];
1036 for (word, value) in [
1037 ("infinity", f64::INFINITY),
1038 ("inf", f64::INFINITY),
1039 ("nan", f64::NAN),
1040 ] {
1041 if rest.len() >= word.len() && rest[..word.len()].eq_ignore_ascii_case(word) {
1042 return DoubleScan {
1043 value: signed(value),
1044 end: pos + word.len(),
1045 exact: true,
1046 };
1047 }
1048 }
1049 if bytes.get(pos) == Some(&b'0') && matches!(bytes.get(pos + 1), Some(b'x' | b'X')) {
1050 return match scan_hex_double(bytes, pos + 2) {
1051 Some(scan) => DoubleScan {
1052 value: signed(scan.value),
1053 ..scan
1054 },
1055 None => nothing_read(),
1056 };
1057 }
1058 let mut end = pos;
1059 let mut integer = String::new();
1060 while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_digit()) {
1061 integer.push(char::from(c));
1062 end += 1;
1063 }
1064 let mut fraction = String::new();
1065 if bytes.get(end) == Some(&b'.') {
1066 let mut after = end + 1;
1067 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1068 fraction.push(char::from(c));
1069 after += 1;
1070 }
1071 end = after;
1072 }
1073 if integer.is_empty() && fraction.is_empty() {
1074 return nothing_read();
1075 }
1076 let mut exponent = String::new();
1077 if matches!(bytes.get(end), Some(b'e' | b'E')) {
1078 let mut after = end + 1;
1079 if matches!(bytes.get(after), Some(b'+' | b'-')) {
1080 exponent.push(char::from(bytes[after]));
1081 after += 1;
1082 }
1083 let digits = after;
1084 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1085 exponent.push(char::from(c));
1086 after += 1;
1087 }
1088 if after > digits {
1089 end = after;
1090 } else {
1091 exponent.clear();
1092 }
1093 }
1094 if integer.is_empty() {
1095 integer.push('0');
1096 }
1097 if fraction.is_empty() {
1098 fraction.push('0');
1099 }
1100 if exponent.is_empty() {
1101 exponent.push('0');
1102 }
1103 let value: f64 = format!("{integer}.{fraction}e{exponent}")
1104 .parse()
1105 .unwrap_or(f64::INFINITY);
1106 DoubleScan {
1107 value: signed(value),
1108 end,
1109 exact: false,
1110 }
1111}
1112
1113fn nothing_read() -> DoubleScan {
1115 DoubleScan {
1116 value: 0.0,
1117 end: 0,
1118 exact: false,
1119 }
1120}
1121
1122const HEX_MANTISSA_CAP: u128 = (u128::MAX - 15) / 16;
1126
1127fn scan_hex_double(bytes: &[u8], start: usize) -> Option<DoubleScan> {
1131 let mut end = start;
1132 let mut mantissa: u128 = 0;
1133 let mut sticky = false;
1134 let mut digits = 0usize;
1135 let mut shift: i32 = 0;
1136 while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_hexdigit()) {
1137 let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1138 if mantissa <= HEX_MANTISSA_CAP {
1139 mantissa = mantissa * 16 + value;
1140 } else {
1141 shift = shift.saturating_add(4);
1142 sticky |= value != 0;
1143 }
1144 digits += 1;
1145 end += 1;
1146 }
1147 if bytes.get(end) == Some(&b'.') {
1148 let mut after = end + 1;
1149 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_hexdigit()) {
1150 let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1151 if mantissa <= HEX_MANTISSA_CAP {
1152 mantissa = mantissa * 16 + value;
1153 shift = shift.saturating_sub(4);
1154 } else {
1155 sticky |= value != 0;
1156 }
1157 digits += 1;
1158 after += 1;
1159 }
1160 end = after;
1161 }
1162 if digits == 0 {
1163 return None;
1164 }
1165 if matches!(bytes.get(end), Some(b'p' | b'P')) {
1166 let mut after = end + 1;
1167 let mut negative = false;
1168 match bytes.get(after) {
1169 Some(b'-') => {
1170 negative = true;
1171 after += 1;
1172 }
1173 Some(b'+') => after += 1,
1174 _ => {}
1175 }
1176 let first = after;
1177 let mut exponent: i32 = 0;
1178 while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1179 exponent = exponent
1180 .saturating_mul(10)
1181 .saturating_add(i32::from(c - b'0'));
1182 after += 1;
1183 }
1184 if after > first {
1185 shift = if negative {
1186 shift.saturating_sub(exponent)
1187 } else {
1188 shift.saturating_add(exponent)
1189 };
1190 end = after;
1191 }
1192 }
1193 let (value, exact) = round_binary(mantissa, sticky, shift);
1194 Some(DoubleScan { value, end, exact })
1195}
1196
1197fn round_binary(mantissa: u128, sticky: bool, shift: i32) -> (f64, bool) {
1202 if mantissa == 0 {
1203 return (0.0, true);
1204 }
1205 let width = i64::from(128 - mantissa.leading_zeros());
1206 let top = i64::from(shift) + width - 1;
1209 let lowest = (top - 52).max(-1074);
1210 let drop = lowest - i64::from(shift);
1211 let (mut significand, inexact) = if drop <= 0 {
1212 (mantissa << (-drop) as u32, sticky)
1214 } else if drop > 128 {
1215 (0u128, true)
1217 } else {
1218 let dropped = drop as u32;
1219 let (kept, rest) = if dropped == 128 {
1220 (0, mantissa)
1221 } else {
1222 (mantissa >> dropped, mantissa & ((1u128 << dropped) - 1))
1223 };
1224 let half = 1u128 << (dropped - 1);
1225 let up = rest > half || (rest == half && (sticky || kept & 1 == 1));
1226 (kept + u128::from(up), rest != 0 || sticky)
1227 };
1228 if significand == 0 {
1229 return (0.0, !inexact);
1230 }
1231 let mut lowest = lowest;
1232 if significand == 1u128 << 53 {
1233 significand >>= 1;
1235 lowest += 1;
1236 }
1237 let bits = if significand < 1u128 << 52 {
1238 significand as u64
1240 } else {
1241 let biased = lowest + 1075;
1242 if biased >= 2047 {
1243 return (f64::INFINITY, false);
1244 }
1245 ((biased as u64) << 52) | ((significand - (1u128 << 52)) as u64)
1246 };
1247 (f64::from_bits(bits), !inexact)
1248}
1249
1250fn double_literal(text: &str, span: Span) -> TextResult<f64> {
1256 let scan = scan_double(text);
1257 if scan.end != text.len() {
1258 let at = span.start + scan.end;
1259 return Err(TextError::new(
1260 Span::new(at, at + 1),
1261 "invalid character in number",
1262 ));
1263 }
1264 let value = scan.value;
1265 let subnormal = value != 0.0 && value.abs() < f64::MIN_POSITIVE;
1266 let (_, body) = split_sign(text);
1267 if !is_special_double(body) && (!value.is_finite() || (subnormal && !scan.exact)) {
1268 return Err(TextError::new(span, "number too big for any type"));
1269 }
1270 Ok(value)
1271}
1272
1273#[derive(Debug, Clone)]
1279enum Guess {
1280 Any(Span),
1281 Int,
1282 Decimal,
1283 StringLit,
1286 Basic(Type),
1287 Variant,
1288 Maybe(Box<Guess>),
1289 Array(Box<Guess>),
1290 Tuple(Vec<Guess>),
1291 Entry(Box<Guess>, Box<Guess>),
1292}
1293
1294impl Guess {
1295 fn of(ty: &Type) -> Guess {
1297 match ty {
1298 Type::Variant => Guess::Variant,
1299 Type::Maybe(elem) => Guess::Maybe(Box::new(Guess::of(elem))),
1300 Type::Array(elem) => Guess::Array(Box::new(Guess::of(elem))),
1301 Type::Tuple(members) => Guess::Tuple(members.iter().map(Guess::of).collect()),
1302 Type::DictEntry(key, value) => {
1303 Guess::Entry(Box::new(Guess::of(key)), Box::new(Guess::of(value)))
1304 }
1305 basic => Guess::Basic(basic.clone()),
1306 }
1307 }
1308}
1309
1310fn is_numeric(ty: &Type) -> bool {
1312 matches!(
1313 ty,
1314 Type::Byte
1315 | Type::I16
1316 | Type::U16
1317 | Type::I32
1318 | Type::U32
1319 | Type::I64
1320 | Type::U64
1321 | Type::Handle
1322 | Type::Double
1323 )
1324}
1325
1326fn unify(left: &Guess, right: &Guess) -> Option<Guess> {
1329 match (left, right) {
1330 (Guess::Any(_), other) | (other, Guess::Any(_)) => Some(other.clone()),
1331 (Guess::Int, Guess::Int) => Some(Guess::Int),
1332 (Guess::Int, Guess::Decimal) | (Guess::Decimal, Guess::Int) => Some(Guess::Decimal),
1333 (Guess::Decimal, Guess::Decimal) => Some(Guess::Decimal),
1334 (Guess::StringLit, Guess::StringLit) => Some(Guess::StringLit),
1335 (Guess::StringLit, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::StringLit)
1336 if matches!(ty, Type::Str | Type::ObjectPath | Type::Signature) =>
1337 {
1338 Some(Guess::Basic(ty.clone()))
1339 }
1340 (Guess::Int, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::Int) if is_numeric(ty) => {
1341 Some(Guess::Basic(ty.clone()))
1342 }
1343 (Guess::Decimal, Guess::Basic(Type::Double))
1344 | (Guess::Basic(Type::Double), Guess::Decimal) => Some(Guess::Basic(Type::Double)),
1345 (Guess::Basic(a), Guess::Basic(b)) if a == b => Some(Guess::Basic(a.clone())),
1346 (Guess::Variant, Guess::Variant) => Some(Guess::Variant),
1347 (Guess::Maybe(a), Guess::Maybe(b)) => Some(Guess::Maybe(Box::new(unify(a, b)?))),
1348 (Guess::Maybe(a), other) | (other, Guess::Maybe(a)) => {
1349 Some(Guess::Maybe(Box::new(unify(a, other)?)))
1350 }
1351 (Guess::Array(a), Guess::Array(b)) => Some(Guess::Array(Box::new(unify(a, b)?))),
1352 (Guess::Tuple(a), Guess::Tuple(b)) if a.len() == b.len() => {
1353 let mut members = Vec::with_capacity(a.len());
1354 for (x, y) in a.iter().zip(b) {
1355 members.push(unify(x, y)?);
1356 }
1357 Some(Guess::Tuple(members))
1358 }
1359 (Guess::Entry(ka, va), Guess::Entry(kb, vb)) => Some(Guess::Entry(
1360 Box::new(unify(ka, kb)?),
1361 Box::new(unify(va, vb)?),
1362 )),
1363 _ => None,
1364 }
1365}
1366
1367fn resolve(guess: &Guess) -> TextResult<Type> {
1370 Ok(match guess {
1371 Guess::Any(span) => return Err(TextError::new(*span, CANNOT_INFER)),
1372 Guess::Int => Type::I32,
1373 Guess::Decimal => Type::Double,
1374 Guess::StringLit => Type::Str,
1375 Guess::Basic(ty) => ty.clone(),
1376 Guess::Variant => Type::Variant,
1377 Guess::Maybe(elem) => Type::Maybe(Box::new(resolve(elem)?)),
1378 Guess::Array(elem) => Type::Array(Box::new(resolve(elem)?)),
1379 Guess::Tuple(members) => {
1380 Type::Tuple(members.iter().map(resolve).collect::<TextResult<_>>()?)
1381 }
1382 Guess::Entry(key, value) => {
1383 Type::DictEntry(Box::new(resolve(key)?), Box::new(resolve(value)?))
1384 }
1385 })
1386}
1387
1388fn value_type(node: &Node) -> TextResult<Type> {
1392 let guess = infer(node)?;
1393 resolve(&guess).map_err(|error| {
1394 if error.reason == CANNOT_INFER {
1395 TextError::new(node.span, CANNOT_INFER)
1396 } else {
1397 error
1398 }
1399 })
1400}
1401
1402fn cannot_parse(span: Span, ty: &Type) -> TextError {
1403 TextError::new(
1404 span,
1405 format!("can not parse as value of type '{}'", ty.signature()),
1406 )
1407}
1408
1409fn no_common_type(first: Span, other: Span) -> TextError {
1412 TextError {
1413 spans: vec![first, other],
1414 reason: "unable to find a common type".to_owned(),
1415 }
1416}
1417
1418fn infer(node: &Node) -> TextResult<Guess> {
1419 Ok(match &node.ast {
1420 Ast::Bool(_) => Guess::Basic(Type::Bool),
1421 Ast::Number(text) => match number_kind(text) {
1422 NumberKind::Integer => Guess::Int,
1423 NumberKind::Double => Guess::Decimal,
1424 },
1425 Ast::Str(_) => Guess::StringLit,
1426 Ast::ByteString(_) => Guess::Array(Box::new(Guess::Basic(Type::Byte))),
1427 Ast::Typed(ty, _) => Guess::of(ty),
1431 Ast::Maybe(None) => Guess::Maybe(Box::new(Guess::Any(node.span))),
1432 Ast::Maybe(Some(child)) => Guess::Maybe(Box::new(infer(child)?)),
1433 Ast::Array(items) => {
1434 let Some((first, rest)) = items.split_first() else {
1435 return Ok(Guess::Array(Box::new(Guess::Any(node.span))));
1436 };
1437 let mut common = infer(first)?;
1438 for item in rest {
1439 let found = infer(item)?;
1440 common =
1441 unify(&common, &found).ok_or_else(|| no_common_type(first.span, item.span))?;
1442 }
1443 Guess::Array(Box::new(common))
1444 }
1445 Ast::Dict(entries) => {
1446 let Some(((first_key, first_value), rest)) = entries.split_first() else {
1447 return Ok(Guess::Array(Box::new(Guess::Entry(
1448 Box::new(Guess::Any(node.span)),
1449 Box::new(Guess::Any(node.span)),
1450 ))));
1451 };
1452 let mut key = infer(first_key)?;
1453 let value = infer(first_value)?;
1458 for (k, _) in rest {
1459 let found = infer(k)?;
1460 key = unify(&key, &found).ok_or_else(|| no_common_type(first_key.span, k.span))?;
1461 }
1462 check_basic_key(&key, node.span)?;
1463 Guess::Array(Box::new(Guess::Entry(Box::new(key), Box::new(value))))
1464 }
1465 Ast::Entry(key, value) => {
1466 let key = infer(key)?;
1467 check_basic_key(&key, node.span)?;
1468 Guess::Entry(Box::new(key), Box::new(infer(value)?))
1469 }
1470 Ast::Tuple(items) => Guess::Tuple(items.iter().map(infer).collect::<TextResult<_>>()?),
1471 Ast::Variant(child) => {
1472 value_type(child)?;
1474 Guess::Variant
1475 }
1476 })
1477}
1478
1479fn guess_is_basic(guess: &Guess) -> bool {
1483 match guess {
1484 Guess::Int | Guess::Decimal | Guess::StringLit => true,
1485 Guess::Basic(ty) => ty.is_basic(),
1486 _ => false,
1487 }
1488}
1489
1490fn check_basic_key(key: &Guess, span: Span) -> TextResult<()> {
1493 if guess_is_basic(key) {
1494 return Ok(());
1495 }
1496 Err(TextError::new(
1497 span,
1498 "dictionary keys must have basic types",
1499 ))
1500}
1501
1502fn is_object_path(text: &str) -> bool {
1507 if text == "/" {
1508 return true;
1509 }
1510 let Some(rest) = text.strip_prefix('/') else {
1511 return false;
1512 };
1513 !rest.is_empty()
1514 && rest.split('/').all(|element| {
1515 !element.is_empty()
1516 && element
1517 .bytes()
1518 .all(|c| c.is_ascii_alphanumeric() || c == b'_')
1519 })
1520}
1521
1522fn is_signature(text: &str) -> bool {
1525 let bytes = text.as_bytes();
1526 let mut pos = 0;
1527 while pos < bytes.len() {
1528 if !scan_signature_type(bytes, &mut pos, 0) {
1529 return false;
1530 }
1531 }
1532 true
1533}
1534
1535fn scan_signature_type(sig: &[u8], pos: &mut usize, depth: usize) -> bool {
1536 if depth > MAX_DECLARATION_DEPTH {
1537 return false;
1538 }
1539 let Some(&c) = sig.get(*pos) else {
1540 return false;
1541 };
1542 *pos += 1;
1543 match c {
1544 b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
1545 | b'g' | b'v' => true,
1546 b'a' => scan_signature_type(sig, pos, depth + 1),
1547 b'(' => {
1548 while sig.get(*pos) != Some(&b')') {
1549 if !scan_signature_type(sig, pos, depth + 1) {
1550 return false;
1551 }
1552 }
1553 *pos += 1;
1554 true
1555 }
1556 b'{' => {
1557 let key = sig.get(*pos).copied();
1558 if !key.is_some_and(|k| {
1559 matches!(
1560 k,
1561 b'b' | b'y'
1562 | b'n'
1563 | b'q'
1564 | b'i'
1565 | b'u'
1566 | b'x'
1567 | b't'
1568 | b'h'
1569 | b'd'
1570 | b's'
1571 | b'o'
1572 | b'g'
1573 )
1574 }) {
1575 return false;
1576 }
1577 *pos += 1;
1578 if !scan_signature_type(sig, pos, depth + 1) {
1579 return false;
1580 }
1581 if sig.get(*pos) != Some(&b'}') {
1582 return false;
1583 }
1584 *pos += 1;
1585 true
1586 }
1587 _ => false,
1588 }
1589}
1590
1591fn build(node: &Node, ty: &Type) -> TextResult<Value> {
1592 if let Type::Maybe(elem) = ty
1595 && !matches!(node.ast, Ast::Maybe(_) | Ast::Typed(..))
1596 {
1597 return Ok(Value::Maybe(Some(Box::new(build(node, elem)?))));
1598 }
1599 match (&node.ast, ty) {
1600 (Ast::Typed(_, child), _) => build(child, ty),
1601 (Ast::Bool(b), Type::Bool) => Ok(Value::Bool(*b)),
1602 (Ast::Number(text), _) => number_value(text, ty, node.span),
1603 (Ast::Str(text), Type::Str) => Ok(Value::Str(text.clone())),
1604 (Ast::Str(text), Type::ObjectPath) => {
1605 if !is_object_path(text) {
1606 return Err(TextError::new(node.span, "not a valid object path"));
1607 }
1608 Ok(Value::Str(text.clone()))
1609 }
1610 (Ast::Str(text), Type::Signature) => {
1611 if !is_signature(text) {
1612 return Err(TextError::new(node.span, "not a valid signature"));
1613 }
1614 Ok(Value::Str(text.clone()))
1615 }
1616 (Ast::ByteString(bytes), Type::Array(elem)) if **elem == Type::Byte => {
1617 Ok(Value::Bytes(bytes.clone()))
1618 }
1619 (Ast::Maybe(None), Type::Maybe(_)) => Ok(Value::Maybe(None)),
1620 (Ast::Maybe(Some(child)), Type::Maybe(elem)) => {
1621 Ok(Value::Maybe(Some(Box::new(build(child, elem)?))))
1622 }
1623 (Ast::Array(items), Type::Array(elem)) if **elem == Type::Byte => {
1624 let mut bytes = Vec::with_capacity(items.len());
1625 for item in items {
1626 match build(item, elem)? {
1627 Value::Byte(b) => bytes.push(b),
1628 _ => return Err(cannot_parse(item.span, elem)),
1629 }
1630 }
1631 Ok(Value::Bytes(bytes))
1632 }
1633 (Ast::Array(items), Type::Array(elem)) => Ok(Value::Array(
1634 items
1635 .iter()
1636 .map(|item| build(item, elem))
1637 .collect::<TextResult<_>>()?,
1638 )),
1639 (Ast::Dict(entries), Type::Array(elem)) => {
1640 let Type::DictEntry(key_ty, value_ty) = &**elem else {
1641 return Err(cannot_parse(node.span, ty));
1642 };
1643 let mut items = Vec::with_capacity(entries.len());
1644 for (key, value) in entries {
1645 items.push(Value::Tuple(vec![
1646 build(key, key_ty)?,
1647 build(value, value_ty)?,
1648 ]));
1649 }
1650 Ok(Value::Array(items))
1651 }
1652 (Ast::Entry(key, value), Type::DictEntry(key_ty, value_ty)) => Ok(Value::Tuple(vec![
1653 build(key, key_ty)?,
1654 build(value, value_ty)?,
1655 ])),
1656 (Ast::Tuple(items), Type::Tuple(members)) if items.len() == members.len() => {
1657 Ok(Value::Tuple(
1658 items
1659 .iter()
1660 .zip(members)
1661 .map(|(item, member)| build(item, member))
1662 .collect::<TextResult<_>>()?,
1663 ))
1664 }
1665 (Ast::Variant(child), Type::Variant) => {
1666 let child_ty = value_type(child)?;
1667 let value = build(child, &child_ty)?;
1668 Ok(Value::variant(child_ty, value))
1669 }
1670 _ => Err(cannot_parse(node.span, ty)),
1671 }
1672}
1673
1674fn number_value(text: &str, ty: &Type, span: Span) -> TextResult<Value> {
1678 if matches!(ty, Type::Double) {
1679 return Ok(Value::double(double_literal(text, span)?));
1680 }
1681 if !is_numeric(ty) {
1682 return Err(cannot_parse(span, ty));
1683 }
1684 let (negative, magnitude) = integer_literal(text, span)?;
1685 let value = if negative {
1686 -i128::from(magnitude)
1687 } else {
1688 i128::from(magnitude)
1689 };
1690 let range = || {
1691 TextError::new(
1692 span,
1693 format!("number out of range for type '{}'", ty.signature()),
1694 )
1695 };
1696 Ok(match ty {
1697 Type::Byte => Value::Byte(u8::try_from(value).map_err(|_| range())?),
1698 Type::I16 => Value::I16(i16::try_from(value).map_err(|_| range())?),
1699 Type::U16 => Value::U16(u16::try_from(value).map_err(|_| range())?),
1700 Type::I32 | Type::Handle => Value::I32(i32::try_from(value).map_err(|_| range())?),
1701 Type::U32 => Value::U32(u32::try_from(value).map_err(|_| range())?),
1702 Type::I64 => Value::I64(i64::try_from(value).map_err(|_| range())?),
1703 Type::U64 => Value::U64(u64::try_from(value).map_err(|_| range())?),
1704 _ => return Err(cannot_parse(span, ty)),
1705 })
1706}
1707
1708#[cfg(test)]
1709mod tests {
1710 use super::*;
1711 use crate::{to_bytes, to_text};
1712
1713 fn round(text: &str) -> String {
1717 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1718 to_bytes(&ty, &value).unwrap_or_else(|e| panic!("{text}: {e:?}"));
1720 to_text(&ty, &value).unwrap()
1721 }
1722
1723 fn refuse(text: &str) -> String {
1724 from_text(text)
1725 .map(|(ty, _)| ty.signature())
1726 .expect_err(&format!("{text} was accepted"))
1727 .to_string()
1728 }
1729
1730 fn double(text: &str) -> f64 {
1732 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1733 assert_eq!(ty.signature(), "d", "type of {text}");
1734 match value {
1735 Value::Double(bits) => f64::from_bits(bits),
1736 other => panic!("{text}: {other:?}"),
1737 }
1738 }
1739
1740 #[test]
1743 fn reads_the_forms_the_tool_accepts() {
1744 let cases: &[(&str, &str)] = &[
1745 ("'a string'", "'a string'"),
1746 ("\"double quoted\"", "'double quoted'"),
1747 ("uint32 42", "uint32 42"),
1748 ("42", "42"),
1749 ("-42", "-42"),
1750 ("+42", "42"),
1751 ("int64 -5", "int64 -5"),
1752 ("@x 5", "int64 5"),
1753 ("uint64 99", "uint64 99"),
1754 ("byte 0x41", "byte 0x41"),
1755 ("true", "true"),
1756 ("false", "false"),
1757 ("1.5", "1.5"),
1758 ("0.1", "0.10000000000000001"),
1759 ("1.0", "1.0"),
1760 ("1e3", "1000.0"),
1761 ("-0.0", "-0.0"),
1762 ("1.7976931348623157e308", "1.7976931348623157e+308"),
1763 ("int16 -5", "int16 -5"),
1764 ("uint16 5", "uint16 5"),
1765 ("handle 5", "handle 5"),
1766 ("objectpath '/a/b'", "objectpath '/a/b'"),
1767 ("objectpath '/'", "objectpath '/'"),
1768 ("objectpath '/a_b'", "objectpath '/a_b'"),
1769 ("objectpath '/A/9'", "objectpath '/A/9'"),
1770 ("signature 'ay'", "signature 'ay'"),
1771 ("signature ''", "signature ''"),
1772 ("signature 'ii'", "signature 'ii'"),
1773 ("signature '{sv}'", "signature '{sv}'"),
1774 ("@o '/a/b'", "objectpath '/a/b'"),
1775 ("@g 'ay'", "signature 'ay'"),
1776 ("['a','b']", "['a', 'b']"),
1777 ("@as ['a','b']", "['a', 'b']"),
1778 ("@ay [1,2,3]", "[byte 0x01, 0x02, 0x03]"),
1779 ("b'bytes'", "b'bytes'"),
1780 ("b\"double\"", "b'double'"),
1781 ("{'x': 'y'}", "{'x': 'y'}"),
1782 ("@a{ss} {'x': 'y'}", "{'x': 'y'}"),
1783 ("('a', 5)", "('a', 5)"),
1784 ("<'nested variant'>", "<'nested variant'>"),
1785 ("<<'x'>>", "<<'x'>>"),
1786 ("@v <'x'>", "<'x'>"),
1787 ("@ms 'just'", "@ms 'just'"),
1788 ("@ms nothing", "@ms nothing"),
1789 ("just 'x'", "@ms 'x'"),
1790 ("@mi 5", "@mi 5"),
1791 ("@mu 7", "@mu 7"),
1792 ("'a=b'", "'a=b'"),
1793 ("[2, 1.5]", "[2.0, 1.5]"),
1794 ("[1.5, 2]", "[1.5, 2.0]"),
1795 ("[[1],[2]]", "[[1], [2]]"),
1796 ("{'a': 1, 'b': 2}", "{'a': 1, 'b': 2}"),
1797 ("{1: 'a'}", "{1: 'a'}"),
1798 ("[@ms 'a', 'b']", "[@ms 'a', 'b']"),
1799 ("['a', @ms 'b']", "[@ms 'a', 'b']"),
1800 ("[nothing, 'a']", "[@ms nothing, 'a']"),
1801 ("[just 'a', nothing]", "[@ms 'a', nothing]"),
1802 ("@(si) ('a', 5)", "('a', 5)"),
1803 ("@ai []", "@ai []"),
1804 ("@as []", "@as []"),
1805 ("@a{sv} {}", "@a{sv} {}"),
1806 ("@aai [[], []]", "[@ai [], []]"),
1807 ("[b'x', b'y']", "[b'x', b'y']"),
1808 ("[@o '/a', '/b']", "[objectpath '/a', '/b']"),
1809 ("@ao ['/a','/b']", "[objectpath '/a', '/b']"),
1810 ("'\\x41'", "'x41'"),
1811 ("'a\\'b'", "\"a'b\""),
1812 ("\"a'b\"", "\"a'b\""),
1813 ("'\\''", "\"'\""),
1814 (" 42 ", "42"),
1815 ("@i 42", "42"),
1816 ("@au [1,2]", "[uint32 1, 2]"),
1817 ("[<'a'>, <5>]", "[<'a'>, <5>]"),
1818 ("0x41", "65"),
1819 ("017", "15"),
1820 ("(1,)", "(1,)"),
1821 ("()", "()"),
1822 ("[1,2,3]", "[1, 2, 3]"),
1823 ("{'a', 5}", "{'a', 5}"),
1824 ("'a\\0b'", "'a0b'"),
1825 ("'a\\tb'", "'a\\tb'"),
1826 ("'\\u00e9'", "'é'"),
1827 ("b'\\u0000'", "b'u0000'"),
1830 ("b'a\\u0000b'", "b'au0000b'"),
1831 ("b'a\0b'", "b'a'"),
1834 ];
1835 for (input, expected) in cases {
1836 assert_eq!(round(input), *expected, "reading {input}");
1837 }
1838 }
1839
1840 #[test]
1843 fn reads_the_numeric_literals_the_tool_accepts() {
1844 let cases: &[(&str, &str)] = &[
1845 ("0b101", "5"),
1847 ("0B101", "5"),
1848 ("0b0", "0"),
1849 ("byte 0b11111111", "byte 0xff"),
1850 ("@t 0b1", "uint64 1"),
1851 ("0xe", "14"),
1853 ("0xE", "14"),
1854 ("0x1e5", "485"),
1855 ("-0x1", "-1"),
1856 ("+0x10", "16"),
1857 ("0x1.8p1", "3.0"),
1858 ("@d 0x1.8p1", "3.0"),
1859 ("@d 0x10", "16.0"),
1860 ("@t 0xFFFFFFFFFFFFFFFF", "uint64 18446744073709551615"),
1861 ("@d 017", "17.0"),
1863 ("double 0777", "777.0"),
1864 ("@d 08", "8.0"),
1865 ("@d 1E3", "1000.0"),
1866 ("double 1E3", "1000.0"),
1867 ("-", "0"),
1869 ("@i -", "0"),
1870 ("@y -", "byte 0x00"),
1871 ("@t -", "uint64 0"),
1872 ("-+5", "-5"),
1873 ("nan", "nan"),
1875 ("-nan", "-nan"),
1876 ("inf", "inf"),
1877 ("-inf", "-inf"),
1878 ("+inf", "inf"),
1879 ("+nan", "nan"),
1880 ("-infinity", "-inf"),
1881 ("double nan", "nan"),
1882 ("double inf", "inf"),
1883 ("@d nan", "nan"),
1884 ("just nan", "@md nan"),
1885 ("[1, nan]", "[1.0, nan]"),
1886 ("[nan, 1]", "[nan, 1.0]"),
1887 ("1e-400", "0.0"),
1889 ("-1e-400", "-0.0"),
1890 ("0.0e-400", "0.0"),
1891 ("2.2250738585072014e-308", "2.2250738585072014e-308"),
1892 ("1.", "1.0"),
1894 (".5", "0.5"),
1895 ("5.", "5.0"),
1896 ("-.5", "-0.5"),
1897 ("1.e3", "1000.0"),
1898 ];
1899 for (input, expected) in cases {
1900 assert_eq!(round(input), *expected, "reading {input}");
1901 }
1902 }
1903
1904 #[test]
1908 fn a_binary_exponent_out_of_range_is_clamped() {
1909 assert_eq!(round("0x0.0p-2147483645"), "0.0");
1910 assert_eq!(round("0x0.0p-9999999999"), "0.0");
1911 assert_eq!(round("0x1.0p-2147483645"), "0.0");
1912 assert_eq!(round("0x0.0p2147483647"), "0.0");
1913 }
1914
1915 #[test]
1919 fn reads_the_hexadecimal_doubles_the_tool_stores() {
1920 let cases: &[(&str, f64)] = &[
1921 ("@d 0x1.8p1", 3.0),
1922 ("@d 0x1p1023", 8.98846567431158e307),
1923 ("@d 0x1.fffffffffffff7ffffffffp1023", f64::MAX),
1924 ("@d 0x1.00000000000008p0", 1.0),
1925 (
1928 "@d 0xffffffffffffffffffffffffffffffffffffffffp0",
1929 1.461501637330903e48,
1930 ),
1931 ("@d 0x1.0000000000000000000000000000000000001p0", 1.0),
1932 ("@d 0x1000000000000000000000000000000000000p-140", 16.0),
1933 ("@d 0x1000000000000000000000000000000000001p-140", 16.0),
1934 (
1935 "@d 0x123456789abcdef123456789abcdef123456789abcdefp-100",
1936 8.596805828370696e22,
1937 ),
1938 ("@d 0x1p-1023", f64::from_bits(0x0008_0000_0000_0000)),
1940 ("@d 0x1p-1074", f64::from_bits(1)),
1941 ("@d 0x2p-1074", f64::from_bits(2)),
1942 ("@d 0x3p-1074", f64::from_bits(3)),
1943 ("@d 0x1.8p-1073", f64::from_bits(3)),
1944 ("@d -0x1p-1074", -f64::from_bits(1)),
1945 ("@d 0x1.000001p-1030", f64::from_bits(0x0000_1000_0010_0000)),
1946 ("@d 0x1.fffffffffffffffp-1023", f64::MIN_POSITIVE),
1948 ("@d 0x1.fffffffffffff8p-1023", f64::MIN_POSITIVE),
1949 ("@d 0x1p-1075", 0.0),
1952 ("@d 0x0.8p-1074", 0.0),
1953 ("@d 0x8000000000000000000000000000000000000000p-1234", 0.0),
1954 ("@d 0x1p-2000", 0.0),
1955 ("@d 0x1p-9999999999", 0.0),
1956 ("@d -0x1p-1075", -0.0),
1957 ("@d 0x0p2147483647", 0.0),
1958 ("@d 0x0p99999999999999999999", 0.0),
1959 ];
1960 for (input, expected) in cases {
1961 assert_eq!(
1962 double(input).to_bits(),
1963 expected.to_bits(),
1964 "reading {input}"
1965 );
1966 }
1967 }
1968
1969 #[test]
1973 fn refuses_the_hexadecimal_doubles_the_tool_refuses() {
1974 let cases: &[(&str, &str)] = &[
1975 ("@d 0x1.8p-1074", "3-14:number too big for any type"),
1978 ("@d 0x1.8p-1075", "3-14:number too big for any type"),
1979 (
1980 "@d 0x1.0000000000001p-1030",
1981 "3-26:number too big for any type",
1982 ),
1983 (
1984 "@d 0x1.0000000000000001p-1030",
1985 "3-29:number too big for any type",
1986 ),
1987 (
1988 "@d 0x1.0000000000000000001p-1075",
1989 "3-32:number too big for any type",
1990 ),
1991 (
1992 "@d 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1330",
1993 "3-80:number too big for any type",
1994 ),
1995 ("@d 0x1p1024", "3-11:number too big for any type"),
1997 ("@d 0x2p1023", "3-11:number too big for any type"),
1998 ("@d -0x1p1024", "3-12:number too big for any type"),
1999 (
2000 "@d 0x1.fffffffffffff8p1023",
2001 "3-26:number too big for any type",
2002 ),
2003 ("@d 0x1p2147483647", "3-17:number too big for any type"),
2004 (
2005 "@d 0x1p99999999999999999999",
2006 "3-27:number too big for any type",
2007 ),
2008 ];
2009 for (input, expected) in cases {
2010 assert_eq!(refuse(input), *expected, "refusing {input}");
2011 }
2012 }
2013
2014 #[test]
2018 fn refuses_what_the_tool_refuses_in_its_own_words() {
2019 let cases: &[(&str, &str)] = &[
2020 ("[]", "0-2:unable to infer type"),
2021 ("", "0:expected value"),
2022 ("garbage syntax (((", "0-7:unknown keyword"),
2023 (
2024 "uint32 99999999999999999999",
2025 "7-27:integer too big for any type",
2026 ),
2027 ("'unterminated", "0-13:unterminated string constant"),
2028 ("(1,2", "4:expected ',' or ')' to follow tuple element"),
2029 ("{'a':}", "5:expected value"),
2030 ("nothing", "0-7:unable to infer type"),
2031 ("@i 'str'", "3-8:can not parse as value of type 'i'"),
2032 ("3000000000", "0-10:number out of range for type 'i'"),
2033 (
2034 "9223372036854775807",
2035 "0-19:number out of range for type 'i'",
2036 ),
2037 (
2038 "18446744073709551615",
2039 "0-20:number out of range for type 'i'",
2040 ),
2041 ("99999999999999999999", "0-20:integer too big for any type"),
2042 ("uint32 -1", "7-9:number out of range for type 'u'"),
2043 ("uint32 4294967296", "7-17:number out of range for type 'u'"),
2044 ("byte 256", "5-8:number out of range for type 'y'"),
2045 ("0o17", "1-2:invalid character in number"),
2046 ("['a', 5]", "1-4,6-7:unable to find a common type"),
2047 (
2048 "{'a': 'b', 'c': 5}",
2049 "16-17:can not parse as value of type 's'",
2050 ),
2051 ("42 43", "3:expected end of input"),
2052 ("true false", "5:expected end of input"),
2053 ("@u", "2:expected value"),
2054 ("@", "0-1:invalid type declaration"),
2055 ("[,]", "1:expected value"),
2056 ("{}", "0-2:unable to infer type"),
2057 (
2058 "{'a'}",
2059 "4:expected ':' or ',' to follow dictionary entry key",
2060 ),
2061 ("(,)", "1:expected value"),
2062 ("@b 1", "3-4:can not parse as value of type 'b'"),
2063 ("B", "0:expected value"),
2064 ("_x", "0:expected value"),
2065 ("Foo", "0:expected value"),
2066 ("uint32x", "0-7:unknown keyword"),
2067 ("x1", "0:expected value"),
2068 ("a", "0:expected value"),
2069 ("%", "0:expected value"),
2070 ("=x", "0:expected value"),
2071 ("trueX", "0-5:unknown keyword"),
2072 ("TRUE", "0:expected value"),
2073 ("aB", "0-2:unknown keyword"),
2074 ("a_b", "0:expected value"),
2075 ("byte0x41", "0-8:unknown keyword"),
2076 ("just1", "0-5:unknown keyword"),
2077 ("ju st", "0-2:unknown keyword"),
2078 ("{[1]: 'a'}", "0-10:dictionary keys must have basic types"),
2079 ("(1)", "2:expected ',' after first tuple element"),
2081 ("('a')", "4:expected ',' after first tuple element"),
2082 ("((1))", "3:expected ',' after first tuple element"),
2083 ("((1,))", "5:expected ',' after first tuple element"),
2084 ("@(i) (1)", "7:expected ',' after first tuple element"),
2085 ("(((1),2),3)", "4:expected ',' after first tuple element"),
2086 ("(1 2)", "3:expected ',' after first tuple element"),
2087 ("(1,2,)", "5:expected value"),
2088 ("(1,2 3)", "5:expected ',' or ')' to follow tuple element"),
2089 ("1E3", "1-2:invalid character in number"),
2091 ("1E+3", "1-2:invalid character in number"),
2092 ("1E", "1-2:invalid character in number"),
2093 ("1d", "1-2:invalid character in number"),
2094 ("0x1p3", "3-4:invalid character in number"),
2095 ("5e-324", "0-6:number too big for any type"),
2097 ("1e-310", "0-6:number too big for any type"),
2098 ("1e-308", "0-6:number too big for any type"),
2099 ("1e400", "0-5:number too big for any type"),
2100 ("-1e400", "0-6:number too big for any type"),
2101 ("1.7976931348623157e309", "0-22:number too big for any type"),
2102 ("@d 5e-324", "3-9:number too big for any type"),
2103 ("1.5.5", "3-4:invalid character in number"),
2105 ("1..5", "2-3:invalid character in number"),
2106 ("1e", "1-2:invalid character in number"),
2107 ("1e+", "1-2:invalid character in number"),
2108 ("1.5e", "3-4:invalid character in number"),
2109 ("+", "0-1:invalid character in number"),
2110 ("++5", "0-1:invalid character in number"),
2111 ("+-5", "0-1:invalid character in number"),
2112 ("--5", "0-3:number out of range for type 'i'"),
2113 ("0xg", "1-2:invalid character in number"),
2114 ("0b12", "3-4:invalid character in number"),
2115 ("0b102", "4-5:invalid character in number"),
2116 ("0b1e1", "1-2:invalid character in number"),
2117 ("-INF", "1-2:invalid character in number"),
2118 ("+INFINITY", "0-1:invalid character in number"),
2119 ("infinity", "0-8:unknown keyword"),
2120 ("nan5", "0-4:unknown keyword"),
2121 ("nan(0x1)", "3:expected end of input"),
2122 ("byte nan", "5-6:invalid character in number"),
2124 ("@i nan", "3-4:invalid character in number"),
2125 ("uint64 nan", "7-8:invalid character in number"),
2126 ("byte 1.5", "6-7:invalid character in number"),
2127 ("uint32 1.5", "8-9:invalid character in number"),
2128 ("@x 1.5", "4-5:invalid character in number"),
2129 ("int32 1e3", "7-8:invalid character in number"),
2130 ("@d 0b101", "4-5:invalid character in number"),
2131 ("@d -", "3-4:invalid character in number"),
2132 (
2134 "int64 -9223372036854775809",
2135 "6-26:number out of range for type 'x'",
2136 ),
2137 (
2138 "-18446744073709551615",
2139 "0-21:number out of range for type 'i'",
2140 ),
2141 ("18446744073709551616", "0-20:integer too big for any type"),
2142 ("objectpath 'notapath'", "11-21:not a valid object path"),
2144 ("objectpath ''", "11-13:not a valid object path"),
2145 ("objectpath '/a/'", "11-16:not a valid object path"),
2146 ("objectpath '//'", "11-15:not a valid object path"),
2147 ("objectpath '/a-b'", "11-17:not a valid object path"),
2148 ("@o 'bad'", "3-8:not a valid object path"),
2149 ("signature 'zz'", "10-14:not a valid signature"),
2150 ("signature 'a'", "10-13:not a valid signature"),
2151 ("signature 'ms'", "10-14:not a valid signature"),
2152 ("signature 'r'", "10-13:not a valid signature"),
2153 ("signature '{vs}'", "10-16:not a valid signature"),
2154 ("@g 'zz'", "3-7:not a valid signature"),
2155 ("@z 5", "0-2:invalid type declaration"),
2158 ("@r 5", "0-2:type declarations must be definite"),
2159 ("@* 5", "0-2:type declarations must be definite"),
2160 ("@? 5", "0-2:type declarations must be definite"),
2161 ("@** 5", "0-3:invalid type declaration"),
2162 ("@i5", "0-3:invalid type declaration"),
2163 ("@ii", "0-3:invalid type declaration"),
2164 ("@m", "0-2:invalid type declaration"),
2165 ("@i(5)", "0-5:invalid type declaration"),
2166 ("@i[5]", "0-4:invalid type declaration"),
2167 ("@i)", "2:expected value"),
2168 ("@i,", "2:expected value"),
2169 ("@as [1]", "5-6:can not parse as value of type 's'"),
2171 ("@ab [1]", "5-6:can not parse as value of type 'b'"),
2172 ("@ai [1,'a']", "7-10:can not parse as value of type 'i'"),
2173 ("@as ['a', 5]", "10-11:can not parse as value of type 's'"),
2174 (
2175 "@a{ss} {'a': 5}",
2176 "13-14:can not parse as value of type 's'",
2177 ),
2178 (
2179 "@a{sv} {'a': 1}",
2180 "13-14:can not parse as value of type 'v'",
2181 ),
2182 ("@av [1]", "5-6:can not parse as value of type 'v'"),
2183 ("@ai 5", "4-5:can not parse as value of type 'ai'"),
2184 ("@i []", "3-5:can not parse as value of type 'i'"),
2185 ("@as [nothing]", "5-12:can not parse as value of type 's'"),
2186 ("[[]]", "0-4:unable to infer type"),
2189 ("just []", "0-7:unable to infer type"),
2190 ("just nothing", "0-12:unable to infer type"),
2191 ("just just nothing", "0-17:unable to infer type"),
2192 ("('a', [])", "0-9:unable to infer type"),
2193 ("[nothing]", "0-9:unable to infer type"),
2194 ("[nothing, nothing]", "0-18:unable to infer type"),
2195 ("{'a': nothing}", "0-14:unable to infer type"),
2196 ("[[[]]]", "0-6:unable to infer type"),
2197 ("[[], []]", "0-8:unable to infer type"),
2198 ("nothing 5", "0-7:unable to infer type"),
2199 ("nothing nothing", "0-7:unable to infer type"),
2200 ("[<[]>]", "2-4:unable to infer type"),
2201 ("<just nothing>", "1-13:unable to infer type"),
2202 ("{nothing: 1}", "0-12:dictionary keys must have basic types"),
2204 ("{{}: 'a'}", "0-9:dictionary keys must have basic types"),
2205 ("{<1>: 'a'}", "0-10:dictionary keys must have basic types"),
2206 ("{'a': 1, 2: 'b'}", "1-4,9-10:unable to find a common type"),
2208 ("{1: 'a', 'b': 2}", "1-2,9-12:unable to find a common type"),
2209 (
2210 "{'a': 'b', 5: 'c'}",
2211 "1-4,11-12:unable to find a common type",
2212 ),
2213 (
2214 "{'a': 1, 'b': 2, 'c': 'x'}",
2215 "22-25:can not parse as value of type 'i'",
2216 ),
2217 ("<1 2>", "3:expected '>' to follow variant value"),
2219 ("{'a', 5, 6}", "7:expected '}' at end of dictionary entry"),
2220 (
2221 "{'a': 1 'b': 2}",
2222 "8:expected ',' or '}' to follow dictionary entry",
2223 ),
2224 ("[1 2]", "3:expected ',' or ']' to follow array element"),
2225 ("'\\uZZZZ'", "3:invalid 4-character unicode escape"),
2227 ("'\\u'", "3:invalid 4-character unicode escape"),
2228 ("'\\u12'", "3-5:invalid 4-character unicode escape"),
2229 ("'\\u00'", "3-5:invalid 4-character unicode escape"),
2230 ("'\\U110000'", "3-9:invalid 8-character unicode escape"),
2231 ("'\\U0001'", "3-7:invalid 8-character unicode escape"),
2232 ("'\\u0000'", "3-7:invalid 4-character unicode escape"),
2235 ("'\\U00000000'", "3-11:invalid 8-character unicode escape"),
2236 ("'a\\u0000b'", "4-8:invalid 4-character unicode escape"),
2237 ("'ab\\u0000'", "5-9:invalid 4-character unicode escape"),
2238 ("'\\u0000x'", "3-7:invalid 4-character unicode escape"),
2239 ("@s '\\u0000'", "6-10:invalid 4-character unicode escape"),
2240 ("@o '/a\\u0000b'", "8-12:invalid 4-character unicode escape"),
2241 (
2242 "objectpath '\\u0000'",
2243 "14-18:invalid 4-character unicode escape",
2244 ),
2245 ("@g '\\u0000'", "6-10:invalid 4-character unicode escape"),
2246 (
2247 "signature 'a\\u0000y'",
2248 "14-18:invalid 4-character unicode escape",
2249 ),
2250 ("{'\\u0000': 1}", "4-8:invalid 4-character unicode escape"),
2251 (
2252 "{'a': '\\u0000'}",
2253 "9-13:invalid 4-character unicode escape",
2254 ),
2255 (
2256 "['a', '\\u0000']",
2257 "9-13:invalid 4-character unicode escape",
2258 ),
2259 ("<'\\u0000'>", "4-8:invalid 4-character unicode escape"),
2260 ("@ms '\\u0000'", "7-11:invalid 4-character unicode escape"),
2261 ("('\\u0000',)", "4-8:invalid 4-character unicode escape"),
2262 ("'\\ud800'", "3-7:invalid 4-character unicode escape"),
2264 ("'\\U0000d800'", "3-11:invalid 8-character unicode escape"),
2265 ("'\\U00110000'", "3-11:invalid 8-character unicode escape"),
2266 ("'a\0b'", "2-3:NUL byte in string constant"),
2271 ("'\0'", "1-2:NUL byte in string constant"),
2272 ("@o '/a\0b'", "6-7:NUL byte in string constant"),
2273 ("{'\0': 1}", "2-3:NUL byte in string constant"),
2274 ];
2275 for (input, expected) in cases {
2276 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2277 }
2278 }
2279
2280 #[test]
2285 fn a_dictionary_reads_its_values_against_the_first_entry() {
2286 let cases: &[(&str, &str)] = &[
2287 ("{'a': 1, 'b': uint32 2}", "{'a': 1, 'b': 2}"),
2289 ("{'a': uint32 2, 'b': 1}", "{'a': uint32 2, 'b': 1}"),
2290 ("{'a': 1.5, 'b': 1}", "{'a': 1.5, 'b': 1.0}"),
2291 ("{'a': 0x1.8p1, 'b': 1}", "{'a': 3.0, 'b': 1.0}"),
2292 ("{'a': 1.5, 'b': 1E3}", "{'a': 1.5, 'b': 1000.0}"),
2293 ("{'a': just 'y', 'b': 'x'}", "{'a': @ms 'y', 'b': 'x'}"),
2295 ("{'a': just 2, 'b': 1}", "{'a': @mi 2, 'b': 1}"),
2296 (
2297 "{'a': @ms nothing, 'b': 'x'}",
2298 "{'a': @ms nothing, 'b': 'x'}",
2299 ),
2300 ("{'a': just 1, 'b': nothing}", "{'a': @mi 1, 'b': nothing}"),
2301 ("{'a': [1], 'b': []}", "{'a': [1], 'b': []}"),
2303 ("{'a': {'d': 2}, 'c': {}}", "{'a': {'d': 2}, 'c': {}}"),
2304 ("{'a': <1>, 'b': <'x'>}", "{'a': <1>, 'b': <'x'>}"),
2305 (
2307 "{'a': 1, 'b': 2, 'c': uint32 3}",
2308 "{'a': 1, 'b': 2, 'c': 3}",
2309 ),
2310 (
2311 "{'a': uint32 1, 'b': 2, 'c': 3}",
2312 "{'a': uint32 1, 'b': 2, 'c': 3}",
2313 ),
2314 ("{1: 'a', 2.5: 'b'}", "{1.0: 'a', 2.5: 'b'}"),
2316 ("{2.5: 'a', 1: 'b'}", "{2.5: 'a', 1.0: 'b'}"),
2317 ];
2318 for (input, expected) in cases {
2319 assert_eq!(round(input), *expected, "reading {input}");
2320 }
2321 }
2322
2323 #[test]
2328 fn a_declaration_under_a_driven_type_gives_up_its_type() {
2329 let cases: &[(&str, &str)] = &[
2330 ("@as [@o '/a']", "['/a']"),
2331 ("@as [@ms 'a']", "['a']"),
2332 ("@ai [@u 5]", "[5]"),
2333 ("@ao ['/a', @s '/b']", "[objectpath '/a', '/b']"),
2334 ("@a{ss} {'a': @o '/b'}", "{'a': '/b'}"),
2335 ("{'a': 'x', 'b': @o '/y'}", "{'a': 'x', 'b': '/y'}"),
2336 (
2337 "{'a': 'x', 'b': @o 'notapath'}",
2338 "{'a': 'x', 'b': 'notapath'}",
2339 ),
2340 ("{'a': 'x', 'b': @g 'ii'}", "{'a': 'x', 'b': 'ii'}"),
2341 ("{'a': 'x', 'b': @ms 'y'}", "{'a': 'x', 'b': 'y'}"),
2342 ("{'a': 1, 'b': @mi 2}", "{'a': 1, 'b': 2}"),
2343 (
2344 "{'a': @g 'ii', 'b': 'x'}",
2345 "{'a': signature 'ii', 'b': 'x'}",
2346 ),
2347 ];
2348 for (input, expected) in cases {
2349 assert_eq!(round(input), *expected, "reading {input}");
2350 }
2351 let refusals: &[(&str, &str)] = &[
2353 ("@as [@i 5]", "8-9:can not parse as value of type 's'"),
2354 ("@ai [@d 1.5]", "9-10:invalid character in number"),
2355 (
2356 "{'a': 1, 'b': @s 'x'}",
2357 "17-20:can not parse as value of type 'i'",
2358 ),
2359 (
2360 "{'a': 1, 'b': @b true}",
2361 "17-21:can not parse as value of type 'i'",
2362 ),
2363 (
2364 "{'a': true, 'b': @i 1}",
2365 "20-21:can not parse as value of type 'b'",
2366 ),
2367 ("{'a': 1, 'b': @d 1.5}", "18-19:invalid character in number"),
2368 (
2369 "{'a': 'x', 'b': @ms nothing}",
2370 "20-27:can not parse as value of type 's'",
2371 ),
2372 (
2373 "{'a': 1, 'b': uint32 4294967296}",
2374 "21-31:number out of range for type 'i'",
2375 ),
2376 ];
2377 for (input, expected) in refusals {
2378 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2379 }
2380 }
2381
2382 #[test]
2388 fn refuses_a_dictionary_value_against_the_settled_type() {
2389 let cases: &[(&str, &str)] = &[
2390 ("{'a': 1, 'b': 1.5}", "15-16:invalid character in number"),
2392 (
2393 "{'a': 1, 'b': 0x1.8p1}",
2394 "17-18:invalid character in number",
2395 ),
2396 ("{'a': 1, 'b': 1e3}", "15-16:invalid character in number"),
2397 (
2398 "{'a': 1, 'b': 2, 'c': 1.5}",
2399 "23-24:invalid character in number",
2400 ),
2401 (
2403 "{'a': 'x', 'b': just 'y'}",
2404 "16-24:can not parse as value of type 's'",
2405 ),
2406 (
2407 "{'a': 'y', 'b': nothing}",
2408 "16-23:can not parse as value of type 's'",
2409 ),
2410 (
2411 "{'a': 1, 'b': just 2}",
2412 "14-20:can not parse as value of type 'i'",
2413 ),
2414 (
2415 "{'a': 1, 'b': 2, 'c': nothing}",
2416 "22-29:can not parse as value of type 'i'",
2417 ),
2418 (
2419 "{'a': 'x', 'b': 'y', 'c': just 'z'}",
2420 "26-34:can not parse as value of type 's'",
2421 ),
2422 (
2424 "{'a': (1,2), 'b': ('x','y')}",
2425 "19-22:can not parse as value of type 'i'",
2426 ),
2427 (
2428 "{'a': ('x','y'), 'b': (1,2)}",
2429 "23-24:can not parse as value of type 's'",
2430 ),
2431 (
2432 "{'a': [1], 'b': ['x']}",
2433 "17-20:can not parse as value of type 'i'",
2434 ),
2435 (
2436 "{'a': {'x': 1}, 'b': {'y': 'z'}}",
2437 "27-30:can not parse as value of type 'i'",
2438 ),
2439 ("{'a': @o '/y', 'b': 'x'}", "20-23:not a valid object path"),
2440 (
2441 "{'a': @o '/z', 'b': 'x', 'c': 'y'}",
2442 "20-23:not a valid object path",
2443 ),
2444 (
2445 "{'a': byte 1, 'b': 256}",
2446 "19-22:number out of range for type 'y'",
2447 ),
2448 (
2449 "{'a': 1, 'b': 99999999999999999999}",
2450 "14-34:integer too big for any type",
2451 ),
2452 (
2455 "{'a': 1, 'b': ['x', 5]}",
2456 "14-22:can not parse as value of type 'i'",
2457 ),
2458 (
2459 "{'a': 1, 'b': {[1]: 'a'}}",
2460 "14-24:can not parse as value of type 'i'",
2461 ),
2462 (
2463 "{'a': 1, 'b': <[]>}",
2464 "14-18:can not parse as value of type 'i'",
2465 ),
2466 (
2467 "{'a': 1, 'b': {'y': 'z'}}",
2468 "14-24:can not parse as value of type 'i'",
2469 ),
2470 (
2471 "{'a': 5, 'b': []}",
2472 "14-16:can not parse as value of type 'i'",
2473 ),
2474 (
2475 "{'a': [1], 'b': 'x'}",
2476 "16-19:can not parse as value of type 'ai'",
2477 ),
2478 (
2479 "{'a': <1>, 'b': 'x'}",
2480 "16-19:can not parse as value of type 'v'",
2481 ),
2482 (
2483 "{'a': 'x', 'b': b'y'}",
2484 "16-20:can not parse as value of type 's'",
2485 ),
2486 (
2487 "{'a': b'x', 'b': 'y'}",
2488 "17-20:can not parse as value of type 'ay'",
2489 ),
2490 ("{'a': <1>, 'b': <[]>}", "17-19:unable to infer type"),
2492 ("{'a': nothing, 'b': 'y'}", "0-24:unable to infer type"),
2495 (
2496 "{'a': nothing, 'b': 2, 'c': 3}",
2497 "0-30:unable to infer type",
2498 ),
2499 ("{'a': [], 'b': [1]}", "0-19:unable to infer type"),
2500 ("{'a': [], 'b': 5}", "0-17:unable to infer type"),
2501 ("{'a': [], 'b': 5, 'c': 6}", "0-25:unable to infer type"),
2502 ("{'a': [], 'b': ['x', 5]}", "0-24:unable to infer type"),
2503 ("{'a': {}, 'c': {'d': 2}}", "0-24:unable to infer type"),
2504 ("{'q': {'a': [], 'b': 5}}", "0-24:unable to infer type"),
2505 ("[{'a': [], 'b': 5}]", "0-19:unable to infer type"),
2506 ("({'a': [], 'b': 5},)", "0-20:unable to infer type"),
2507 ("just {'a': [], 'b': 5}", "0-22:unable to infer type"),
2508 ("<{'a': [], 'b': 5}>", "1-18:unable to infer type"),
2509 (
2512 "{[1]: [], 'b': 5}",
2513 "1-4,10-13:unable to find a common type",
2514 ),
2515 (
2516 "{'a': [], [1]: 5}",
2517 "1-4,10-13:unable to find a common type",
2518 ),
2519 ("{'a': 1, @u 2: 3}", "1-4,9-13:unable to find a common type"),
2520 ("{@o '/a': 1, 'b': 2}", "13-16:not a valid object path"),
2521 ("{'a': 1, @o '/b': 2}", "1-4:not a valid object path"),
2522 ];
2523 for (input, expected) in cases {
2524 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2525 }
2526 }
2527
2528 #[test]
2531 fn a_bytestring_ends_at_its_first_nul() {
2532 let cases: &[(&str, &[u8])] = &[
2533 (r"b'\0'", &[0]),
2534 (r"b''", &[0]),
2535 (r"b'\400'", &[0]),
2536 (r"b'\0001'", &[0]),
2537 (r"b'\0\0'", &[0]),
2538 (r"b'a\0b'", &[b'a', 0]),
2539 (r"b'a\0'", &[b'a', 0]),
2540 (r"b'\101'", &[b'A', 0]),
2541 ("b'bytes'", b"bytes\0"),
2542 ];
2543 for (input, expected) in cases {
2544 let (ty, value) = from_text(input).unwrap_or_else(|e| panic!("{input}: {e}"));
2545 assert_eq!(ty.signature(), "ay", "type of {input}");
2546 assert_eq!(
2547 value,
2548 Value::Bytes((*expected).to_vec()),
2549 "value of {input}"
2550 );
2551 }
2552 }
2553
2554 #[test]
2558 fn a_backslash_before_a_line_feed_continues_the_line() {
2559 assert_eq!(round("'a\\\nb'"), "'ab'");
2560 assert_eq!(round("'\\\n'"), "''");
2561 assert_eq!(round("'a\\\n'"), "'a'");
2562 assert_eq!(round("'a\\\n\\\nb'"), "'ab'");
2563 assert_eq!(round("'a\\\\\nb'"), "'a\\\\\\nb'");
2565 assert_eq!(round("'a\\\n\nb'"), "'a\\nb'");
2567 let (ty, value) = from_text("b'a\\\nb'").expect("the bytestring reads");
2568 assert_eq!(ty.signature(), "ay");
2569 assert_eq!(value, Value::Bytes(b"ab\0".to_vec()));
2570 }
2571
2572 #[test]
2575 fn refuses_the_level_past_the_nesting_cap() {
2576 for (open, close) in [("[", "]"), ("(", ",)"), ("<", ">")] {
2579 for depth in [125usize, 126, 127] {
2580 let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2581 assert!(
2582 from_text(&text).is_ok(),
2583 "depth {depth} of {open} was refused"
2584 );
2585 }
2586 for depth in [128usize, 129, 200] {
2587 let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2588 assert_eq!(
2589 refuse(&text),
2590 "128:variant nested too deeply",
2591 "depth {depth} of {open}"
2592 );
2593 }
2594 }
2595 assert!(from_text(&format!("{}5", "just ".repeat(127))).is_ok());
2597 assert!(from_text(&format!("{}5", "@i ".repeat(127))).is_ok());
2598 assert!(from_text(&format!("{}5", "uint32 ".repeat(127))).is_ok());
2599 for text in [
2600 format!("{}5", "just ".repeat(128)),
2601 format!("{}5", "@i ".repeat(128)),
2602 format!("{}5", "uint32 ".repeat(128)),
2603 ] {
2604 assert!(
2605 refuse(&text).ends_with("variant nested too deeply"),
2606 "{text}"
2607 );
2608 }
2609 }
2610
2611 #[test]
2616 fn a_signature_value_takes_129_levels() {
2617 let arrays = |count: usize| "a".repeat(count);
2618 for count in [0usize, 1, 65, 127, 128] {
2619 for text in [
2620 format!("signature '{}y'", arrays(count)),
2621 format!("@g '{}y'", arrays(count)),
2622 ] {
2623 assert!(from_text(&text).is_ok(), "{count} arrays was refused");
2624 }
2625 }
2626 assert_eq!(
2627 refuse(&format!("signature '{}y'", arrays(129))),
2628 "10-142:not a valid signature"
2629 );
2630 assert_eq!(
2631 refuse(&format!("@g '{}y'", arrays(129))),
2632 "3-135:not a valid signature"
2633 );
2634 let deep = format!(
2636 "{}signature '{}y'{}",
2637 "[".repeat(100),
2638 arrays(128),
2639 "]".repeat(100)
2640 );
2641 assert!(from_text(&deep).is_ok());
2642 }
2643
2644 #[test]
2652 fn a_declaration_takes_128_levels_from_where_it_stands() {
2653 let arrays = |count: usize| "a".repeat(count);
2654 for text in [
2655 format!("@{}y []", arrays(127)),
2656 format!("@{}() []", arrays(128)),
2657 format!("@{}(y) []", arrays(126)),
2658 format!("@{}(()) []", arrays(127)),
2659 format!("@{}{{sy}} []", arrays(126)),
2660 format!("@{}{{s()}} []", arrays(127)),
2661 format!("@{}(y()) []", arrays(126)),
2662 format!("@{}((y)y) []", arrays(125)),
2663 format!("[@{}y []]", arrays(126)),
2664 format!("[[@{}y []]]", arrays(125)),
2665 ] {
2666 assert!(from_text(&text).is_ok(), "{text} was refused");
2667 }
2668 let deep = "type declaration recurses too deeply";
2669 let invalid = "invalid type declaration";
2670 let indefinite = "type declarations must be definite";
2671 let cases: &[(String, String)] = &[
2672 (format!("@{}y []", arrays(128)), format!("0-130:{deep}")),
2673 (format!("@{}y []", arrays(129)), format!("0-131:{invalid}")),
2674 (format!("@{}(y) []", arrays(127)), format!("0-131:{deep}")),
2675 (format!("@{}() []", arrays(129)), format!("0-132:{invalid}")),
2676 (
2677 format!("@{}{{sy}} []", arrays(127)),
2678 format!("0-132:{deep}"),
2679 ),
2680 (
2681 format!("@{}(()) []", arrays(128)),
2682 format!("0-133:{invalid}"),
2683 ),
2684 (format!("@{}(y()) []", arrays(127)), format!("0-133:{deep}")),
2685 (
2686 format!("@{}((y)y) []", arrays(126)),
2687 format!("0-133:{deep}"),
2688 ),
2689 (format!("@{}r 5", arrays(66)), format!("0-68:{indefinite}")),
2692 (
2693 format!("@{}r 5", arrays(127)),
2694 format!("0-129:{indefinite}"),
2695 ),
2696 (format!("@{}r 5", arrays(128)), format!("0-130:{deep}")),
2697 (format!("@{}r 5", arrays(129)), format!("0-131:{invalid}")),
2698 (
2699 format!("@{}* 5", arrays(127)),
2700 format!("0-129:{indefinite}"),
2701 ),
2702 (format!("@{}* 5", arrays(128)), format!("0-130:{deep}")),
2703 (
2704 format!("@{}(r) 5", arrays(126)),
2705 format!("0-130:{indefinite}"),
2706 ),
2707 (format!("@{}(r) 5", arrays(127)), format!("0-131:{deep}")),
2708 (format!("[@{}y []]", arrays(127)), format!("1-130:{deep}")),
2710 (format!("[[@{}y []]]", arrays(126)), format!("2-130:{deep}")),
2711 ];
2712 for (text, expected) in cases {
2713 assert_eq!(refuse(text), *expected, "refusing {text}");
2714 }
2715 }
2716
2717 #[test]
2720 fn a_fault_in_the_value_stands_ahead_of_trailing_input() {
2721 let cases: &[(&str, &str)] = &[
2722 ("@i 'x' 5", "3-6:can not parse as value of type 'i'"),
2723 ("3000000000 5", "0-10:number out of range for type 'i'"),
2724 ("@d 5e-324 5", "3-9:number too big for any type"),
2725 ("objectpath 'bad' 5", "11-16:not a valid object path"),
2726 ("nothing 5", "0-7:unable to infer type"),
2727 ("(1) 5", "2:expected ',' after first tuple element"),
2728 ("42 43", "3:expected end of input"),
2730 ("nan(0x1)", "3:expected end of input"),
2731 ];
2732 for (input, expected) in cases {
2733 assert_eq!(refuse(input), *expected, "refusing {input:?}");
2734 }
2735 }
2736
2737 #[test]
2741 fn deep_nesting_does_not_overflow_the_stack() {
2742 for text in [
2743 "[".repeat(50_000),
2744 format!("{}1{}", "[".repeat(50_000), "]".repeat(50_000)),
2745 format!("{}1{}", "(".repeat(50_000), ")".repeat(50_000)),
2746 format!("{}1{}", "<".repeat(50_000), ">".repeat(50_000)),
2747 format!("{}1", "just ".repeat(50_000)),
2748 format!("{}1{}", "{'a': ".repeat(20_000), "}".repeat(20_000)),
2749 format!("{}5", "@i ".repeat(50_000)),
2750 format!("@{}i 5", "a".repeat(50_000)),
2751 ] {
2752 assert!(from_text(&text).is_err(), "{:.20} was accepted", text);
2753 }
2754 }
2755
2756 #[test]
2759 fn the_printers_output_reads_back() {
2760 let cases = [
2761 "nan",
2762 "-nan",
2763 "inf",
2764 "-inf",
2765 "1.5",
2766 "-0.0",
2767 "0.10000000000000001",
2768 "1.7976931348623157e+308",
2769 "uint32 42",
2770 "byte 0x41",
2771 "@ms nothing",
2772 "b'bytes'",
2773 "{'x': 'y'}",
2774 "('a', 5)",
2775 "<'x'>",
2776 "objectpath '/a/b'",
2777 "signature 'ay'",
2778 "(1,)",
2779 "[byte 0x01, 0x02]",
2780 "@a{sv} {}",
2781 "[@ms 'a', nothing]",
2782 "{'a', 5}",
2783 "int64 -5",
2784 "handle 5",
2785 "'a\\ab'",
2788 "'a\\bb'",
2789 "'a\\fb'",
2790 "'a\\nb'",
2791 "'a\\rb'",
2792 "'a\\tb'",
2793 "'a\\vb'",
2794 "'a\\\\b'",
2795 "'a\\u001bb'",
2796 "'a\\u007fb'",
2797 "\"a'b\"",
2798 "'a\"b'",
2799 "\"a'\\\"b\"",
2800 "'héllo'",
2801 "b'a\\tb'",
2804 "b'a\\nb'",
2805 "b'a\\rb'",
2806 "b'a\\bb'",
2807 "b'a\\fb'",
2808 "b'a\\vb'",
2809 "b'a\\\\b'",
2810 "b'a\\\"b'",
2811 "b\"a'b\"",
2812 "b\"a'\\\"b\"",
2813 "b'\\377'",
2814 "b'h\\303\\251'",
2815 "@mmi 5",
2819 "@mmi just nothing",
2820 "@mmi nothing",
2821 "@mmmi just just nothing",
2822 "@mmmi just nothing",
2823 "@mmmmi just just just nothing",
2824 "@mms just nothing",
2825 "@mmv just nothing",
2826 "@mmv <5>",
2827 "@mmay just nothing",
2828 "@mm() just nothing",
2829 "@mammi [just nothing]",
2830 "[@mmi just nothing, nothing, 5]",
2831 "[@mmmi just just nothing, just nothing, nothing, 5]",
2832 "{'a': @mmi just nothing, 'b': nothing, 'c': 5}",
2833 "{'a', @mmi just nothing}",
2834 "(@mmi just nothing,)",
2835 "(@mmi just nothing, @mmi nothing, @mmi 5)",
2836 ];
2837 for text in cases {
2838 let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
2839 let printed = to_text(&ty, &value).unwrap();
2840 assert_eq!(printed, text, "printing {text}");
2841 let (again_ty, again_value) =
2842 from_text(&printed).unwrap_or_else(|e| panic!("{printed}: {e}"));
2843 assert_eq!(again_ty, ty, "type of {text}");
2844 assert_eq!(again_value, value, "value of {text}");
2845 }
2846 let printed = to_text(&Type::Double, &Value::double(f64::from_bits(1))).unwrap();
2849 assert_eq!(printed, "4.9406564584124654e-324");
2850 assert_eq!(
2851 refuse(&printed),
2852 "0-23:number too big for any type",
2853 "the subnormal the printer writes"
2854 );
2855 }
2856
2857 #[test]
2864 fn every_maybe_chain_the_printer_writes_reads_back() {
2865 let leaves: &[(&str, Value)] = &[
2866 ("i", Value::I32(5)),
2867 ("s", Value::Str("x".into())),
2868 ("v", Value::variant(Type::I32, Value::I32(5))),
2869 ("ay", Value::Bytes(vec![0x01])),
2870 ("()", Value::Tuple(Vec::new())),
2871 ("ai", Value::Array(vec![Value::I32(1)])),
2872 (
2873 "(is)",
2874 Value::Tuple(vec![Value::I32(1), Value::Str("x".into())]),
2875 ),
2876 (
2877 "a{si}",
2878 Value::Array(vec![Value::Tuple(vec![
2879 Value::Str("k".into()),
2880 Value::I32(1),
2881 ])]),
2882 ),
2883 ];
2884 for (element, leaf) in leaves {
2885 for depth in 1..=4usize {
2886 let signature = format!("{}{element}", "m".repeat(depth));
2887 let ty = Type::parse(&signature).unwrap();
2888 for set in 0..=depth {
2889 let mut value = if set == depth {
2890 leaf.clone()
2891 } else {
2892 Value::Maybe(None)
2893 };
2894 for _ in 0..set {
2895 value = Value::Maybe(Some(Box::new(value)));
2896 }
2897 let printed = to_text(&ty, &value).unwrap();
2898 let (again_ty, again_value) = from_text(&printed)
2899 .unwrap_or_else(|e| panic!("{signature} set {set}: {printed}: {e}"));
2900 assert_eq!(again_ty, ty, "type of {printed}");
2901 assert_eq!(again_value, value, "value of {printed}");
2902 }
2903 }
2904 }
2905 }
2906
2907 #[test]
2910 fn serializes_in_host_byte_order() {
2911 let (ty, value) = from_text("uint32 42").unwrap();
2912 assert_eq!(ty.signature(), "u");
2913 assert_eq!(to_bytes(&ty, &value).unwrap(), 42u32.to_le_bytes());
2914 let (ty, value) = from_text("1.5").unwrap();
2915 assert_eq!(ty.signature(), "d");
2916 assert_eq!(to_bytes(&ty, &value).unwrap(), 1.5f64.to_le_bytes());
2917 }
2918}