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