(index<- ) ./libextra/json.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Rust JSON serialization library
12 // Copyright (c) 2011 Google Inc.
13
14 #[forbid(non_camel_case_types)];
15 #[allow(missing_doc)];
16
17 //! json parsing and serialization
18
19 use std::char;
20 use std::cast::transmute;
21 use std::float;
22 use std::hashmap::HashMap;
23 use std::io::WriterUtil;
24 use std::io;
25 use std::str;
26 use std::to_str;
27
28 use serialize::Encodable;
29 use serialize;
30 use treemap::TreeMap;
31
32 /// Represents a json value
33 #[deriving(Clone, Eq)]
34 pub enum Json {
35 Number(float),
36 String(~str),
37 Boolean(bool),
38 List(List),
39 Object(~Object),
40 Null,
41 }
42
43 pub type List = ~[Json];
44 pub type Object = TreeMap<~str, Json>;
45
46 #[deriving(Eq)]
47 /// If an error occurs while parsing some JSON, this is the structure which is
48 /// returned
49 pub struct Error {
50 /// The line number at which the error occurred
51 line: uint,
52 /// The column number at which the error occurred
53 col: uint,
54 /// A message describing the type of the error
55 msg: @~str,
56 }
57
58 fn escape_str(s: &str) -> ~str {
59 let mut escaped = ~"\"";
60 for c in s.iter() {
61 match c {
62 '"' => escaped.push_str("\\\""),
63 '\\' => escaped.push_str("\\\\"),
64 '\x08' => escaped.push_str("\\b"),
65 '\x0c' => escaped.push_str("\\f"),
66 '\n' => escaped.push_str("\\n"),
67 '\r' => escaped.push_str("\\r"),
68 '\t' => escaped.push_str("\\t"),
69 _ => escaped.push_char(c),
70 }
71 };
72
73 escaped.push_char('"');
74
75 escaped
76 }
77
78 fn spaces(n: uint) -> ~str {
79 let mut ss = ~"";
80 do n.times {
81 ss.push_str(" ");
82 }
83 return ss;
84 }
85
86 /// A structure for implementing serialization to JSON.
87 pub struct Encoder {
88 priv wr: @io::Writer,
89 }
90
91 /// Creates a new JSON encoder whose output will be written to the writer
92 /// specified.
93 pub fn Encoder(wr: @io::Writer) -> Encoder {
94 Encoder {
95 wr: wr
96 }
97 }
98
99 impl serialize::Encoder for Encoder {
100 fn emit_nil(&mut self) { self.wr.write_str("null") }
101
102 fn emit_uint(&mut self, v: uint) { self.emit_float(v as float); }
103 fn emit_u64(&mut self, v: u64) { self.emit_float(v as float); }
104 fn emit_u32(&mut self, v: u32) { self.emit_float(v as float); }
105 fn emit_u16(&mut self, v: u16) { self.emit_float(v as float); }
106 fn emit_u8(&mut self, v: u8) { self.emit_float(v as float); }
107
108 fn emit_int(&mut self, v: int) { self.emit_float(v as float); }
109 fn emit_i64(&mut self, v: i64) { self.emit_float(v as float); }
110 fn emit_i32(&mut self, v: i32) { self.emit_float(v as float); }
111 fn emit_i16(&mut self, v: i16) { self.emit_float(v as float); }
112 fn emit_i8(&mut self, v: i8) { self.emit_float(v as float); }
113
114 fn emit_bool(&mut self, v: bool) {
115 if v {
116 self.wr.write_str("true");
117 } else {
118 self.wr.write_str("false");
119 }
120 }
121
122 fn emit_f64(&mut self, v: f64) { self.emit_float(v as float); }
123 fn emit_f32(&mut self, v: f32) { self.emit_float(v as float); }
124 fn emit_float(&mut self, v: float) {
125 self.wr.write_str(float::to_str_digits(v, 6u));
126 }
127
128 fn emit_char(&mut self, v: char) { self.emit_str(str::from_char(v)) }
129 fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)) }
130
131 fn emit_enum(&mut self, _name: &str, f: &fn(&mut Encoder)) { f(self) }
132
133 fn emit_enum_variant(&mut self,
134 name: &str,
135 _id: uint,
136 cnt: uint,
137 f: &fn(&mut Encoder)) {
138 // enums are encoded as strings or objects
139 // Bunny => "Bunny"
140 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
141 if cnt == 0 {
142 self.wr.write_str(escape_str(name));
143 } else {
144 self.wr.write_char('{');
145 self.wr.write_str("\"variant\"");
146 self.wr.write_char(':');
147 self.wr.write_str(escape_str(name));
148 self.wr.write_char(',');
149 self.wr.write_str("\"fields\"");
150 self.wr.write_str(":[");
151 f(self);
152 self.wr.write_str("]}");
153 }
154 }
155
156 fn emit_enum_variant_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
157 if idx != 0 {
158 self.wr.write_char(',');
159 }
160 f(self);
161 }
162
163 fn emit_enum_struct_variant(&mut self,
164 name: &str,
165 id: uint,
166 cnt: uint,
167 f: &fn(&mut Encoder)) {
168 self.emit_enum_variant(name, id, cnt, f)
169 }
170
171 fn emit_enum_struct_variant_field(&mut self,
172 _: &str,
173 idx: uint,
174 f: &fn(&mut Encoder)) {
175 self.emit_enum_variant_arg(idx, f)
176 }
177
178 fn emit_struct(&mut self, _: &str, _: uint, f: &fn(&mut Encoder)) {
179 self.wr.write_char('{');
180 f(self);
181 self.wr.write_char('}');
182 }
183
184 fn emit_struct_field(&mut self,
185 name: &str,
186 idx: uint,
187 f: &fn(&mut Encoder)) {
188 if idx != 0 { self.wr.write_char(','); }
189 self.wr.write_str(escape_str(name));
190 self.wr.write_char(':');
191 f(self);
192 }
193
194 fn emit_tuple(&mut self, len: uint, f: &fn(&mut Encoder)) {
195 self.emit_seq(len, f)
196 }
197 fn emit_tuple_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
198 self.emit_seq_elt(idx, f)
199 }
200
201 fn emit_tuple_struct(&mut self,
202 _name: &str,
203 len: uint,
204 f: &fn(&mut Encoder)) {
205 self.emit_seq(len, f)
206 }
207 fn emit_tuple_struct_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
208 self.emit_seq_elt(idx, f)
209 }
210
211 fn emit_option(&mut self, f: &fn(&mut Encoder)) { f(self); }
212 fn emit_option_none(&mut self) { self.emit_nil(); }
213 fn emit_option_some(&mut self, f: &fn(&mut Encoder)) { f(self); }
214
215 fn emit_seq(&mut self, _len: uint, f: &fn(&mut Encoder)) {
216 self.wr.write_char('[');
217 f(self);
218 self.wr.write_char(']');
219 }
220
221 fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut Encoder)) {
222 if idx != 0 {
223 self.wr.write_char(',');
224 }
225 f(self)
226 }
227
228 fn emit_map(&mut self, _len: uint, f: &fn(&mut Encoder)) {
229 self.wr.write_char('{');
230 f(self);
231 self.wr.write_char('}');
232 }
233
234 fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut Encoder)) {
235 if idx != 0 { self.wr.write_char(','); }
236 f(self)
237 }
238
239 fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut Encoder)) {
240 self.wr.write_char(':');
241 f(self)
242 }
243 }
244
245 /// Another encoder for JSON, but prints out human-readable JSON instead of
246 /// compact data
247 pub struct PrettyEncoder {
248 priv wr: @io::Writer,
249 priv indent: uint,
250 }
251
252 /// Creates a new encoder whose output will be written to the specified writer
253 pub fn PrettyEncoder(wr: @io::Writer) -> PrettyEncoder {
254 PrettyEncoder {
255 wr: wr,
256 indent: 0,
257 }
258 }
259
260 impl serialize::Encoder for PrettyEncoder {
261 fn emit_nil(&mut self) { self.wr.write_str("null") }
262
263 fn emit_uint(&mut self, v: uint) { self.emit_float(v as float); }
264 fn emit_u64(&mut self, v: u64) { self.emit_float(v as float); }
265 fn emit_u32(&mut self, v: u32) { self.emit_float(v as float); }
266 fn emit_u16(&mut self, v: u16) { self.emit_float(v as float); }
267 fn emit_u8(&mut self, v: u8) { self.emit_float(v as float); }
268
269 fn emit_int(&mut self, v: int) { self.emit_float(v as float); }
270 fn emit_i64(&mut self, v: i64) { self.emit_float(v as float); }
271 fn emit_i32(&mut self, v: i32) { self.emit_float(v as float); }
272 fn emit_i16(&mut self, v: i16) { self.emit_float(v as float); }
273 fn emit_i8(&mut self, v: i8) { self.emit_float(v as float); }
274
275 fn emit_bool(&mut self, v: bool) {
276 if v {
277 self.wr.write_str("true");
278 } else {
279 self.wr.write_str("false");
280 }
281 }
282
283 fn emit_f64(&mut self, v: f64) { self.emit_float(v as float); }
284 fn emit_f32(&mut self, v: f32) { self.emit_float(v as float); }
285 fn emit_float(&mut self, v: float) {
286 self.wr.write_str(float::to_str_digits(v, 6u));
287 }
288
289 fn emit_char(&mut self, v: char) { self.emit_str(str::from_char(v)) }
290 fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)); }
291
292 fn emit_enum(&mut self, _name: &str, f: &fn(&mut PrettyEncoder)) {
293 f(self)
294 }
295
296 fn emit_enum_variant(&mut self,
297 name: &str,
298 _: uint,
299 cnt: uint,
300 f: &fn(&mut PrettyEncoder)) {
301 if cnt == 0 {
302 self.wr.write_str(escape_str(name));
303 } else {
304 self.wr.write_char('[');
305 self.indent += 2;
306 self.wr.write_char('\n');
307 self.wr.write_str(spaces(self.indent));
308 self.wr.write_str(escape_str(name));
309 self.wr.write_str(",\n");
310 f(self);
311 self.wr.write_char('\n');
312 self.indent -= 2;
313 self.wr.write_str(spaces(self.indent));
314 self.wr.write_char(']');
315 }
316 }
317
318 fn emit_enum_variant_arg(&mut self,
319 idx: uint,
320 f: &fn(&mut PrettyEncoder)) {
321 if idx != 0 {
322 self.wr.write_str(",\n");
323 }
324 self.wr.write_str(spaces(self.indent));
325 f(self)
326 }
327
328 fn emit_enum_struct_variant(&mut self,
329 name: &str,
330 id: uint,
331 cnt: uint,
332 f: &fn(&mut PrettyEncoder)) {
333 self.emit_enum_variant(name, id, cnt, f)
334 }
335
336 fn emit_enum_struct_variant_field(&mut self,
337 _: &str,
338 idx: uint,
339 f: &fn(&mut PrettyEncoder)) {
340 self.emit_enum_variant_arg(idx, f)
341 }
342
343
344 fn emit_struct(&mut self,
345 _: &str,
346 len: uint,
347 f: &fn(&mut PrettyEncoder)) {
348 if len == 0 {
349 self.wr.write_str("{}");
350 } else {
351 self.wr.write_char('{');
352 self.indent += 2;
353 f(self);
354 self.wr.write_char('\n');
355 self.indent -= 2;
356 self.wr.write_str(spaces(self.indent));
357 self.wr.write_char('}');
358 }
359 }
360
361 fn emit_struct_field(&mut self,
362 name: &str,
363 idx: uint,
364 f: &fn(&mut PrettyEncoder)) {
365 if idx == 0 {
366 self.wr.write_char('\n');
367 } else {
368 self.wr.write_str(",\n");
369 }
370 self.wr.write_str(spaces(self.indent));
371 self.wr.write_str(escape_str(name));
372 self.wr.write_str(": ");
373 f(self);
374 }
375
376 fn emit_tuple(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
377 self.emit_seq(len, f)
378 }
379 fn emit_tuple_arg(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
380 self.emit_seq_elt(idx, f)
381 }
382
383 fn emit_tuple_struct(&mut self,
384 _: &str,
385 len: uint,
386 f: &fn(&mut PrettyEncoder)) {
387 self.emit_seq(len, f)
388 }
389 fn emit_tuple_struct_arg(&mut self,
390 idx: uint,
391 f: &fn(&mut PrettyEncoder)) {
392 self.emit_seq_elt(idx, f)
393 }
394
395 fn emit_option(&mut self, f: &fn(&mut PrettyEncoder)) { f(self); }
396 fn emit_option_none(&mut self) { self.emit_nil(); }
397 fn emit_option_some(&mut self, f: &fn(&mut PrettyEncoder)) { f(self); }
398
399 fn emit_seq(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
400 if len == 0 {
401 self.wr.write_str("[]");
402 } else {
403 self.wr.write_char('[');
404 self.indent += 2;
405 f(self);
406 self.wr.write_char('\n');
407 self.indent -= 2;
408 self.wr.write_str(spaces(self.indent));
409 self.wr.write_char(']');
410 }
411 }
412
413 fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
414 if idx == 0 {
415 self.wr.write_char('\n');
416 } else {
417 self.wr.write_str(",\n");
418 }
419 self.wr.write_str(spaces(self.indent));
420 f(self)
421 }
422
423 fn emit_map(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
424 if len == 0 {
425 self.wr.write_str("{}");
426 } else {
427 self.wr.write_char('{');
428 self.indent += 2;
429 f(self);
430 self.wr.write_char('\n');
431 self.indent -= 2;
432 self.wr.write_str(spaces(self.indent));
433 self.wr.write_char('}');
434 }
435 }
436
437 fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
438 if idx == 0 {
439 self.wr.write_char('\n');
440 } else {
441 self.wr.write_str(",\n");
442 }
443 self.wr.write_str(spaces(self.indent));
444 f(self);
445 }
446
447 fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut PrettyEncoder)) {
448 self.wr.write_str(": ");
449 f(self);
450 }
451 }
452
453 impl<E: serialize::Encoder> serialize::Encodable<E> for Json {
454 fn encode(&self, e: &mut E) {
455 match *self {
456 Number(v) => v.encode(e),
457 String(ref v) => v.encode(e),
458 Boolean(v) => v.encode(e),
459 List(ref v) => v.encode(e),
460 Object(ref v) => v.encode(e),
461 Null => e.emit_nil(),
462 }
463 }
464 }
465
466 impl Json{
467 /// Encodes a json value into a io::writer. Uses a single line.
468 pub fn to_writer(&self, wr: @io::Writer) {
469 let mut encoder = Encoder(wr);
470 self.encode(&mut encoder)
471 }
472
473 /// Encodes a json value into a io::writer.
474 /// Pretty-prints in a more readable format.
475 pub fn to_pretty_writer(&self, wr: @io::Writer) {
476 let mut encoder = PrettyEncoder(wr);
477 self.encode(&mut encoder)
478 }
479
480 /// Encodes a json value into a string
481 pub fn to_pretty_str(&self) -> ~str {
482 io::with_str_writer(|wr| self.to_pretty_writer(wr))
483 }
484 }
485
486 pub struct Parser<T> {
487 priv rdr: ~T,
488 priv ch: char,
489 priv line: uint,
490 priv col: uint,
491 }
492
493 /// Decode a json value from an Iterator<char>
494 pub fn Parser<T : Iterator<char>>(rdr: ~T) -> Parser<T> {
495 let mut p = Parser {
496 rdr: rdr,
497 ch: '\x00',
498 line: 1,
499 col: 0,
500 };
501 p.bump();
502 p
503 }
504
505 impl<T: Iterator<char>> Parser<T> {
506 pub fn parse(&mut self) -> Result<Json, Error> {
507 match self.parse_value() {
508 Ok(value) => {
509 // Skip trailing whitespaces.
510 self.parse_whitespace();
511 // Make sure there is no trailing characters.
512 if self.eof() {
513 Ok(value)
514 } else {
515 self.error(~"trailing characters")
516 }
517 }
518 Err(e) => Err(e)
519 }
520 }
521 }
522
523 impl<T : Iterator<char>> Parser<T> {
524 // FIXME: #8971: unsound
525 fn eof(&self) -> bool { self.ch == unsafe { transmute(-1u32) } }
526
527 fn bump(&mut self) {
528 match self.rdr.next() {
529 Some(ch) => self.ch = ch,
530 None() => self.ch = unsafe { transmute(-1u32) }, // FIXME: #8971: unsound
531 }
532
533 if self.ch == '\n' {
534 self.line += 1u;
535 self.col = 1u;
536 } else {
537 self.col += 1u;
538 }
539 }
540
541 fn next_char(&mut self) -> char {
542 self.bump();
543 self.ch
544 }
545
546 fn error<T>(&self, msg: ~str) -> Result<T, Error> {
547 Err(Error { line: self.line, col: self.col, msg: @msg })
548 }
549
550 fn parse_value(&mut self) -> Result<Json, Error> {
551 self.parse_whitespace();
552
553 if self.eof() { return self.error(~"EOF while parsing value"); }
554
555 match self.ch {
556 'n' => self.parse_ident("ull", Null),
557 't' => self.parse_ident("rue", Boolean(true)),
558 'f' => self.parse_ident("alse", Boolean(false)),
559 '0' .. '9' | '-' => self.parse_number(),
560 '"' =>
561 match self.parse_str() {
562 Ok(s) => Ok(String(s)),
563 Err(e) => Err(e),
564 },
565 '[' => self.parse_list(),
566 '{' => self.parse_object(),
567 _ => self.error(~"invalid syntax")
568 }
569 }
570
571 fn parse_whitespace(&mut self) {
572 while self.ch == ' ' ||
573 self.ch == '\n' ||
574 self.ch == '\t' ||
575 self.ch == '\r' { self.bump(); }
576 }
577
578 fn parse_ident(&mut self, ident: &str, value: Json) -> Result<Json, Error> {
579 if ident.iter().all(|c| c == self.next_char()) {
580 self.bump();
581 Ok(value)
582 } else {
583 self.error(~"invalid syntax")
584 }
585 }
586
587 fn parse_number(&mut self) -> Result<Json, Error> {
588 let mut neg = 1f;
589
590 if self.ch == '-' {
591 self.bump();
592 neg = -1f;
593 }
594
595 let mut res = match self.parse_integer() {
596 Ok(res) => res,
597 Err(e) => return Err(e)
598 };
599
600 if self.ch == '.' {
601 match self.parse_decimal(res) {
602 Ok(r) => res = r,
603 Err(e) => return Err(e)
604 }
605 }
606
607 if self.ch == 'e' || self.ch == 'E' {
608 match self.parse_exponent(res) {
609 Ok(r) => res = r,
610 Err(e) => return Err(e)
611 }
612 }
613
614 Ok(Number(neg * res))
615 }
616
617 fn parse_integer(&mut self) -> Result<float, Error> {
618 let mut res = 0f;
619
620 match self.ch {
621 '0' => {
622 self.bump();
623
624 // There can be only one leading '0'.
625 match self.ch {
626 '0' .. '9' => return self.error(~"invalid number"),
627 _ => ()
628 }
629 }
630 '1' .. '9' => {
631 while !self.eof() {
632 match self.ch {
633 '0' .. '9' => {
634 res *= 10f;
635 res += ((self.ch as int) - ('0' as int)) as float;
636
637 self.bump();
638 }
639 _ => break
640 }
641 }
642 }
643 _ => return self.error(~"invalid number")
644 }
645
646 Ok(res)
647 }
648
649 fn parse_decimal(&mut self, res: float) -> Result<float, Error> {
650 self.bump();
651
652 // Make sure a digit follows the decimal place.
653 match self.ch {
654 '0' .. '9' => (),
655 _ => return self.error(~"invalid number")
656 }
657
658 let mut res = res;
659 let mut dec = 1f;
660 while !self.eof() {
661 match self.ch {
662 '0' .. '9' => {
663 dec /= 10f;
664 res += (((self.ch as int) - ('0' as int)) as float) * dec;
665
666 self.bump();
667 }
668 _ => break
669 }
670 }
671
672 Ok(res)
673 }
674
675 fn parse_exponent(&mut self, mut res: float) -> Result<float, Error> {
676 self.bump();
677
678 let mut exp = 0u;
679 let mut neg_exp = false;
680
681 match self.ch {
682 '+' => self.bump(),
683 '-' => { self.bump(); neg_exp = true; }
684 _ => ()
685 }
686
687 // Make sure a digit follows the exponent place.
688 match self.ch {
689 '0' .. '9' => (),
690 _ => return self.error(~"invalid number")
691 }
692
693 while !self.eof() {
694 match self.ch {
695 '0' .. '9' => {
696 exp *= 10u;
697 exp += (self.ch as uint) - ('0' as uint);
698
699 self.bump();
700 }
701 _ => break
702 }
703 }
704
705 let exp = float::pow_with_uint(10u, exp);
706 if neg_exp {
707 res /= exp;
708 } else {
709 res *= exp;
710 }
711
712 Ok(res)
713 }
714
715 fn parse_str(&mut self) -> Result<~str, Error> {
716 let mut escape = false;
717 let mut res = ~"";
718
719 loop {
720 self.bump();
721 if self.eof() {
722 return self.error(~"EOF while parsing string");
723 }
724
725 if (escape) {
726 match self.ch {
727 '"' => res.push_char('"'),
728 '\\' => res.push_char('\\'),
729 '/' => res.push_char('/'),
730 'b' => res.push_char('\x08'),
731 'f' => res.push_char('\x0c'),
732 'n' => res.push_char('\n'),
733 'r' => res.push_char('\r'),
734 't' => res.push_char('\t'),
735 'u' => {
736 // Parse \u1234.
737 let mut i = 0u;
738 let mut n = 0u;
739 while i < 4u {
740 match self.next_char() {
741 '0' .. '9' => {
742 n = n * 16u + (self.ch as uint)
743 - ('0' as uint);
744 },
745 'a' | 'A' => n = n * 16u + 10u,
746 'b' | 'B' => n = n * 16u + 11u,
747 'c' | 'C' => n = n * 16u + 12u,
748 'd' | 'D' => n = n * 16u + 13u,
749 'e' | 'E' => n = n * 16u + 14u,
750 'f' | 'F' => n = n * 16u + 15u,
751 _ => return self.error(
752 ~"invalid \\u escape (unrecognized hex)")
753 }
754 i += 1u;
755 }
756
757 // Error out if we didn't parse 4 digits.
758 if i != 4u {
759 return self.error(
760 ~"invalid \\u escape (not four digits)");
761 }
762
763 res.push_char(char::from_u32(n as u32).unwrap());
764 }
765 _ => return self.error(~"invalid escape")
766 }
767 escape = false;
768 } else if self.ch == '\\' {
769 escape = true;
770 } else {
771 if self.ch == '"' {
772 self.bump();
773 return Ok(res);
774 }
775 res.push_char(self.ch);
776 }
777 }
778 }
779
780 fn parse_list(&mut self) -> Result<Json, Error> {
781 self.bump();
782 self.parse_whitespace();
783
784 let mut values = ~[];
785
786 if self.ch == ']' {
787 self.bump();
788 return Ok(List(values));
789 }
790
791 loop {
792 match self.parse_value() {
793 Ok(v) => values.push(v),
794 Err(e) => return Err(e)
795 }
796
797 self.parse_whitespace();
798 if self.eof() {
799 return self.error(~"EOF while parsing list");
800 }
801
802 match self.ch {
803 ',' => self.bump(),
804 ']' => { self.bump(); return Ok(List(values)); }
805 _ => return self.error(~"expected `,` or `]`")
806 }
807 };
808 }
809
810 fn parse_object(&mut self) -> Result<Json, Error> {
811 self.bump();
812 self.parse_whitespace();
813
814 let mut values = ~TreeMap::new();
815
816 if self.ch == '}' {
817 self.bump();
818 return Ok(Object(values));
819 }
820
821 while !self.eof() {
822 self.parse_whitespace();
823
824 if self.ch != '"' {
825 return self.error(~"key must be a string");
826 }
827
828 let key = match self.parse_str() {
829 Ok(key) => key,
830 Err(e) => return Err(e)
831 };
832
833 self.parse_whitespace();
834
835 if self.ch != ':' {
836 if self.eof() { break; }
837 return self.error(~"expected `:`");
838 }
839 self.bump();
840
841 match self.parse_value() {
842 Ok(value) => { values.insert(key, value); }
843 Err(e) => return Err(e)
844 }
845 self.parse_whitespace();
846
847 match self.ch {
848 ',' => self.bump(),
849 '}' => { self.bump(); return Ok(Object(values)); }
850 _ => {
851 if self.eof() { break; }
852 return self.error(~"expected `,` or `}`");
853 }
854 }
855 }
856
857 return self.error(~"EOF while parsing object");
858 }
859 }
860
861 /// Decodes a json value from an @io::Reader
862 pub fn from_reader(rdr: @io::Reader) -> Result<Json, Error> {
863 let s = str::from_utf8(rdr.read_whole_stream());
864 let mut parser = Parser(~s.iter());
865 parser.parse()
866 }
867
868 /// Decodes a json value from a string
869 pub fn from_str(s: &str) -> Result<Json, Error> {
870 let mut parser = Parser(~s.iter());
871 parser.parse()
872 }
873
874 /// A structure to decode JSON to values in rust.
875 pub struct Decoder {
876 priv stack: ~[Json],
877 }
878
879 /// Creates a new decoder instance for decoding the specified JSON value.
880 pub fn Decoder(json: Json) -> Decoder {
881 Decoder {
882 stack: ~[json]
883 }
884 }
885
886 impl serialize::Decoder for Decoder {
887 fn read_nil(&mut self) -> () {
888 debug!("read_nil");
889 match self.stack.pop() {
890 Null => (),
891 value => fail!("not a null: %?", value)
892 }
893 }
894
895 fn read_u64(&mut self) -> u64 { self.read_float() as u64 }
896 fn read_u32(&mut self) -> u32 { self.read_float() as u32 }
897 fn read_u16(&mut self) -> u16 { self.read_float() as u16 }
898 fn read_u8 (&mut self) -> u8 { self.read_float() as u8 }
899 fn read_uint(&mut self) -> uint { self.read_float() as uint }
900
901 fn read_i64(&mut self) -> i64 { self.read_float() as i64 }
902 fn read_i32(&mut self) -> i32 { self.read_float() as i32 }
903 fn read_i16(&mut self) -> i16 { self.read_float() as i16 }
904 fn read_i8 (&mut self) -> i8 { self.read_float() as i8 }
905 fn read_int(&mut self) -> int { self.read_float() as int }
906
907 fn read_bool(&mut self) -> bool {
908 debug!("read_bool");
909 match self.stack.pop() {
910 Boolean(b) => b,
911 value => fail!("not a boolean: %?", value)
912 }
913 }
914
915 fn read_f64(&mut self) -> f64 { self.read_float() as f64 }
916 fn read_f32(&mut self) -> f32 { self.read_float() as f32 }
917 fn read_float(&mut self) -> float {
918 debug!("read_float");
919 match self.stack.pop() {
920 Number(f) => f,
921 value => fail!("not a number: %?", value)
922 }
923 }
924
925 fn read_char(&mut self) -> char {
926 let mut v = ~[];
927 let s = self.read_str();
928 for c in s.iter() { v.push(c) }
929 if v.len() != 1 { fail!("string must have one character") }
930 v[0]
931 }
932
933 fn read_str(&mut self) -> ~str {
934 debug!("read_str");
935 match self.stack.pop() {
936 String(s) => s,
937 json => fail!("not a string: %?", json)
938 }
939 }
940
941 fn read_enum<T>(&mut self, name: &str, f: &fn(&mut Decoder) -> T) -> T {
942 debug!("read_enum(%s)", name);
943 f(self)
944 }
945
946 fn read_enum_variant<T>(&mut self,
947 names: &[&str],
948 f: &fn(&mut Decoder, uint) -> T)
949 -> T {
950 debug!("read_enum_variant(names=%?)", names);
951 let name = match self.stack.pop() {
952 String(s) => s,
953 Object(o) => {
954 let n = match o.find(&~"variant").expect("invalidly encoded json") {
955 &String(ref s) => s.clone(),
956 _ => fail!("invalidly encoded json"),
957 };
958 match o.find(&~"fields").expect("invalidly encoded json") {
959 &List(ref l) => {
960 for field in l.rev_iter() {
961 self.stack.push(field.clone());
962 }
963 },
964 _ => fail!("invalidly encoded json")
965 }
966 n
967 }
968 ref json => fail!("invalid variant: %?", *json),
969 };
970 let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
971 Some(idx) => idx,
972 None => fail!("Unknown variant name: %?", name),
973 };
974 f(self, idx)
975 }
976
977 fn read_enum_variant_arg<T>(&mut self,
978 idx: uint,
979 f: &fn(&mut Decoder) -> T)
980 -> T {
981 debug!("read_enum_variant_arg(idx=%u)", idx);
982 f(self)
983 }
984
985 fn read_enum_struct_variant<T>(&mut self,
986 names: &[&str],
987 f: &fn(&mut Decoder, uint) -> T)
988 -> T {
989 debug!("read_enum_struct_variant(names=%?)", names);
990 self.read_enum_variant(names, f)
991 }
992
993
994 fn read_enum_struct_variant_field<T>(&mut self,
995 name: &str,
996 idx: uint,
997 f: &fn(&mut Decoder) -> T)
998 -> T {
999 debug!("read_enum_struct_variant_field(name=%?, idx=%u)", name, idx);
1000 self.read_enum_variant_arg(idx, f)
1001 }
1002
1003 fn read_struct<T>(&mut self,
1004 name: &str,
1005 len: uint,
1006 f: &fn(&mut Decoder) -> T)
1007 -> T {
1008 debug!("read_struct(name=%s, len=%u)", name, len);
1009 let value = f(self);
1010 self.stack.pop();
1011 value
1012 }
1013
1014 fn read_struct_field<T>(&mut self,
1015 name: &str,
1016 idx: uint,
1017 f: &fn(&mut Decoder) -> T)
1018 -> T {
1019 debug!("read_struct_field(name=%?, idx=%u)", name, idx);
1020 match self.stack.pop() {
1021 Object(obj) => {
1022 let mut obj = obj;
1023 let value = match obj.pop(&name.to_owned()) {
1024 None => fail!("no such field: %s", name),
1025 Some(json) => {
1026 self.stack.push(json);
1027 f(self)
1028 }
1029 };
1030 self.stack.push(Object(obj));
1031 value
1032 }
1033 value => fail!("not an object: %?", value)
1034 }
1035 }
1036
1037 fn read_tuple<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
1038 debug!("read_tuple()");
1039 self.read_seq(f)
1040 }
1041
1042 fn read_tuple_arg<T>(&mut self,
1043 idx: uint,
1044 f: &fn(&mut Decoder) -> T)
1045 -> T {
1046 debug!("read_tuple_arg(idx=%u)", idx);
1047 self.read_seq_elt(idx, f)
1048 }
1049
1050 fn read_tuple_struct<T>(&mut self,
1051 name: &str,
1052 f: &fn(&mut Decoder, uint) -> T)
1053 -> T {
1054 debug!("read_tuple_struct(name=%?)", name);
1055 self.read_tuple(f)
1056 }
1057
1058 fn read_tuple_struct_arg<T>(&mut self,
1059 idx: uint,
1060 f: &fn(&mut Decoder) -> T)
1061 -> T {
1062 debug!("read_tuple_struct_arg(idx=%u)", idx);
1063 self.read_tuple_arg(idx, f)
1064 }
1065
1066 fn read_option<T>(&mut self, f: &fn(&mut Decoder, bool) -> T) -> T {
1067 match self.stack.pop() {
1068 Null => f(self, false),
1069 value => { self.stack.push(value); f(self, true) }
1070 }
1071 }
1072
1073 fn read_seq<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
1074 debug!("read_seq()");
1075 let len = match self.stack.pop() {
1076 List(list) => {
1077 let len = list.len();
1078 for v in list.move_rev_iter() {
1079 self.stack.push(v);
1080 }
1081 len
1082 }
1083 _ => fail!("not a list"),
1084 };
1085 f(self, len)
1086 }
1087
1088 fn read_seq_elt<T>(&mut self, idx: uint, f: &fn(&mut Decoder) -> T) -> T {
1089 debug!("read_seq_elt(idx=%u)", idx);
1090 f(self)
1091 }
1092
1093 fn read_map<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
1094 debug!("read_map()");
1095 let len = match self.stack.pop() {
1096 Object(obj) => {
1097 let len = obj.len();
1098 for (key, value) in obj.move_iter() {
1099 self.stack.push(value);
1100 self.stack.push(String(key));
1101 }
1102 len
1103 }
1104 json => fail!("not an object: %?", json),
1105 };
1106 f(self, len)
1107 }
1108
1109 fn read_map_elt_key<T>(&mut self,
1110 idx: uint,
1111 f: &fn(&mut Decoder) -> T)
1112 -> T {
1113 debug!("read_map_elt_key(idx=%u)", idx);
1114 f(self)
1115 }
1116
1117 fn read_map_elt_val<T>(&mut self, idx: uint, f: &fn(&mut Decoder) -> T)
1118 -> T {
1119 debug!("read_map_elt_val(idx=%u)", idx);
1120 f(self)
1121 }
1122 }
1123
1124 /// Test if two json values are less than one another
1125 impl Ord for Json {
1126 fn lt(&self, other: &Json) -> bool {
1127 match (*self) {
1128 Number(f0) => {
1129 match *other {
1130 Number(f1) => f0 < f1,
1131 String(_) | Boolean(_) | List(_) | Object(_) |
1132 Null => true
1133 }
1134 }
1135
1136 String(ref s0) => {
1137 match *other {
1138 Number(_) => false,
1139 String(ref s1) => s0 < s1,
1140 Boolean(_) | List(_) | Object(_) | Null => true
1141 }
1142 }
1143
1144 Boolean(b0) => {
1145 match *other {
1146 Number(_) | String(_) => false,
1147 Boolean(b1) => b0 < b1,
1148 List(_) | Object(_) | Null => true
1149 }
1150 }
1151
1152 List(ref l0) => {
1153 match *other {
1154 Number(_) | String(_) | Boolean(_) => false,
1155 List(ref l1) => (*l0) < (*l1),
1156 Object(_) | Null => true
1157 }
1158 }
1159
1160 Object(ref d0) => {
1161 match *other {
1162 Number(_) | String(_) | Boolean(_) | List(_) => false,
1163 Object(ref d1) => d0 < d1,
1164 Null => true
1165 }
1166 }
1167
1168 Null => {
1169 match *other {
1170 Number(_) | String(_) | Boolean(_) | List(_) |
1171 Object(_) =>
1172 false,
1173 Null => true
1174 }
1175 }
1176 }
1177 }
1178 }
1179
1180 /// A trait for converting values to JSON
1181 pub trait ToJson {
1182 /// Converts the value of `self` to an instance of JSON
1183 fn to_json(&self) -> Json;
1184 }
1185
1186 impl ToJson for Json {
1187 fn to_json(&self) -> Json { (*self).clone() }
1188 }
1189
1190 impl ToJson for @Json {
1191 fn to_json(&self) -> Json { (**self).to_json() }
1192 }
1193
1194 impl ToJson for int {
1195 fn to_json(&self) -> Json { Number(*self as float) }
1196 }
1197
1198 impl ToJson for i8 {
1199 fn to_json(&self) -> Json { Number(*self as float) }
1200 }
1201
1202 impl ToJson for i16 {
1203 fn to_json(&self) -> Json { Number(*self as float) }
1204 }
1205
1206 impl ToJson for i32 {
1207 fn to_json(&self) -> Json { Number(*self as float) }
1208 }
1209
1210 impl ToJson for i64 {
1211 fn to_json(&self) -> Json { Number(*self as float) }
1212 }
1213
1214 impl ToJson for uint {
1215 fn to_json(&self) -> Json { Number(*self as float) }
1216 }
1217
1218 impl ToJson for u8 {
1219 fn to_json(&self) -> Json { Number(*self as float) }
1220 }
1221
1222 impl ToJson for u16 {
1223 fn to_json(&self) -> Json { Number(*self as float) }
1224 }
1225
1226 impl ToJson for u32 {
1227 fn to_json(&self) -> Json { Number(*self as float) }
1228 }
1229
1230 impl ToJson for u64 {
1231 fn to_json(&self) -> Json { Number(*self as float) }
1232 }
1233
1234 impl ToJson for float {
1235 fn to_json(&self) -> Json { Number(*self) }
1236 }
1237
1238 impl ToJson for f32 {
1239 fn to_json(&self) -> Json { Number(*self as float) }
1240 }
1241
1242 impl ToJson for f64 {
1243 fn to_json(&self) -> Json { Number(*self as float) }
1244 }
1245
1246 impl ToJson for () {
1247 fn to_json(&self) -> Json { Null }
1248 }
1249
1250 impl ToJson for bool {
1251 fn to_json(&self) -> Json { Boolean(*self) }
1252 }
1253
1254 impl ToJson for ~str {
1255 fn to_json(&self) -> Json { String((*self).clone()) }
1256 }
1257
1258 impl ToJson for @~str {
1259 fn to_json(&self) -> Json { String((**self).clone()) }
1260 }
1261
1262 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1263 fn to_json(&self) -> Json {
1264 match *self {
1265 (ref a, ref b) => {
1266 List(~[a.to_json(), b.to_json()])
1267 }
1268 }
1269 }
1270 }
1271
1272 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1273 fn to_json(&self) -> Json {
1274 match *self {
1275 (ref a, ref b, ref c) => {
1276 List(~[a.to_json(), b.to_json(), c.to_json()])
1277 }
1278 }
1279 }
1280 }
1281
1282 impl<A:ToJson> ToJson for ~[A] {
1283 fn to_json(&self) -> Json { List(self.map(|elt| elt.to_json())) }
1284 }
1285
1286 impl<A:ToJson> ToJson for TreeMap<~str, A> {
1287 fn to_json(&self) -> Json {
1288 let mut d = TreeMap::new();
1289 for (key, value) in self.iter() {
1290 d.insert((*key).clone(), value.to_json());
1291 }
1292 Object(~d)
1293 }
1294 }
1295
1296 impl<A:ToJson> ToJson for HashMap<~str, A> {
1297 fn to_json(&self) -> Json {
1298 let mut d = TreeMap::new();
1299 for (key, value) in self.iter() {
1300 d.insert((*key).clone(), value.to_json());
1301 }
1302 Object(~d)
1303 }
1304 }
1305
1306 impl<A:ToJson> ToJson for Option<A> {
1307 fn to_json(&self) -> Json {
1308 match *self {
1309 None => Null,
1310 Some(ref value) => value.to_json()
1311 }
1312 }
1313 }
1314
1315 impl to_str::ToStr for Json {
1316 /// Encodes a json value into a string
1317 fn to_str(&self) -> ~str {
1318 io::with_str_writer(|wr| self.to_writer(wr))
1319 }
1320 }
1321
1322 impl to_str::ToStr for Error {
1323 fn to_str(&self) -> ~str {
1324 fmt!("%u:%u: %s", self.line, self.col, *self.msg)
1325 }
1326 }
1327
1328 #[cfg(test)]
1329 mod tests {
1330
1331 use super::*;
1332
1333 use std::io;
1334
1335 use serialize::Decodable;
1336 use treemap::TreeMap;
1337
1338 #[deriving(Eq, Encodable, Decodable)]
1339 enum Animal {
1340 Dog,
1341 Frog(~str, int)
1342 }
1343
1344 #[deriving(Eq, Encodable, Decodable)]
1345 struct Inner {
1346 a: (),
1347 b: uint,
1348 c: ~[~str],
1349 }
1350
1351 #[deriving(Eq, Encodable, Decodable)]
1352 struct Outer {
1353 inner: ~[Inner],
1354 }
1355
1356 fn mk_object(items: &[(~str, Json)]) -> Json {
1357 let mut d = ~TreeMap::new();
1358
1359 for item in items.iter() {
1360 match *item {
1361 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1362 }
1363 };
1364
1365 Object(d)
1366 }
1367
1368 #[test]
1369 fn test_write_null() {
1370 assert_eq!(Null.to_str(), ~"null");
1371 assert_eq!(Null.to_pretty_str(), ~"null");
1372 }
1373
1374
1375 #[test]
1376 fn test_write_number() {
1377 assert_eq!(Number(3f).to_str(), ~"3");
1378 assert_eq!(Number(3f).to_pretty_str(), ~"3");
1379
1380 assert_eq!(Number(3.1f).to_str(), ~"3.1");
1381 assert_eq!(Number(3.1f).to_pretty_str(), ~"3.1");
1382
1383 assert_eq!(Number(-1.5f).to_str(), ~"-1.5");
1384 assert_eq!(Number(-1.5f).to_pretty_str(), ~"-1.5");
1385
1386 assert_eq!(Number(0.5f).to_str(), ~"0.5");
1387 assert_eq!(Number(0.5f).to_pretty_str(), ~"0.5");
1388 }
1389
1390 #[test]
1391 fn test_write_str() {
1392 assert_eq!(String(~"").to_str(), ~"\"\"");
1393 assert_eq!(String(~"").to_pretty_str(), ~"\"\"");
1394
1395 assert_eq!(String(~"foo").to_str(), ~"\"foo\"");
1396 assert_eq!(String(~"foo").to_pretty_str(), ~"\"foo\"");
1397 }
1398
1399 #[test]
1400 fn test_write_bool() {
1401 assert_eq!(Boolean(true).to_str(), ~"true");
1402 assert_eq!(Boolean(true).to_pretty_str(), ~"true");
1403
1404 assert_eq!(Boolean(false).to_str(), ~"false");
1405 assert_eq!(Boolean(false).to_pretty_str(), ~"false");
1406 }
1407
1408 #[test]
1409 fn test_write_list() {
1410 assert_eq!(List(~[]).to_str(), ~"[]");
1411 assert_eq!(List(~[]).to_pretty_str(), ~"[]");
1412
1413 assert_eq!(List(~[Boolean(true)]).to_str(), ~"[true]");
1414 assert_eq!(
1415 List(~[Boolean(true)]).to_pretty_str(),
1416 ~"\
1417 [\n \
1418 true\n\
1419 ]"
1420 );
1421
1422 let longTestList = List(~[
1423 Boolean(false),
1424 Null,
1425 List(~[String(~"foo\nbar"), Number(3.5f)])]);
1426
1427 assert_eq!(longTestList.to_str(),
1428 ~"[false,null,[\"foo\\nbar\",3.5]]");
1429 assert_eq!(
1430 longTestList.to_pretty_str(),
1431 ~"\
1432 [\n \
1433 false,\n \
1434 null,\n \
1435 [\n \
1436 \"foo\\nbar\",\n \
1437 3.5\n \
1438 ]\n\
1439 ]"
1440 );
1441 }
1442
1443 #[test]
1444 fn test_write_object() {
1445 assert_eq!(mk_object([]).to_str(), ~"{}");
1446 assert_eq!(mk_object([]).to_pretty_str(), ~"{}");
1447
1448 assert_eq!(
1449 mk_object([(~"a", Boolean(true))]).to_str(),
1450 ~"{\"a\":true}"
1451 );
1452 assert_eq!(
1453 mk_object([(~"a", Boolean(true))]).to_pretty_str(),
1454 ~"\
1455 {\n \
1456 \"a\": true\n\
1457 }"
1458 );
1459
1460 let complexObj = mk_object([
1461 (~"b", List(~[
1462 mk_object([(~"c", String(~"\x0c\r"))]),
1463 mk_object([(~"d", String(~""))])
1464 ]))
1465 ]);
1466
1467 assert_eq!(
1468 complexObj.to_str(),
1469 ~"{\
1470 \"b\":[\
1471 {\"c\":\"\\f\\r\"},\
1472 {\"d\":\"\"}\
1473 ]\
1474 }"
1475 );
1476 assert_eq!(
1477 complexObj.to_pretty_str(),
1478 ~"\
1479 {\n \
1480 \"b\": [\n \
1481 {\n \
1482 \"c\": \"\\f\\r\"\n \
1483 },\n \
1484 {\n \
1485 \"d\": \"\"\n \
1486 }\n \
1487 ]\n\
1488 }"
1489 );
1490
1491 let a = mk_object([
1492 (~"a", Boolean(true)),
1493 (~"b", List(~[
1494 mk_object([(~"c", String(~"\x0c\r"))]),
1495 mk_object([(~"d", String(~""))])
1496 ]))
1497 ]);
1498
1499 // We can't compare the strings directly because the object fields be
1500 // printed in a different order.
1501 assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
1502 assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1503 }
1504
1505 #[test]
1506 fn test_write_enum() {
1507 let animal = Dog;
1508 assert_eq!(
1509 do io::with_str_writer |wr| {
1510 let mut encoder = Encoder(wr);
1511 animal.encode(&mut encoder);
1512 },
1513 ~"\"Dog\""
1514 );
1515 assert_eq!(
1516 do io::with_str_writer |wr| {
1517 let mut encoder = PrettyEncoder(wr);
1518 animal.encode(&mut encoder);
1519 },
1520 ~"\"Dog\""
1521 );
1522
1523 let animal = Frog(~"Henry", 349);
1524 assert_eq!(
1525 do io::with_str_writer |wr| {
1526 let mut encoder = Encoder(wr);
1527 animal.encode(&mut encoder);
1528 },
1529 ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
1530 );
1531 assert_eq!(
1532 do io::with_str_writer |wr| {
1533 let mut encoder = PrettyEncoder(wr);
1534 animal.encode(&mut encoder);
1535 },
1536 ~"\
1537 [\n \
1538 \"Frog\",\n \
1539 \"Henry\",\n \
1540 349\n\
1541 ]"
1542 );
1543 }
1544
1545 #[test]
1546 fn test_write_some() {
1547 let value = Some(~"jodhpurs");
1548 let s = do io::with_str_writer |wr| {
1549 let mut encoder = Encoder(wr);
1550 value.encode(&mut encoder);
1551 };
1552 assert_eq!(s, ~"\"jodhpurs\"");
1553
1554 let value = Some(~"jodhpurs");
1555 let s = do io::with_str_writer |wr| {
1556 let mut encoder = PrettyEncoder(wr);
1557 value.encode(&mut encoder);
1558 };
1559 assert_eq!(s, ~"\"jodhpurs\"");
1560 }
1561
1562 #[test]
1563 fn test_write_none() {
1564 let value: Option<~str> = None;
1565 let s = do io::with_str_writer |wr| {
1566 let mut encoder = Encoder(wr);
1567 value.encode(&mut encoder);
1568 };
1569 assert_eq!(s, ~"null");
1570
1571 let s = do io::with_str_writer |wr| {
1572 let mut encoder = Encoder(wr);
1573 value.encode(&mut encoder);
1574 };
1575 assert_eq!(s, ~"null");
1576 }
1577
1578 #[test]
1579 fn test_trailing_characters() {
1580 assert_eq!(from_str("nulla"),
1581 Err(Error {line: 1u, col: 5u, msg: @~"trailing characters"}));
1582 assert_eq!(from_str("truea"),
1583 Err(Error {line: 1u, col: 5u, msg: @~"trailing characters"}));
1584 assert_eq!(from_str("falsea"),
1585 Err(Error {line: 1u, col: 6u, msg: @~"trailing characters"}));
1586 assert_eq!(from_str("1a"),
1587 Err(Error {line: 1u, col: 2u, msg: @~"trailing characters"}));
1588 assert_eq!(from_str("[]a"),
1589 Err(Error {line: 1u, col: 3u, msg: @~"trailing characters"}));
1590 assert_eq!(from_str("{}a"),
1591 Err(Error {line: 1u, col: 3u, msg: @~"trailing characters"}));
1592 }
1593
1594 #[test]
1595 fn test_read_identifiers() {
1596 assert_eq!(from_str("n"),
1597 Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"}));
1598 assert_eq!(from_str("nul"),
1599 Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"}));
1600
1601 assert_eq!(from_str("t"),
1602 Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"}));
1603 assert_eq!(from_str("truz"),
1604 Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"}));
1605
1606 assert_eq!(from_str("f"),
1607 Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"}));
1608 assert_eq!(from_str("faz"),
1609 Err(Error {line: 1u, col: 3u, msg: @~"invalid syntax"}));
1610
1611 assert_eq!(from_str("null"), Ok(Null));
1612 assert_eq!(from_str("true"), Ok(Boolean(true)));
1613 assert_eq!(from_str("false"), Ok(Boolean(false)));
1614 assert_eq!(from_str(" null "), Ok(Null));
1615 assert_eq!(from_str(" true "), Ok(Boolean(true)));
1616 assert_eq!(from_str(" false "), Ok(Boolean(false)));
1617 }
1618
1619 #[test]
1620 fn test_decode_identifiers() {
1621 let mut decoder = Decoder(from_str("null").unwrap());
1622 let v: () = Decodable::decode(&mut decoder);
1623 assert_eq!(v, ());
1624
1625 let mut decoder = Decoder(from_str("true").unwrap());
1626 let v: bool = Decodable::decode(&mut decoder);
1627 assert_eq!(v, true);
1628
1629 let mut decoder = Decoder(from_str("false").unwrap());
1630 let v: bool = Decodable::decode(&mut decoder);
1631 assert_eq!(v, false);
1632 }
1633
1634 #[test]
1635 fn test_read_number() {
1636 assert_eq!(from_str("+"),
1637 Err(Error {line: 1u, col: 1u, msg: @~"invalid syntax"}));
1638 assert_eq!(from_str("."),
1639 Err(Error {line: 1u, col: 1u, msg: @~"invalid syntax"}));
1640
1641 assert_eq!(from_str("-"),
1642 Err(Error {line: 1u, col: 2u, msg: @~"invalid number"}));
1643 assert_eq!(from_str("00"),
1644 Err(Error {line: 1u, col: 2u, msg: @~"invalid number"}));
1645 assert_eq!(from_str("1."),
1646 Err(Error {line: 1u, col: 3u, msg: @~"invalid number"}));
1647 assert_eq!(from_str("1e"),
1648 Err(Error {line: 1u, col: 3u, msg: @~"invalid number"}));
1649 assert_eq!(from_str("1e+"),
1650 Err(Error {line: 1u, col: 4u, msg: @~"invalid number"}));
1651
1652 assert_eq!(from_str("3"), Ok(Number(3f)));
1653 assert_eq!(from_str("3.1"), Ok(Number(3.1f)));
1654 assert_eq!(from_str("-1.2"), Ok(Number(-1.2f)));
1655 assert_eq!(from_str("0.4"), Ok(Number(0.4f)));
1656 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5f)));
1657 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15f)));
1658 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01f)));
1659 assert_eq!(from_str(" 3 "), Ok(Number(3f)));
1660 }
1661
1662 #[test]
1663 fn test_decode_numbers() {
1664 let mut decoder = Decoder(from_str("3").unwrap());
1665 let v: float = Decodable::decode(&mut decoder);
1666 assert_eq!(v, 3f);
1667
1668 let mut decoder = Decoder(from_str("3.1").unwrap());
1669 let v: float = Decodable::decode(&mut decoder);
1670 assert_eq!(v, 3.1f);
1671
1672 let mut decoder = Decoder(from_str("-1.2").unwrap());
1673 let v: float = Decodable::decode(&mut decoder);
1674 assert_eq!(v, -1.2f);
1675
1676 let mut decoder = Decoder(from_str("0.4").unwrap());
1677 let v: float = Decodable::decode(&mut decoder);
1678 assert_eq!(v, 0.4f);
1679
1680 let mut decoder = Decoder(from_str("0.4e5").unwrap());
1681 let v: float = Decodable::decode(&mut decoder);
1682 assert_eq!(v, 0.4e5f);
1683
1684 let mut decoder = Decoder(from_str("0.4e15").unwrap());
1685 let v: float = Decodable::decode(&mut decoder);
1686 assert_eq!(v, 0.4e15f);
1687
1688 let mut decoder = Decoder(from_str("0.4e-01").unwrap());
1689 let v: float = Decodable::decode(&mut decoder);
1690 assert_eq!(v, 0.4e-01f);
1691 }
1692
1693 #[test]
1694 fn test_read_str() {
1695 assert_eq!(from_str("\""),
1696 Err(Error {line: 1u, col: 2u, msg: @~"EOF while parsing string"
1697 }));
1698 assert_eq!(from_str("\"lol"),
1699 Err(Error {line: 1u, col: 5u, msg: @~"EOF while parsing string"
1700 }));
1701
1702 assert_eq!(from_str("\"\""), Ok(String(~"")));
1703 assert_eq!(from_str("\"foo\""), Ok(String(~"foo")));
1704 assert_eq!(from_str("\"\\\"\""), Ok(String(~"\"")));
1705 assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08")));
1706 assert_eq!(from_str("\"\\n\""), Ok(String(~"\n")));
1707 assert_eq!(from_str("\"\\r\""), Ok(String(~"\r")));
1708 assert_eq!(from_str("\"\\t\""), Ok(String(~"\t")));
1709 assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo")));
1710 assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab")));
1711 assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12")));
1712 }
1713
1714 #[test]
1715 fn test_decode_str() {
1716 let mut decoder = Decoder(from_str("\"\"").unwrap());
1717 let v: ~str = Decodable::decode(&mut decoder);
1718 assert_eq!(v, ~"");
1719
1720 let mut decoder = Decoder(from_str("\"foo\"").unwrap());
1721 let v: ~str = Decodable::decode(&mut decoder);
1722 assert_eq!(v, ~"foo");
1723
1724 let mut decoder = Decoder(from_str("\"\\\"\"").unwrap());
1725 let v: ~str = Decodable::decode(&mut decoder);
1726 assert_eq!(v, ~"\"");
1727
1728 let mut decoder = Decoder(from_str("\"\\b\"").unwrap());
1729 let v: ~str = Decodable::decode(&mut decoder);
1730 assert_eq!(v, ~"\x08");
1731
1732 let mut decoder = Decoder(from_str("\"\\n\"").unwrap());
1733 let v: ~str = Decodable::decode(&mut decoder);
1734 assert_eq!(v, ~"\n");
1735
1736 let mut decoder = Decoder(from_str("\"\\r\"").unwrap());
1737 let v: ~str = Decodable::decode(&mut decoder);
1738 assert_eq!(v, ~"\r");
1739
1740 let mut decoder = Decoder(from_str("\"\\t\"").unwrap());
1741 let v: ~str = Decodable::decode(&mut decoder);
1742 assert_eq!(v, ~"\t");
1743
1744 let mut decoder = Decoder(from_str("\"\\u12ab\"").unwrap());
1745 let v: ~str = Decodable::decode(&mut decoder);
1746 assert_eq!(v, ~"\u12ab");
1747
1748 let mut decoder = Decoder(from_str("\"\\uAB12\"").unwrap());
1749 let v: ~str = Decodable::decode(&mut decoder);
1750 assert_eq!(v, ~"\uAB12");
1751 }
1752
1753 #[test]
1754 fn test_read_list() {
1755 assert_eq!(from_str("["),
1756 Err(Error {line: 1u, col: 2u, msg: @~"EOF while parsing value"}));
1757 assert_eq!(from_str("[1"),
1758 Err(Error {line: 1u, col: 3u, msg: @~"EOF while parsing list"}));
1759 assert_eq!(from_str("[1,"),
1760 Err(Error {line: 1u, col: 4u, msg: @~"EOF while parsing value"}));
1761 assert_eq!(from_str("[1,]"),
1762 Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"}));
1763 assert_eq!(from_str("[6 7]"),
1764 Err(Error {line: 1u, col: 4u, msg: @~"expected `,` or `]`"}));
1765
1766 assert_eq!(from_str("[]"), Ok(List(~[])));
1767 assert_eq!(from_str("[ ]"), Ok(List(~[])));
1768 assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
1769 assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
1770 assert_eq!(from_str("[null]"), Ok(List(~[Null])));
1771 assert_eq!(from_str("[3, 1]"),
1772 Ok(List(~[Number(3f), Number(1f)])));
1773 assert_eq!(from_str("\n[3, 2]\n"),
1774 Ok(List(~[Number(3f), Number(2f)])));
1775 assert_eq!(from_str("[2, [4, 1]]"),
1776 Ok(List(~[Number(2f), List(~[Number(4f), Number(1f)])])));
1777 }
1778
1779 #[test]
1780 fn test_decode_list() {
1781 let mut decoder = Decoder(from_str("[]").unwrap());
1782 let v: ~[()] = Decodable::decode(&mut decoder);
1783 assert_eq!(v, ~[]);
1784
1785 let mut decoder = Decoder(from_str("[null]").unwrap());
1786 let v: ~[()] = Decodable::decode(&mut decoder);
1787 assert_eq!(v, ~[()]);
1788
1789 let mut decoder = Decoder(from_str("[true]").unwrap());
1790 let v: ~[bool] = Decodable::decode(&mut decoder);
1791 assert_eq!(v, ~[true]);
1792
1793 let mut decoder = Decoder(from_str("[true]").unwrap());
1794 let v: ~[bool] = Decodable::decode(&mut decoder);
1795 assert_eq!(v, ~[true]);
1796
1797 let mut decoder = Decoder(from_str("[3, 1]").unwrap());
1798 let v: ~[int] = Decodable::decode(&mut decoder);
1799 assert_eq!(v, ~[3, 1]);
1800
1801 let mut decoder = Decoder(from_str("[[3], [1, 2]]").unwrap());
1802 let v: ~[~[uint]] = Decodable::decode(&mut decoder);
1803 assert_eq!(v, ~[~[3], ~[1, 2]]);
1804 }
1805
1806 #[test]
1807 fn test_read_object() {
1808 assert_eq!(from_str("{"),
1809 Err(Error {
1810 line: 1u,
1811 col: 2u,
1812 msg: @~"EOF while parsing object"}));
1813 assert_eq!(from_str("{ "),
1814 Err(Error {
1815 line: 1u,
1816 col: 3u,
1817 msg: @~"EOF while parsing object"}));
1818 assert_eq!(from_str("{1"),
1819 Err(Error {
1820 line: 1u,
1821 col: 2u,
1822 msg: @~"key must be a string"}));
1823 assert_eq!(from_str("{ \"a\""),
1824 Err(Error {
1825 line: 1u,
1826 col: 6u,
1827 msg: @~"EOF while parsing object"}));
1828 assert_eq!(from_str("{\"a\""),
1829 Err(Error {
1830 line: 1u,
1831 col: 5u,
1832 msg: @~"EOF while parsing object"}));
1833 assert_eq!(from_str("{\"a\" "),
1834 Err(Error {
1835 line: 1u,
1836 col: 6u,
1837 msg: @~"EOF while parsing object"}));
1838
1839 assert_eq!(from_str("{\"a\" 1"),
1840 Err(Error {line: 1u, col: 6u, msg: @~"expected `:`"}));
1841 assert_eq!(from_str("{\"a\":"),
1842 Err(Error {line: 1u, col: 6u, msg: @~"EOF while parsing value"}));
1843 assert_eq!(from_str("{\"a\":1"),
1844 Err(Error {
1845 line: 1u,
1846 col: 7u,
1847 msg: @~"EOF while parsing object"}));
1848 assert_eq!(from_str("{\"a\":1 1"),
1849 Err(Error {line: 1u, col: 8u, msg: @~"expected `,` or `}`"}));
1850 assert_eq!(from_str("{\"a\":1,"),
1851 Err(Error {
1852 line: 1u,
1853 col: 8u,
1854 msg: @~"EOF while parsing object"}));
1855
1856 assert_eq!(from_str("{}").unwrap(), mk_object([]));
1857 assert_eq!(from_str("{\"a\": 3}").unwrap(),
1858 mk_object([(~"a", Number(3.0f))]));
1859
1860 assert_eq!(from_str(
1861 "{ \"a\": null, \"b\" : true }").unwrap(),
1862 mk_object([
1863 (~"a", Null),
1864 (~"b", Boolean(true))]));
1865 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
1866 mk_object([
1867 (~"a", Null),
1868 (~"b", Boolean(true))]));
1869 assert_eq!(from_str(
1870 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
1871 mk_object([
1872 (~"a", Number(1.0)),
1873 (~"b", List(~[Boolean(true)]))
1874 ]));
1875 assert_eq!(from_str(
1876 ~"{" +
1877 "\"a\": 1.0, " +
1878 "\"b\": [" +
1879 "true," +
1880 "\"foo\\nbar\", " +
1881 "{ \"c\": {\"d\": null} } " +
1882 "]" +
1883 "}").unwrap(),
1884 mk_object([
1885 (~"a", Number(1.0f)),
1886 (~"b", List(~[
1887 Boolean(true),
1888 String(~"foo\nbar"),
1889 mk_object([
1890 (~"c", mk_object([(~"d", Null)]))
1891 ])
1892 ]))
1893 ]));
1894 }
1895
1896 #[test]
1897 fn test_decode_struct() {
1898 let s = ~"{
1899 \"inner\": [
1900 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
1901 ]
1902 }";
1903 let mut decoder = Decoder(from_str(s).unwrap());
1904 let v: Outer = Decodable::decode(&mut decoder);
1905 assert_eq!(
1906 v,
1907 Outer {
1908 inner: ~[
1909 Inner { a: (), b: 2, c: ~[~"abc", ~"xyz"] }
1910 ]
1911 }
1912 );
1913 }
1914
1915 #[test]
1916 fn test_decode_option() {
1917 let mut decoder = Decoder(from_str("null").unwrap());
1918 let value: Option<~str> = Decodable::decode(&mut decoder);
1919 assert_eq!(value, None);
1920
1921 let mut decoder = Decoder(from_str("\"jodhpurs\"").unwrap());
1922 let value: Option<~str> = Decodable::decode(&mut decoder);
1923 assert_eq!(value, Some(~"jodhpurs"));
1924 }
1925
1926 #[test]
1927 fn test_decode_enum() {
1928 let mut decoder = Decoder(from_str("\"Dog\"").unwrap());
1929 let value: Animal = Decodable::decode(&mut decoder);
1930 assert_eq!(value, Dog);
1931
1932 let mut decoder =
1933 Decoder(from_str("{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}").unwrap());
1934 let value: Animal = Decodable::decode(&mut decoder);
1935 assert_eq!(value, Frog(~"Henry", 349));
1936 }
1937
1938 #[test]
1939 fn test_decode_map() {
1940 let s = ~"{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\"fields\":[\"Henry\", 349]}}";
1941 let mut decoder = Decoder(from_str(s).unwrap());
1942 let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder);
1943
1944 assert_eq!(map.pop(&~"a"), Some(Dog));
1945 assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349)));
1946 }
1947
1948 #[test]
1949 fn test_multiline_errors() {
1950 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
1951 Err(Error {
1952 line: 3u,
1953 col: 8u,
1954 msg: @~"EOF while parsing object"}));
1955 }
1956 }
libextra/json.rs:42:1-42:1 -ty- definition:
pub type List = ~[Json];
references:-38: List(List),
libextra/json.rs:879:74-879:74 -fn- definition:
/// Creates a new decoder instance for decoding the specified JSON value.
pub fn Decoder(json: Json) -> Decoder {
references:-libextra/workcache.rs:
270: let mut decoder = json::Decoder(j);
193: let mut decoder = json::Decoder(r);
libextra/test.rs:
898: let mut decoder = json::Decoder(json::from_reader(f).unwrap());
libextra/flatpipes.rs:
478: json::Decoder(json)
libextra/json.rs:874:50-874:50 -struct- definition:
/// A structure to decode JSON to values in rust.
pub struct Decoder {
references:-1006: f: &fn(&mut Decoder) -> T)
1066: fn read_option<T>(&mut self, f: &fn(&mut Decoder, bool) -> T) -> T {
1037: fn read_tuple<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
979: f: &fn(&mut Decoder) -> T)
1017: f: &fn(&mut Decoder) -> T)
1117: fn read_map_elt_val<T>(&mut self, idx: uint, f: &fn(&mut Decoder) -> T)
1060: f: &fn(&mut Decoder) -> T)
1111: f: &fn(&mut Decoder) -> T)
1088: fn read_seq_elt<T>(&mut self, idx: uint, f: &fn(&mut Decoder) -> T) -> T {
1093: fn read_map<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
881: Decoder {
948: f: &fn(&mut Decoder, uint) -> T)
1052: f: &fn(&mut Decoder, uint) -> T)
1044: f: &fn(&mut Decoder) -> T)
987: f: &fn(&mut Decoder, uint) -> T)
997: f: &fn(&mut Decoder) -> T)
1073: fn read_seq<T>(&mut self, f: &fn(&mut Decoder, uint) -> T) -> T {
880: pub fn Decoder(json: Json) -> Decoder {
886: impl serialize::Decoder for Decoder {
941: fn read_enum<T>(&mut self, name: &str, f: &fn(&mut Decoder) -> T) -> T {
libextra/workcache.rs:
462: Decodable<json::Decoder>>
266: fn json_decode<T:Decodable<json::Decoder>>(s: &str) -> T {
410: Decodable<json::Decoder>>(
417: Decodable<json::Decoder>>( // FIXME(#5121)
libextra/flatpipes.rs:
475: fn from_reader(r: @Reader) -> json::Decoder {
474: impl FromReader for json::Decoder {
libextra/json.rs:246:17-246:17 -struct- definition:
/// compact data
pub struct PrettyEncoder {
references:-320: f: &fn(&mut PrettyEncoder)) {
253: pub fn PrettyEncoder(wr: @io::Writer) -> PrettyEncoder {
413: fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
397: fn emit_option_some(&mut self, f: &fn(&mut PrettyEncoder)) { f(self); }
399: fn emit_seq(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
395: fn emit_option(&mut self, f: &fn(&mut PrettyEncoder)) { f(self); }
347: f: &fn(&mut PrettyEncoder)) {
260: impl serialize::Encoder for PrettyEncoder {
339: f: &fn(&mut PrettyEncoder)) {
300: f: &fn(&mut PrettyEncoder)) {
364: f: &fn(&mut PrettyEncoder)) {
386: f: &fn(&mut PrettyEncoder)) {
391: f: &fn(&mut PrettyEncoder)) {
423: fn emit_map(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
447: fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut PrettyEncoder)) {
379: fn emit_tuple_arg(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
254: PrettyEncoder {
437: fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) {
376: fn emit_tuple(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) {
292: fn emit_enum(&mut self, _name: &str, f: &fn(&mut PrettyEncoder)) {
332: f: &fn(&mut PrettyEncoder)) {
libextra/json.rs:1180:42-1180:42 -trait- definition:
/// A trait for converting values to JSON
pub trait ToJson {
references:-1272: impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1286: impl<A:ToJson> ToJson for TreeMap<~str, A> {
1230: impl ToJson for u64 {
1206: impl ToJson for i32 {
1296: impl<A:ToJson> ToJson for HashMap<~str, A> {
1186: impl ToJson for Json {
1238: impl ToJson for f32 {
1282: impl<A:ToJson> ToJson for ~[A] {
1254: impl ToJson for ~str {
1286: impl<A:ToJson> ToJson for TreeMap<~str, A> {
1242: impl ToJson for f64 {
1222: impl ToJson for u16 {
1218: impl ToJson for u8 {
1282: impl<A:ToJson> ToJson for ~[A] {
1194: impl ToJson for int {
1210: impl ToJson for i64 {
1234: impl ToJson for float {
1198: impl ToJson for i8 {
1214: impl ToJson for uint {
1306: impl<A:ToJson> ToJson for Option<A> {
1246: impl ToJson for () {
1272: impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1306: impl<A:ToJson> ToJson for Option<A> {
1272: impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1262: impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1262: impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1258: impl ToJson for @~str {
1226: impl ToJson for u32 {
1202: impl ToJson for i16 {
1250: impl ToJson for bool {
(1272)(1190)(1262)(1296)libextra/test.rs:
(879)libextra/json.rs:493:47-493:47 -fn- definition:
/// Decode a json value from an Iterator<char>
pub fn Parser<T : Iterator<char>>(rdr: ~T) -> Parser<T> {
references:-870: let mut parser = Parser(~s.iter());
864: let mut parser = Parser(~s.iter());
libextra/json.rs:485:1-485:1 -struct- definition:
pub struct Parser<T> {
references:-495: let mut p = Parser {
505: impl<T: Iterator<char>> Parser<T> {
523: impl<T : Iterator<char>> Parser<T> {
494: pub fn Parser<T : Iterator<char>>(rdr: ~T) -> Parser<T> {
libextra/json.rs:92:15-92:15 -fn- definition:
/// specified.
pub fn Encoder(wr: @io::Writer) -> Encoder {
references:-469: let mut encoder = Encoder(wr);
libextra/workcache.rs:
260: let mut encoder = json::Encoder(wr);
libextra/flatpipes.rs:
487: json::Encoder(w)
libextra/json.rs:861:45-861:45 -fn- definition:
/// Decodes a json value from an @io::Reader
pub fn from_reader(rdr: @io::Reader) -> Result<Json, Error> {
references:-libextra/workcache.rs:
269: let j = json::from_reader(rdr).unwrap();
189: match json::from_reader(r) {
libextra/test.rs:
898: let mut decoder = json::Decoder(json::from_reader(f).unwrap());
libextra/flatpipes.rs:
476: match json::from_reader(r) {
libextra/json.rs:48:13-48:13 -struct- definition:
/// returned
pub struct Error {
references:-550: fn parse_value(&mut self) -> Result<Json, Error> {
547: Err(Error { line: self.line, col: self.col, msg: @msg })
46: #[deriving(Eq)]
578: fn parse_ident(&mut self, ident: &str, value: Json) -> Result<Json, Error> {
862: pub fn from_reader(rdr: @io::Reader) -> Result<Json, Error> {
1322: impl to_str::ToStr for Error {
675: fn parse_exponent(&mut self, mut res: float) -> Result<float, Error> {
780: fn parse_list(&mut self) -> Result<Json, Error> {
617: fn parse_integer(&mut self) -> Result<float, Error> {
869: pub fn from_str(s: &str) -> Result<Json, Error> {
506: pub fn parse(&mut self) -> Result<Json, Error> {
46: #[deriving(Eq)]
810: fn parse_object(&mut self) -> Result<Json, Error> {
715: fn parse_str(&mut self) -> Result<~str, Error> {
649: fn parse_decimal(&mut self, res: float) -> Result<float, Error> {
587: fn parse_number(&mut self) -> Result<Json, Error> {
546: fn error<T>(&self, msg: ~str) -> Result<T, Error> {
46: #[deriving(Eq)]
46: #[deriving(Eq)]
46: #[deriving(Eq)]
46: #[deriving(Eq)]
46: #[deriving(Eq)]
libextra/json.rs:57:1-57:1 -fn- definition:
fn escape_str(s: &str) -> ~str {
references:-142: self.wr.write_str(escape_str(name));
129: fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)) }
290: fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)); }
302: self.wr.write_str(escape_str(name));
371: self.wr.write_str(escape_str(name));
147: self.wr.write_str(escape_str(name));
308: self.wr.write_str(escape_str(name));
189: self.wr.write_str(escape_str(name));
libextra/json.rs:33:23-33:23 -enum- definition:
#[deriving(Clone, Eq)]
pub enum Json {
references:-33: #[deriving(Clone, Eq)]
1223: fn to_json(&self) -> Json { Number(*self as float) }
1243: fn to_json(&self) -> Json { Number(*self as float) }
1126: fn lt(&self, other: &Json) -> bool {
466: impl Json{
1247: fn to_json(&self) -> Json { Null }
1191: fn to_json(&self) -> Json { (**self).to_json() }
1235: fn to_json(&self) -> Json { Number(*self) }
550: fn parse_value(&mut self) -> Result<Json, Error> {
578: fn parse_ident(&mut self, ident: &str, value: Json) -> Result<Json, Error> {
1195: fn to_json(&self) -> Json { Number(*self as float) }
780: fn parse_list(&mut self) -> Result<Json, Error> {
1239: fn to_json(&self) -> Json { Number(*self as float) }
1297: fn to_json(&self) -> Json {
1183: fn to_json(&self) -> Json;
810: fn parse_object(&mut self) -> Result<Json, Error> {
506: pub fn parse(&mut self) -> Result<Json, Error> {
1207: fn to_json(&self) -> Json { Number(*self as float) }
1315: impl to_str::ToStr for Json {
1199: fn to_json(&self) -> Json { Number(*self as float) }
587: fn parse_number(&mut self) -> Result<Json, Error> {
578: fn parse_ident(&mut self, ident: &str, value: Json) -> Result<Json, Error> {
33: #[deriving(Clone, Eq)]
1125: impl Ord for Json {
33: #[deriving(Clone, Eq)]
33: #[deriving(Clone, Eq)]
1190: impl ToJson for @Json {
1186: impl ToJson for Json {
1259: fn to_json(&self) -> Json { String((**self).clone()) }
1219: fn to_json(&self) -> Json { Number(*self as float) }
(1215)(43)(33)(880)(876)(1273)(44)(1255)(869)(1287)(1263)(1231)(1283)(1187)(1211)(1227)(453)(1307)(1251)(1203)(862)libextra/test.rs:
(880)libextra/json.rs:252:79-252:79 -fn- definition:
/// Creates a new encoder whose output will be written to the specified writer
pub fn PrettyEncoder(wr: @io::Writer) -> PrettyEncoder {
references:-476: let mut encoder = PrettyEncoder(wr);
libextra/json.rs:86:56-86:56 -struct- definition:
/// A structure for implementing serialization to JSON.
pub struct Encoder {
references:-215: fn emit_seq(&mut self, _len: uint, f: &fn(&mut Encoder)) {
194: fn emit_tuple(&mut self, len: uint, f: &fn(&mut Encoder)) {
178: fn emit_struct(&mut self, _: &str, _: uint, f: &fn(&mut Encoder)) {
239: fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut Encoder)) {
94: Encoder {
99: impl serialize::Encoder for Encoder {
137: f: &fn(&mut Encoder)) {
187: f: &fn(&mut Encoder)) {
221: fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut Encoder)) {
156: fn emit_enum_variant_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
131: fn emit_enum(&mut self, _name: &str, f: &fn(&mut Encoder)) { f(self) }
234: fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut Encoder)) {
213: fn emit_option_some(&mut self, f: &fn(&mut Encoder)) { f(self); }
167: f: &fn(&mut Encoder)) {
197: fn emit_tuple_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
207: fn emit_tuple_struct_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) {
211: fn emit_option(&mut self, f: &fn(&mut Encoder)) { f(self); }
204: f: &fn(&mut Encoder)) {
174: f: &fn(&mut Encoder)) {
228: fn emit_map(&mut self, _len: uint, f: &fn(&mut Encoder)) {
93: pub fn Encoder(wr: @io::Writer) -> Encoder {
libextra/workcache.rs:
275: fn digest<T:Encodable<json::Encoder>>(t: &T) -> ~str {
416: Encodable<json::Encoder> +
258: fn json_encode<T:Encodable<json::Encoder>>(t: &T) -> ~str {
461: Encodable<json::Encoder> +
409: Encodable<json::Encoder> +
libextra/flatpipes.rs:
485: impl FromWriter for json::Encoder {
486: fn from_writer(w: @Writer) -> json::Encoder {
libextra/json.rs:77:1-77:1 -fn- definition:
fn spaces(n: uint) -> ~str {
references:-443: self.wr.write_str(spaces(self.indent));
419: self.wr.write_str(spaces(self.indent));
370: self.wr.write_str(spaces(self.indent));
408: self.wr.write_str(spaces(self.indent));
313: self.wr.write_str(spaces(self.indent));
307: self.wr.write_str(spaces(self.indent));
432: self.wr.write_str(spaces(self.indent));
356: self.wr.write_str(spaces(self.indent));
324: self.wr.write_str(spaces(self.indent));
libextra/json.rs:43:25-43:25 -ty- definition:
pub type List = ~[Json];
pub type Object = TreeMap<~str, Json>;
references:-39: Object(~Object),
libextra/workcache.rs:
232: cfg: Arc<json::Object>,
298: cfg: Arc<json::Object>,
292: cfg: Arc<json::Object>) -> Context {