]> gitweb.factorcode.org Git - factor.git/blob - basis/formatting/formatting.factor
formatting: fix strftime %U and %W
[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
4 calendar.private combinators combinators.smart generalizations
5 io io.streams.string kernel math math.functions
6 math.functions.integer-logs math.parser multiline namespaces
7 peg.ebnf present prettyprint quotations sequences
8 sequences.generalizations splitting strings unicode ;
9 FROM: math.parser.private => format-float ;
10 IN: formatting
11
12 ERROR: unknown-format-directive value ;
13
14 <PRIVATE
15
16 : compose-all ( seq -- quot )
17     [ ] [ compose ] reduce ; inline
18
19 : fix-sign ( string -- string )
20     dup first CHAR: 0 = [
21         dup [ [ CHAR: 0 = not ] [ digit? ] bi and ] find
22         [
23             1 - swap 2dup nth {
24                 { CHAR: - [ remove-nth "-" prepend ] }
25                 { CHAR: + [ remove-nth "+" prepend ] }
26                 [ drop nip ]
27             } case
28         ] [ drop ] if
29     ] when ;
30
31 : >digits ( string -- digits )
32     [ 0 ] [ string>number ] if-empty ;
33
34 : format-decimal-simple ( x digits -- string )
35     [
36         [ abs ] dip
37         [ 10^ * round-to-even >integer number>string ]
38         [ 1 + CHAR: 0 pad-head ]
39         [ cut* ] tri [ "." glue ] unless-empty
40     ] keepd neg? [ CHAR: - prefix ] when ;
41
42 : format-scientific-mantissa ( x log10x digits -- string rounded-up? )
43     [ swap - 10^ * round-to-even >integer number>string ] keep
44     over length 1 - < [
45         [ but-last >string ] when ! 9.9 rounded to 1e+01
46         1 cut [ "." glue ] unless-empty
47     ] keep ;
48
49 : format-scientific-exponent ( rounded-up? log10x -- string )
50     swap [ 1 + ] when number>string 2 CHAR: 0 pad-head
51     dup CHAR: - swap index "e" "e+" ? prepend ;
52
53 : format-scientific-simple ( x digits -- string )
54     [
55         [ abs dup integer-log10 ] dip
56         [ format-scientific-mantissa ]
57         [ drop nip format-scientific-exponent ] 3bi append
58     ] keepd neg? [ CHAR: - prefix ] when ;
59
60 : format-float-fast ( x digits string -- string )
61     [ "" -1 ] 2dip "C" format-float ;
62
63 : format-fast-scientific? ( x digits -- x' digits ? )
64     over float? [ t ]
65     [ 2dup
66         [ [ t ] [ abs integer-log10 abs 308 < ] if-zero ]
67         [ 15 < ] bi* and
68         [ [ [ >float ] dip ] when ] keep
69     ] if ;
70
71 : format-scientific ( x digits -- string )
72     format-fast-scientific?  [
73         [ "e" format-float-fast ]
74         [ [ ".0e" "e" replace ] [ drop ] if-zero ] bi
75     ] [ format-scientific-simple ] if ;
76
77 : format-fast-decimal? ( x digits -- x' digits ? )
78     over float? [ t ]
79     [
80         2dup
81         [ drop dup integer?  [ abs 53 2^ < ] [ drop f ] if ]
82         [ over ratio?
83             [ [ abs integer-log10 ] dip
84               [ drop abs 308 < ] [ + 15 <= ] 2bi and ]
85             [ 2drop f ] if
86         ] 2bi or
87         [ [ [ >float ] dip ] when ] keep
88     ] if ; inline
89
90 : format-decimal ( x digits -- string )
91     format-fast-decimal? [
92         [ "f" format-float-fast ]
93         [ [ ".0" ?tail drop ] [ drop ] if-zero ] bi
94     ] [ format-decimal-simple ] if ;
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 '[ _ index-or-length 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"                  => [[ [ >integer number>string ] ]]
122 fmt-o     = "o"                  => [[ [ >integer >oct ] ]]
123 fmt-b     = "b"                  => [[ [ >integer >bin ] ]]
124 fmt-e     = digits "e"           => [[ first '[ _ format-scientific ] ]]
125 fmt-E     = digits "E"           => [[ first '[ _ format-scientific >upper ] ]]
126 fmt-f     = digits "f"           => [[ first '[ _ format-decimal ] ]]
127 fmt-x     = "x"                  => [[ [ >integer >hex ] ]]
128 fmt-X     = "X"                  => [[ [ >integer >hex >upper ] ]]
129 unknown   = (.)*                 => [[ "" like unknown-format-directive ]]
130
131 strings_  = fmt-c|fmt-C|fmt-s|fmt-S|fmt-u
132 strings   = pad width strings_   => [[ <reversed> compose-all ]]
133
134 numbers_  = fmt-d|fmt-o|fmt-b|fmt-e|fmt-E|fmt-f|fmt-x|fmt-X
135 numbers   = sign pad numbers_    => [[ unclip-last prefix compose-all [ fix-sign ] append ]]
136
137 types     = strings|numbers
138
139 lists     = "[%" types ", %]"    => [[ second '[ _ { } map-as ", " join "{ " " }" surround ] ]]
140
141 assocs    = "[%" types ": %" types " %]" => [[ [ second ] [ fourth ] bi '[ [ _ _ bi* ":" glue ] { } assoc>map ", " join "{ " " }" surround ] ]]
142
143 formats   = "%" (types|fmt-%|lists|assocs|unknown) => [[ second ]]
144
145 plain-text = [^%]+               => [[ >string ]]
146
147 text      = (formats|plain-text)*
148
149 ]=]
150
151 : printf-quot ( format-string -- format-quot n )
152     parse-printf [ [ callable? ] count ] keep [
153         dup string? [ 1quotation ] [ [ 1 - ] dip ] if
154         over [ ndip ] 2curry
155     ] map nip [ compose-all ] [ length ] bi ; inline
156
157 PRIVATE>
158
159 MACRO: printf ( format-string -- quot )
160     printf-quot '[
161         @ output-stream get [ stream-write ] curry _ napply
162     ] ;
163
164 MACRO: sprintf ( format-string -- quot )
165     printf-quot '[
166         @ _ "" nappend-as
167     ] ;
168
169 : vprintf ( seq format-string -- )
170     parse-printf output-stream get '[
171         dup string? [
172             [ unclip-slice ] dip call( x -- y )
173         ] unless _ stream-write
174     ] each drop ;
175
176 : vsprintf ( seq format-string -- result )
177     [ vprintf ] with-string-writer ; inline
178
179 <PRIVATE
180
181 : pad-00 ( n -- string )
182     number>string 2 CHAR: 0 pad-head ; inline
183
184 : pad-000 ( n -- string )
185     number>string 3 CHAR: 0 pad-head ; inline
186
187 : >time ( timestamp -- string )
188     [ hour>> ] [ minute>> ] [ second>> floor ] tri
189     [ pad-00 ] tri@ 3array ":" join ; inline
190
191 : >date ( timestamp -- string )
192     [ month>> ] [ day>> ] [ year>> ] tri
193     [ pad-00 ] tri@ 3array "/" join ; inline
194
195 : >datetime ( timestamp -- string )
196     [
197        {
198           [ day-of-week day-abbreviation3 ]
199           [ month>> month-abbreviation ]
200           [ day>> pad-00 ]
201           [ >time ]
202           [ year>> number>string ]
203        } cleave
204     ] output>array join-words ; inline
205
206 : week-of-year ( timestamp day -- n )
207     [ dup clone first-day-of-year dup clone ]
208     [ day-this-week ] bi* swap '[ _ time- duration>days ] bi@
209     dup 0 < [ 7 + - ] [ drop ] if 7 + 7 /i ;
210
211 : week-of-year-sunday ( timestamp -- n ) 0 week-of-year ; inline
212
213 : week-of-year-monday ( timestamp -- n ) 1 week-of-year ; inline
214
215 EBNF: parse-strftime [=[
216
217 fmt-%     = "%"                  => [[ "%" ]]
218 fmt-a     = "a"                  => [[ [ day-of-week day-abbreviation3 ] ]]
219 fmt-A     = "A"                  => [[ [ day-of-week day-name ] ]]
220 fmt-b     = "b"                  => [[ [ month>> month-abbreviation ] ]]
221 fmt-B     = "B"                  => [[ [ month>> month-name ] ]]
222 fmt-c     = "c"                  => [[ [ >datetime ] ]]
223 fmt-d     = "d"                  => [[ [ day>> pad-00 ] ]]
224 fmt-H     = "H"                  => [[ [ hour>> pad-00 ] ]]
225 fmt-I     = "I"                  => [[ [ hour>> dup 12 > [ 12 - ] when pad-00 ] ]]
226 fmt-j     = "j"                  => [[ [ day-of-year pad-000 ] ]]
227 fmt-m     = "m"                  => [[ [ month>> pad-00 ] ]]
228 fmt-M     = "M"                  => [[ [ minute>> pad-00 ] ]]
229 fmt-p     = "p"                  => [[ [ hour>> 12 < "AM" "PM" ? ] ]]
230 fmt-S     = "S"                  => [[ [ second>> floor pad-00 ] ]]
231 fmt-U     = "U"                  => [[ [ week-of-year-sunday pad-00 ] ]]
232 fmt-w     = "w"                  => [[ [ day-of-week number>string ] ]]
233 fmt-W     = "W"                  => [[ [ week-of-year-monday pad-00 ] ]]
234 fmt-x     = "x"                  => [[ [ >date ] ]]
235 fmt-X     = "X"                  => [[ [ >time ] ]]
236 fmt-y     = "y"                  => [[ [ year>> 100 mod pad-00 ] ]]
237 fmt-Y     = "Y"                  => [[ [ year>> number>string ] ]]
238 fmt-Z     = "Z"                  => [[ [ "Not yet implemented" throw ] ]]
239 unknown   = (.)*                 => [[ "" like unknown-format-directive ]]
240
241 formats_  = fmt-%|fmt-a|fmt-A|fmt-b|fmt-B|fmt-c|fmt-d|fmt-H|fmt-I|
242             fmt-j|fmt-m|fmt-M|fmt-p|fmt-S|fmt-U|fmt-w|fmt-W|fmt-x|
243             fmt-X|fmt-y|fmt-Y|fmt-Z|unknown
244
245 formats   = "%" (formats_)       => [[ second ]]
246
247 plain-text = [^%]+               => [[ >string ]]
248
249 text      = (formats|plain-text)*
250
251 ]=]
252
253 PRIVATE>
254
255 MACRO: strftime ( format-string -- quot )
256     parse-strftime [
257         dup string? [
258             '[ _ append! ]
259         ] [
260             '[ over @ append! ]
261         ] if
262     ] map concat '[ SBUF" " clone @ nip "" like ] ;