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