]> gitweb.factorcode.org Git - factor.git/blob - basis/formatting/formatting.factor
formatting, fix %f and %e for ratios and integers
[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 calendar.english 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 vectors
8 math.functions.integer-logs math.order ;
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-decimal-simple ( x digits -- string )
33     [
34         [ abs ] dip
35         [ 10^ * round-to-even >integer number>string ]
36         [ 1 + CHAR: 0 pad-head 2 CHAR: 0 pad-tail ]
37         [ 1 max cut* ] tri "." glue
38     ] curry keep neg? [ CHAR: - prefix ] when ;
39
40 : format-scientific-mantissa ( x log10x digits -- string )
41     swap - 10^ * round-to-even >integer
42     number>string 1 cut "." glue ;
43
44 : format-scientific-exponent ( log10x -- string )
45     number>string 2 CHAR: 0 pad-head
46     dup CHAR: - swap index "e" "e+" ? prepend ;
47
48 : format-scientific-simple ( x digits -- string )
49     [
50         [ abs dup integer-log10 ] dip
51         [ format-scientific-mantissa ]
52         [ drop nip format-scientific-exponent ] 3bi append
53     ] curry keep neg? [ CHAR: - prefix ] when ;
54
55 : format-float-fast ( x digits string -- string )
56     [ "" -1 ] 2dip "C" format-float ;
57
58 : format-fast-scientific? ( x digits -- x' digits ? )
59     over float? [ t ]
60     [ 2dup
61         [ abs integer-log10 abs 308 < ]
62         [ 15 < ] bi* and
63         [ [ [ >float ] dip ] when ] keep
64     ] if ;
65
66 : format-scientific ( x digits -- string )
67     format-fast-scientific?
68     [ "e" format-float-fast ]
69     [ format-scientific-simple ] if ;
70
71 : format-fast-decimal? ( x digits -- x' digits ? )
72     over float? [ t ]
73     [
74         2dup
75         [ drop dup integer?  [ abs 53 2^ < ] [ drop f ] if ]
76         [ over ratio?
77             [ [ abs integer-log10 ] dip
78               [ drop abs 308 < ] [ + 15 <= ] 2bi and ]
79             [ 2drop f ] if
80         ] 2bi or
81         [ [ [ >float ] dip ] when ] keep
82     ] if ; inline
83
84 : format-decimal ( x digits -- string )
85     format-fast-decimal?
86     [ "f" format-float-fast ]
87     [ format-decimal-simple ] if ;
88
89 ERROR: unknown-printf-directive ;
90
91 EBNF: parse-printf
92
93 zero      = "0"                  => [[ CHAR: 0 ]]
94 char      = "'" (.)              => [[ second ]]
95
96 pad-char  = (zero|char)?         => [[ CHAR: \s or ]]
97 pad-align = ("-")?               => [[ \ pad-tail \ pad-head ? ]]
98 pad-width = ([0-9])*             => [[ >digits ]]
99 pad       = pad-align pad-char pad-width => [[ <reversed> >quotation dup first 0 = [ drop [ ] ] when ]]
100
101 sign_     = [+ ]                 => [[ '[ dup first CHAR: - = [ _ prefix ] unless ] ]]
102 sign      = (sign_)?             => [[ [ ] or ]]
103
104 width_    = "." ([0-9])*         => [[ second >digits '[ _ short head ] ]]
105 width     = (width_)?            => [[ [ ] or ]]
106
107 digits_   = "." ([0-9])*         => [[ second >digits ]]
108 digits    = (digits_)?           => [[ 6 or ]]
109
110 fmt-%     = "%"                  => [[ "%" ]]
111 fmt-c     = "c"                  => [[ [ 1string ] ]]
112 fmt-C     = "C"                  => [[ [ 1string >upper ] ]]
113 fmt-s     = "s"                  => [[ [ present ] ]]
114 fmt-S     = "S"                  => [[ [ present >upper ] ]]
115 fmt-u     = "u"                  => [[ [ unparse ] ]]
116 fmt-d     = "d"                  => [[ [ >integer number>string ] ]]
117 fmt-o     = "o"                  => [[ [ >integer >oct ] ]]
118 fmt-b     = "b"                  => [[ [ >integer >bin ] ]]
119 fmt-e     = digits "e"           => [[ first '[ _ format-scientific ] ]]
120 fmt-E     = digits "E"           => [[ first '[ _ format-scientific >upper ] ]]
121 fmt-f     = digits "f"           => [[ first '[ _ format-decimal ] ]]
122 fmt-x     = "x"                  => [[ [ >hex ] ]]
123 fmt-X     = "X"                  => [[ [ >hex >upper ] ]]
124 unknown   = (.)*                 => [[ unknown-printf-directive ]]
125
126 strings_  = fmt-c|fmt-C|fmt-s|fmt-S|fmt-u
127 strings   = pad width strings_   => [[ <reversed> compose-all ]]
128
129 numbers_  = fmt-d|fmt-o|fmt-b|fmt-e|fmt-E|fmt-f|fmt-x|fmt-X
130 numbers   = sign pad numbers_    => [[ unclip-last prefix compose-all [ fix-sign ] append ]]
131
132 types     = strings|numbers
133
134 lists     = "[%" types ", %]"    => [[ second '[ _ map ", " join "{ " prepend " }" append ] ]]
135
136 assocs    = "[%" types ": %" types " %]" => [[ [ second ] [ fourth ] bi '[ unzip [ _ map ] dip _ map zip [ ":" join ] map ", " join "{ " prepend " }" append ] ]]
137
138 formats   = "%" (types|fmt-%|lists|assocs|unknown) => [[ second ]]
139
140 plain-text = (!("%").)+          => [[ >string ]]
141
142 text      = (formats|plain-text)* => [[ ]]
143
144 ;EBNF
145
146 : printf-quot ( format-string -- format-quot n )
147     parse-printf [ [ callable? ] count ] keep [
148         dup string? [ 1quotation ] [ [ 1 - ] dip ] if
149         over [ ndip ] 2curry
150     ] map nip [ compose-all ] [ length ] bi ; inline
151
152 PRIVATE>
153
154 MACRO: printf ( format-string -- quot )
155     printf-quot '[
156         @ output-stream get [ stream-write ] curry _ napply
157     ] ;
158
159 MACRO: sprintf ( format-string -- quot )
160     printf-quot '[
161         @ _ "" nappend-as
162     ] ;
163
164 : vprintf ( seq format-string -- )
165     parse-printf output-stream get '[
166         dup string? [
167             [ unclip-slice ] dip call( x -- y )
168         ] unless _ stream-write
169     ] each drop ;
170
171 : vsprintf ( seq format-string -- result )
172     [ vprintf ] with-string-writer ; inline
173
174 <PRIVATE
175
176 : pad-00 ( n -- string )
177     number>string 2 CHAR: 0 pad-head ; inline
178
179 : pad-000 ( n -- string )
180     number>string 3 CHAR: 0 pad-head ; inline
181
182 : >time ( timestamp -- string )
183     [ hour>> ] [ minute>> ] [ second>> floor ] tri
184     [ pad-00 ] tri@ 3array ":" join ; inline
185
186 : >date ( timestamp -- string )
187     [ month>> ] [ day>> ] [ year>> ] tri
188     [ pad-00 ] tri@ 3array "/" join ; inline
189
190 : >datetime ( timestamp -- string )
191     [
192        {
193           [ day-of-week day-abbreviation3 ]
194           [ month>> month-abbreviation ]
195           [ day>> pad-00 ]
196           [ >time ]
197           [ year>> number>string ]
198        } cleave
199     ] output>array " " join ; inline
200
201 : week-of-year ( timestamp day -- n )
202     [ dup clone 1 >>month 1 >>day day-of-week dup ] dip > [ 7 swap - ] when
203     [ day-of-year ] dip 2dup < [ 0 2nip ] [ - 7 / 1 + >fixnum ] if ;
204
205 : week-of-year-sunday ( timestamp -- n ) 0 week-of-year ; inline
206
207 : week-of-year-monday ( timestamp -- n ) 1 week-of-year ; inline
208
209 EBNF: parse-strftime
210
211 fmt-%     = "%"                  => [[ "%" ]]
212 fmt-a     = "a"                  => [[ [ day-of-week day-abbreviation3 ] ]]
213 fmt-A     = "A"                  => [[ [ day-of-week day-name ] ]]
214 fmt-b     = "b"                  => [[ [ month>> month-abbreviation ] ]]
215 fmt-B     = "B"                  => [[ [ month>> month-name ] ]]
216 fmt-c     = "c"                  => [[ [ >datetime ] ]]
217 fmt-d     = "d"                  => [[ [ day>> pad-00 ] ]]
218 fmt-H     = "H"                  => [[ [ hour>> pad-00 ] ]]
219 fmt-I     = "I"                  => [[ [ hour>> dup 12 > [ 12 - ] when pad-00 ] ]]
220 fmt-j     = "j"                  => [[ [ day-of-year pad-000 ] ]]
221 fmt-m     = "m"                  => [[ [ month>> pad-00 ] ]]
222 fmt-M     = "M"                  => [[ [ minute>> pad-00 ] ]]
223 fmt-p     = "p"                  => [[ [ hour>> 12 < "AM" "PM" ? ] ]]
224 fmt-S     = "S"                  => [[ [ second>> floor pad-00 ] ]]
225 fmt-U     = "U"                  => [[ [ week-of-year-sunday pad-00 ] ]]
226 fmt-w     = "w"                  => [[ [ day-of-week number>string ] ]]
227 fmt-W     = "W"                  => [[ [ week-of-year-monday pad-00 ] ]]
228 fmt-x     = "x"                  => [[ [ >date ] ]]
229 fmt-X     = "X"                  => [[ [ >time ] ]]
230 fmt-y     = "y"                  => [[ [ year>> 100 mod pad-00 ] ]]
231 fmt-Y     = "Y"                  => [[ [ year>> number>string ] ]]
232 fmt-Z     = "Z"                  => [[ [ "Not yet implemented" throw ] ]]
233 unknown   = (.)*                 => [[ "Unknown directive" throw ]]
234
235 formats_  = fmt-%|fmt-a|fmt-A|fmt-b|fmt-B|fmt-c|fmt-d|fmt-H|fmt-I|
236             fmt-j|fmt-m|fmt-M|fmt-p|fmt-S|fmt-U|fmt-w|fmt-W|fmt-x|
237             fmt-X|fmt-y|fmt-Y|fmt-Z|unknown
238
239 formats   = "%" (formats_)       => [[ second ]]
240
241 plain-text = (!("%").)+          => [[ >string ]]
242
243 text      = (formats|plain-text)* => [[ ]]
244
245 ;EBNF
246
247 PRIVATE>
248
249 MACRO: strftime ( format-string -- quot )
250     parse-strftime [
251         dup string? [
252             '[ _ swap push-all ]
253         ] [
254             '[ over @ swap push-all ]
255         ] if
256     ] map '[
257         SBUF" " clone [ _ cleave drop ] keep "" like
258     ] ;