factor/library/syntax/unparser.factor

102 lines
2.4 KiB
Factor
Raw Normal View History

2005-02-14 21:58:07 -05:00
! Copyright (C) 2004, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
2004-07-16 02:26:21 -04:00
IN: unparser
2005-04-03 16:55:56 -04:00
USING: alien generic kernel lists math memory namespaces parser
2005-04-02 02:39:33 -05:00
sequences sequences stdio strings words ;
2004-07-16 02:26:21 -04:00
2004-12-12 16:54:29 -05:00
GENERIC: unparse ( obj -- str )
M: object unparse ( obj -- str )
"( " swap class word-name " )" append3 ;
2004-12-12 16:54:29 -05:00
: >digit ( n -- ch )
dup 10 < [ CHAR: 0 + ] [ 10 - CHAR: a + ] ifte ;
: integer, ( num radix -- )
dup >r /mod >digit , dup 0 > [
r> integer,
] [
r> 2drop
2004-08-25 20:51:19 -04:00
] ifte ;
2004-07-16 02:26:21 -04:00
2004-08-04 03:12:55 -04:00
: >base ( num radix -- string )
#! Convert a number to a string in a certain base.
[
over 0 < [
swap neg swap integer, CHAR: - ,
] [
integer,
] ifte
] make-rstring ;
: >dec ( num -- string ) 10 >base ;
: >bin ( num -- string ) 2 >base ;
: >oct ( num -- string ) 8 >base ;
: >hex ( num -- string ) 16 >base ;
2004-08-04 03:12:55 -04:00
M: integer unparse ( obj -- str ) >dec ;
2004-08-23 18:46:46 -04:00
2004-12-12 16:54:29 -05:00
M: ratio unparse ( num -- str )
[
dup
numerator unparse %
CHAR: / ,
denominator unparse %
] make-string ;
2004-12-12 16:54:29 -05:00
: fix-float ( str -- str )
#! This is terrible. Will go away when we do our own float
#! output.
2005-07-16 22:16:18 -04:00
CHAR: . over member? [ ".0" append ] unless ;
2004-12-12 16:54:29 -05:00
M: float unparse ( float -- str )
(unparse-float) fix-float ;
M: complex unparse ( num -- str )
[
"#{ " %
dup
real unparse %
" " %
imaginary unparse %
" }#" %
] make-string ;
: ch>ascii-escape ( ch -- esc )
[
[[ CHAR: \e "\\e" ]]
[[ CHAR: \n "\\n" ]]
[[ CHAR: \r "\\r" ]]
[[ CHAR: \t "\\t" ]]
[[ CHAR: \0 "\\0" ]]
[[ CHAR: \\ "\\\\" ]]
[[ CHAR: \" "\\\"" ]]
] assoc ;
: ch>unicode-escape ( ch -- esc )
2005-06-15 23:27:28 -04:00
>hex 4 CHAR: 0 pad-left "\\u" swap append ;
: unparse-ch ( ch -- ch/str )
dup quotable? [
2005-03-21 14:39:46 -05:00
dup ch>ascii-escape [ ] [ ch>unicode-escape ] ?ifte
] unless ;
: unparse-string [ unparse-ch , ] each ;
2005-04-02 02:39:33 -05:00
2004-12-12 16:54:29 -05:00
M: string unparse ( str -- str )
2005-04-02 02:39:33 -05:00
[ CHAR: " , unparse-string CHAR: " , ] make-string ;
M: sbuf unparse ( str -- str )
[ "SBUF\" " % unparse-string CHAR: " , ] make-string ;
2004-07-16 02:26:21 -04:00
M: word unparse ( obj -- str ) word-name dup "( unnamed )" ? ;
2004-07-16 02:26:21 -04:00
2004-12-12 16:54:29 -05:00
M: t unparse drop "t" ;
M: f unparse drop "f" ;
2005-04-10 18:58:30 -04:00
M: dll unparse ( obj -- str )
[ "DLL\" " % dll-path unparse-string CHAR: " , ] make-string ;
: hex-string ( str -- str )
[ [ >hex 2 CHAR: 0 pad-left % ] each ] make-string ;