]> gitweb.factorcode.org Git - factor.git/blob - basis/formatting/formatting.factor
formatting: use nappend-as in sprintf.
[factor.git] / basis / formatting / formatting.factor
1 ! Copyright (C) 2008 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: accessors arrays assocs calendar combinators
4 combinators.smart fry generalizations io io.streams.string
5 kernel macros math math.functions math.parser namespaces
6 peg.ebnf present prettyprint quotations sequences
7 sequences.generalizations strings unicode.case
8 unicode.categories vectors ;
9 FROM: math.parser.private => format-float ;
10 IN: formatting
11
12 <PRIVATE
13
14 : compose-all ( seq -- quot )
15     [ ] [ compose ] reduce ; inline
16
17 : fix-sign ( string -- string )
18     dup first CHAR: 0 = [
19         dup [ [ CHAR: 0 = not ] [ digit? ] bi and ] find
20         [
21             1 - swap 2dup nth {
22                 { CHAR: - [ remove-nth "-" prepend ] }
23                 { CHAR: + [ remove-nth "+" prepend ] }
24                 [ drop nip ]
25             } case
26         ] [ drop ] if
27     ] when ;
28
29 : >digits ( string -- digits )
30     [ 0 ] [ string>number ] if-empty ;
31
32 : format-simple ( x digits string -- string )
33     [ [ >float ] [ number>string ] bi* "%." ] dip
34     surround format-float ;
35
36 : format-scientific ( x digits -- string ) "e" format-simple ;
37
38 : format-decimal ( x digits -- string ) "f" format-simple ;
39
40 ERROR: unknown-printf-directive ;
41
42 EBNF: parse-printf
43
44 zero      = "0"                  => [[ CHAR: 0 ]]
45 char      = "'" (.)              => [[ second ]]
46
47 pad-char  = (zero|char)?         => [[ CHAR: \s or ]]
48 pad-align = ("-")?               => [[ \ pad-tail \ pad-head ? ]]
49 pad-width = ([0-9])*             => [[ >digits ]]
50 pad       = pad-align pad-char pad-width => [[ <reversed> >quotation dup first 0 = [ drop [ ] ] when ]]
51
52 sign_     = [+ ]                 => [[ '[ dup CHAR: - swap index [ _ prefix ] unless ] ]]
53 sign      = (sign_)?             => [[ [ ] or ]]
54
55 width_    = "." ([0-9])*         => [[ second >digits '[ _ short head ] ]]
56 width     = (width_)?            => [[ [ ] or ]]
57
58 digits_   = "." ([0-9])*         => [[ second >digits ]]
59 digits    = (digits_)?           => [[ 6 or ]]
60
61 fmt-%     = "%"                  => [[ "%" ]]
62 fmt-c     = "c"                  => [[ [ 1string ] ]]
63 fmt-C     = "C"                  => [[ [ 1string >upper ] ]]
64 fmt-s     = "s"                  => [[ [ present ] ]]
65 fmt-S     = "S"                  => [[ [ present >upper ] ]]
66 fmt-u     = "u"                  => [[ [ unparse ] ]]
67 fmt-d     = "d"                  => [[ [ >integer number>string ] ]]
68 fmt-o     = "o"                  => [[ [ >integer >oct ] ]]
69 fmt-b     = "b"                  => [[ [ >integer >bin ] ]]
70 fmt-e     = digits "e"           => [[ first '[ _ format-scientific ] ]]
71 fmt-E     = digits "E"           => [[ first '[ _ format-scientific >upper ] ]]
72 fmt-f     = digits "f"           => [[ first '[ _ format-decimal ] ]]
73 fmt-x     = "x"                  => [[ [ >hex ] ]]
74 fmt-X     = "X"                  => [[ [ >hex >upper ] ]]
75 unknown   = (.)*                 => [[ unknown-printf-directive ]]
76
77 strings_  = fmt-c|fmt-C|fmt-s|fmt-S|fmt-u
78 strings   = pad width strings_   => [[ <reversed> compose-all ]]
79
80 numbers_  = fmt-d|fmt-o|fmt-b|fmt-e|fmt-E|fmt-f|fmt-x|fmt-X
81 numbers   = sign pad numbers_    => [[ unclip-last prefix compose-all [ fix-sign ] append ]]
82
83 types     = strings|numbers
84
85 lists     = "[%" types ", %]"    => [[ second '[ _ map ", " join "{ " prepend " }" append ] ]]
86
87 assocs    = "[%" types ": %" types " %]" => [[ [ second ] [ fourth ] bi '[ unzip [ _ map ] dip _ map zip [ ":" join ] map ", " join "{ " prepend " }" append ] ]]
88
89 formats   = "%" (types|fmt-%|lists|assocs|unknown) => [[ second ]]
90
91 plain-text = (!("%").)+          => [[ >string ]]
92
93 text      = (formats|plain-text)* => [[ ]]
94
95 ;EBNF
96
97 : printf-quot ( format-string -- format-quot n )
98     parse-printf [ [ callable? ] count ] keep [
99         dup string? [ 1quotation ] [ [ 1 - ] dip ] if
100         over [ ndip ] 2curry
101     ] map nip [ compose-all ] [ length ] bi ; inline
102
103 PRIVATE>
104
105 MACRO: printf ( format-string -- )
106     printf-quot '[
107         @ output-stream get [ stream-write ] curry _ napply
108     ] ;
109
110 MACRO: sprintf ( format-string -- result )
111     printf-quot '[
112         @ _ "" nappend-as
113     ] ;
114
115 : vprintf ( seq format-string -- )
116     parse-printf output-stream get '[
117         dup string? [
118             [ unclip-slice ] dip call( x -- y )
119         ] unless _ stream-write
120     ] each drop ;
121
122 : vsprintf ( seq format-string -- result )
123     [ vprintf ] with-string-writer ; inline
124
125 <PRIVATE
126
127 : pad-00 ( n -- string )
128     number>string 2 CHAR: 0 pad-head ; inline
129
130 : pad-000 ( n -- string )
131     number>string 3 CHAR: 0 pad-head ; inline
132
133 : >time ( timestamp -- string )
134     [ hour>> ] [ minute>> ] [ second>> floor ] tri
135     [ pad-00 ] tri@ 3array ":" join ; inline
136
137 : >date ( timestamp -- string )
138     [ month>> ] [ day>> ] [ year>> ] tri
139     [ pad-00 ] tri@ 3array "/" join ; inline
140
141 : >datetime ( timestamp -- string )
142     [
143        {
144           [ day-of-week day-abbreviation3 ]
145           [ month>> month-abbreviation ]
146           [ day>> pad-00 ]
147           [ >time ]
148           [ year>> number>string ]
149        } cleave
150     ] output>array " " join ; inline
151
152 : week-of-year ( timestamp day -- n )
153     [ dup clone 1 >>month 1 >>day day-of-week dup ] dip > [ 7 swap - ] when
154     [ day-of-year ] dip 2dup < [ 0 2nip ] [ - 7 / 1 + >fixnum ] if ;
155
156 : week-of-year-sunday ( timestamp -- n ) 0 week-of-year ; inline
157
158 : week-of-year-monday ( timestamp -- n ) 1 week-of-year ; inline
159
160 EBNF: parse-strftime
161
162 fmt-%     = "%"                  => [[ "%" ]]
163 fmt-a     = "a"                  => [[ [ day-of-week day-abbreviation3 ] ]]
164 fmt-A     = "A"                  => [[ [ day-of-week day-name ] ]]
165 fmt-b     = "b"                  => [[ [ month>> month-abbreviation ] ]]
166 fmt-B     = "B"                  => [[ [ month>> month-name ] ]]
167 fmt-c     = "c"                  => [[ [ >datetime ] ]]
168 fmt-d     = "d"                  => [[ [ day>> pad-00 ] ]]
169 fmt-H     = "H"                  => [[ [ hour>> pad-00 ] ]]
170 fmt-I     = "I"                  => [[ [ hour>> dup 12 > [ 12 - ] when pad-00 ] ]]
171 fmt-j     = "j"                  => [[ [ day-of-year pad-000 ] ]]
172 fmt-m     = "m"                  => [[ [ month>> pad-00 ] ]]
173 fmt-M     = "M"                  => [[ [ minute>> pad-00 ] ]]
174 fmt-p     = "p"                  => [[ [ hour>> 12 < "AM" "PM" ? ] ]]
175 fmt-S     = "S"                  => [[ [ second>> floor pad-00 ] ]]
176 fmt-U     = "U"                  => [[ [ week-of-year-sunday pad-00 ] ]]
177 fmt-w     = "w"                  => [[ [ day-of-week number>string ] ]]
178 fmt-W     = "W"                  => [[ [ week-of-year-monday pad-00 ] ]]
179 fmt-x     = "x"                  => [[ [ >date ] ]]
180 fmt-X     = "X"                  => [[ [ >time ] ]]
181 fmt-y     = "y"                  => [[ [ year>> 100 mod pad-00 ] ]]
182 fmt-Y     = "Y"                  => [[ [ year>> number>string ] ]]
183 fmt-Z     = "Z"                  => [[ [ "Not yet implemented" throw ] ]]
184 unknown   = (.)*                 => [[ "Unknown directive" throw ]]
185
186 formats_  = fmt-%|fmt-a|fmt-A|fmt-b|fmt-B|fmt-c|fmt-d|fmt-H|fmt-I|
187             fmt-j|fmt-m|fmt-M|fmt-p|fmt-S|fmt-U|fmt-w|fmt-W|fmt-x|
188             fmt-X|fmt-y|fmt-Y|fmt-Z|unknown
189
190 formats   = "%" (formats_)       => [[ second ]]
191
192 plain-text = (!("%").)+          => [[ >string ]]
193
194 text      = (formats|plain-text)* => [[ ]]
195
196 ;EBNF
197
198 PRIVATE>
199
200 MACRO: strftime ( format-string -- )
201     parse-strftime [
202         dup string? [
203             '[ _ swap push-all ]
204         ] [
205             '[ over @ swap push-all ]
206         ] if
207     ] map '[
208         SBUF" " clone [ _ cleave drop ] keep "" like
209     ] ;