factor/basis/json/reader/reader.factor

88 lines
2.3 KiB
Factor
Raw Normal View History

! Copyright (C) 2008 Peter Burns, 2009 Philipp Winkler
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: arrays assocs combinators fry hashtables io
io.streams.string json kernel make math math.parser namespaces
prettyprint sequences strings vectors ;
2007-09-20 18:09:08 -04:00
IN: json.reader
<PRIVATE
: value ( char -- num char )
1string " \t\r\n,:}]" read-until
[ append string>number ] dip ;
DEFER: j-string%
: j-escape% ( -- )
read1 {
{ CHAR: b [ 8 ] }
{ CHAR: f [ 12 ] }
{ CHAR: n [ CHAR: \n ] }
{ CHAR: r [ CHAR: \r ] }
{ CHAR: t [ CHAR: \t ] }
{ CHAR: u [ 4 read hex> ] }
[ ]
} case [ , j-string% ] when* ;
: j-string% ( -- )
"\\\"" read-until [ % ] dip
CHAR: \" = [ j-escape% ] unless ;
: j-string ( -- str )
"\\\"" read-until CHAR: \" =
[ [ % j-escape% ] "" make ] unless ;
: second-last ( seq -- second-last )
[ length 2 - ] [ nth ] bi ; inline
ERROR: json-error ;
2007-09-20 18:09:08 -04:00
: check-length ( seq n -- seq )
[ dup length ] [ >= ] bi* [ json-error ] unless ;
2007-09-20 18:09:08 -04:00
: v-over-push ( vec -- vec' )
2 check-length dup [ pop ] [ last ] bi push ;
2007-09-20 18:09:08 -04:00
: v-pick-push ( vec -- vec' )
3 check-length dup [ pop ] [ second-last ] bi push ;
: (close) ( accum -- accum' )
dup last V{ } = not [ v-over-push ] when ;
2007-09-20 18:09:08 -04:00
2009-06-06 23:49:44 -04:00
: (close-array) ( accum -- accum' )
2011-10-15 22:19:44 -04:00
(close) dup pop >array suffix! ;
2009-06-06 23:49:44 -04:00
: (close-hash) ( accum -- accum' )
2011-10-15 22:19:44 -04:00
(close) dup dup [ pop ] bi@ swap zip >hashtable suffix! ;
: scan ( accum char -- accum )
! 2dup 1string swap . . ! Great for debug...
{
2011-10-15 22:19:44 -04:00
{ CHAR: \" [ j-string suffix! ] }
{ CHAR: [ [ V{ } clone suffix! ] }
{ CHAR: , [ v-over-push ] }
{ CHAR: ] [ (close-array) ] }
2011-10-15 22:19:44 -04:00
{ CHAR: { [ 2 [ V{ } clone suffix! ] times ] }
{ CHAR: : [ v-pick-push ] }
{ CHAR: } [ (close-hash) ] }
{ CHAR: \s [ ] }
{ CHAR: \t [ ] }
{ CHAR: \r [ ] }
{ CHAR: \n [ ] }
2011-10-15 22:19:44 -04:00
{ CHAR: t [ 3 read drop t suffix! ] }
{ CHAR: f [ 4 read drop f suffix! ] }
{ CHAR: n [ 3 read drop json-null suffix! ] }
[ value [ suffix! ] dip [ scan ] when* ]
} case ;
2008-11-15 04:09:57 -05:00
PRIVATE>
: read-jsons ( -- objects )
V{ } clone input-stream get
'[ _ stream-read1 dup ] [ scan ] while drop ;
: json> ( string -- object )
[ read-jsons first ] with-string-reader ;