forked from dotnet/fsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintf.fs
More file actions
1389 lines (1206 loc) · 63.6 KB
/
Copy pathprintf.fs
File metadata and controls
1389 lines (1206 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.FSharp.Core
type PrintfFormat<'Printer,'State,'Residue,'Result>(value:string) =
member x.Value = value
type PrintfFormat<'Printer,'State,'Residue,'Result,'Tuple>(value:string) =
inherit PrintfFormat<'Printer,'State,'Residue,'Result>(value)
type Format<'Printer,'State,'Residue,'Result> = PrintfFormat<'Printer,'State,'Residue,'Result>
type Format<'Printer,'State,'Residue,'Result,'Tuple> = PrintfFormat<'Printer,'State,'Residue,'Result,'Tuple>
#if FX_RESHAPED_REFLECTION
open Microsoft.FSharp.Core.PrimReflectionAdapters
open Microsoft.FSharp.Core.ReflectionAdapters
#endif
module internal PrintfImpl =
/// Basic idea of implementation:
/// Every Printf.* family should returns curried function that collects arguments and then somehow prints them.
/// Idea - instead of building functions on fly argument by argument we instead introduce some predefined parts and then construct functions from these parts
/// Parts include:
/// Plain ones:
/// 1. Final pieces (1..5) - set of functions with arguments number 1..5.
/// Primary characteristic - these functions produce final result of the *printf* operation
/// 2. Chained pieces (1..5) - set of functions with arguments number 1..5.
/// Primary characteristic - these functions doesn not produce final result by itself, instead they tailed with some another piece (chained or final).
/// Plain parts correspond to simple format specifiers (that are projected to just one parameter of the function, say %d or %s). However we also have
/// format specifiers that can be projected to more than one argument (i.e %a, %t or any simple format specified with * width or precision).
/// For them we add special cases (both chained and final to denote that they can either return value themselves or continue with some other piece)
/// These primitives allow us to construct curried functions with arbitrary signatures.
/// For example:
/// - function that corresponds to %s%s%s%s%s (string -> string -> string -> string -> string -> T) will be represented by one piece final 5.
/// - function that has more that 5 arguments will include chained parts: %s%s%s%s%s%d%s => chained2 -> final 5
/// Primary benefits:
/// 1. creating specialized version of any part requires only one reflection call. This means that we can handle up to 5 simple format specifiers
/// with just one reflection call
/// 2. we can make combinable parts independent from particular printf implementation. Thus final result can be cached and shared.
/// i.e when first calll to printf "%s %s" will trigger creation of the specialization. Subsequent calls will pick existing specialization
open System
open System.IO
open System.Collections.Generic
open System.Reflection
open Microsoft.FSharp.Core
open Microsoft.FSharp.Core.Operators
open Microsoft.FSharp.Collections
open LanguagePrimitives.IntrinsicOperators
[<Flags>]
type FormatFlags =
| None = 0
| LeftJustify = 1
| PadWithZeros = 2
| PlusForPositives = 4
| SpaceForPositives = 8
let inline hasFlag flags (expected : FormatFlags) = (flags &&& expected) = expected
let inline isLeftJustify flags = hasFlag flags FormatFlags.LeftJustify
let inline isPadWithZeros flags = hasFlag flags FormatFlags.PadWithZeros
let inline isPlusForPositives flags = hasFlag flags FormatFlags.PlusForPositives
let inline isSpaceForPositives flags = hasFlag flags FormatFlags.SpaceForPositives
/// Used for width and precision to denote that user has specified '*' flag
[<Literal>]
let StarValue = -1
/// Used for width and precision to denote that corresponding value was omitted in format string
[<Literal>]
let NotSpecifiedValue = -2
[<System.Diagnostics.DebuggerDisplayAttribute("{ToString()}")>]
[<NoComparison; NoEquality>]
type FormatSpecifier =
{
TypeChar : char
Precision : int
Width : int
Flags : FormatFlags
}
member this.IsStarPrecision = this.Precision = StarValue
member this.IsPrecisionSpecified = this.Precision <> NotSpecifiedValue
member this.IsStarWidth = this.Width = StarValue
member this.IsWidthSpecified = this.Width <> NotSpecifiedValue
override this.ToString() =
let valueOf n = match n with StarValue -> "*" | NotSpecifiedValue -> "-" | n -> n.ToString()
System.String.Format
(
"'{0}', Precision={1}, Width={2}, Flags={3}",
this.TypeChar,
(valueOf this.Precision),
(valueOf this.Width),
this.Flags
)
/// Set of helpers to parse format string
module private FormatString =
let inline isDigit c = c >= '0' && c <= '9'
let intFromString (s : string) pos =
let rec go acc i =
if isDigit s.[i] then
let n = int s.[i] - int '0'
go (acc * 10 + n) (i + 1)
else acc, i
go 0 pos
let parseFlags (s : string) i : FormatFlags * int =
let rec go flags i =
match s.[i] with
| '0' -> go (flags ||| FormatFlags.PadWithZeros) (i + 1)
| '+' -> go (flags ||| FormatFlags.PlusForPositives) (i + 1)
| ' ' -> go (flags ||| FormatFlags.SpaceForPositives) (i + 1)
| '-' -> go (flags ||| FormatFlags.LeftJustify) (i + 1)
| _ -> flags, i
go FormatFlags.None i
let parseWidth (s : string) i : int * int =
if s.[i] = '*' then StarValue, (i + 1)
elif isDigit (s.[i]) then intFromString s i
else NotSpecifiedValue, i
let parsePrecision (s : string) i : int * int =
if s.[i] = '.' then
if s.[i + 1] = '*' then StarValue, i + 2
elif isDigit (s.[i + 1]) then intFromString s (i + 1)
else raise (ArgumentException("invalid precision value"))
else NotSpecifiedValue, i
let parseTypeChar (s : string) i : char * int =
s.[i], (i + 1)
let findNextFormatSpecifier (s : string) i =
let rec go i (buf : Text.StringBuilder) =
if i >= s.Length then
s.Length, buf.ToString()
else
let c = s.[i]
if c = '%' then
if i + 1 < s.Length then
let _, i1 = parseFlags s (i + 1)
let w, i2 = parseWidth s i1
let p, i3 = parsePrecision s i2
let typeChar, i4 = parseTypeChar s i3
// shortcut for the simpliest case
// if typeChar is not % or it has star as width\precision - resort to long path
if typeChar = '%' && not (w = StarValue || p = StarValue) then
buf.Append('%') |> ignore
go i4 buf
else
i, buf.ToString()
else
raise (ArgumentException("Missing format specifier"))
else
buf.Append(c) |> ignore
go (i + 1) buf
go i (Text.StringBuilder())
/// Abstracts generated printer from the details of particular environment: how to write text, how to produce results etc...
[<AbstractClass>]
type PrintfEnv<'State, 'Residue, 'Result> =
val State : 'State
new(s : 'State) = { State = s }
abstract Finalize : unit -> 'Result
abstract Write : string -> unit
abstract WriteT : 'Residue -> unit
type Utils =
static member inline Write (env : PrintfEnv<_, _, _>, a, b) =
env.Write a
env.Write b
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c) =
Utils.Write(env, a, b)
env.Write c
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d) =
Utils.Write(env, a, b)
Utils.Write(env, c, d)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e) =
Utils.Write(env, a, b, c)
Utils.Write(env, d, e)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f) =
Utils.Write(env, a, b, c, d)
Utils.Write(env, e, f)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g) =
Utils.Write(env, a, b, c, d, e)
Utils.Write(env, f, g)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h) =
Utils.Write(env, a, b, c, d, e, f)
Utils.Write(env, g, h)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i) =
Utils.Write(env, a, b, c, d, e, f, g)
Utils.Write(env, h ,i)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j) =
Utils.Write(env, a, b, c, d, e, f, g, h)
Utils.Write(env, i, j)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k) =
Utils.Write(env, a, b, c, d, e, f, g, h, i)
Utils.Write(env, j, k)
static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k, l, m) =
Utils.Write(env, a, b, c, d, e, f, g, h, i, j, k)
Utils.Write(env, l, m)
/// Type of results produced by specialization
/// This is function that accepts thunk to create PrintfEnv on demand and returns concrete instance of Printer (curried function)
/// After all arguments is collected, specialization obtains concrete PrintfEnv from the thunk and use it to output collected data.
type PrintfFactory<'State, 'Residue, 'Result, 'Printer> = (unit -> PrintfEnv<'State, 'Residue, 'Result>) -> 'Printer
[<Literal>]
let MaxArgumentsInSpecialization = 5
/// Specializations are created via factory methods. These methods accepts 2 kinds of arguments
/// - parts of format string that corresponds to raw text
/// - functions that can transform collected values to strings
/// basic shape of the signature of specialization
/// <prefix-string> + <converter for arg1> + <suffix that comes after arg1> + ... <converter for arg-N> + <suffix that comes after arg-N>
type Specializations<'State, 'Residue, 'Result> private ()=
static member Final1<'A>
(
s0, conv1, s1
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) ->
let env = env()
Utils.Write(env, s0, (conv1 a), s1)
env.Finalize()
)
)
static member Final2<'A, 'B>
(
s0, conv1, s1, conv2, s2
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) ->
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2)
env.Finalize()
)
)
static member Final3<'A, 'B, 'C>
(
s0, conv1, s1, conv2, s2, conv3, s3
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) ->
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3)
env.Finalize()
)
)
static member Final4<'A, 'B, 'C, 'D>
(
s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)->
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4)
env.Finalize()
)
)
static member Final5<'A, 'B, 'C, 'D, 'E>
(
s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5, s5
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)->
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e), s5)
env.Finalize()
)
)
static member Chained1<'A, 'Tail>
(
s0, conv1,
next
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) ->
let env() =
let env = env()
Utils.Write(env, s0, (conv1 a))
env
next env : 'Tail
)
)
static member Chained2<'A, 'B, 'Tail>
(
s0, conv1, s1, conv2,
next
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) ->
let env() =
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b))
env
next env : 'Tail
)
)
static member Chained3<'A, 'B, 'C, 'Tail>
(
s0, conv1, s1, conv2, s2, conv3,
next
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) ->
let env() =
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c))
env
next env : 'Tail
)
)
static member Chained4<'A, 'B, 'C, 'D, 'Tail>
(
s0, conv1, s1, conv2, s2, conv3, s3, conv4,
next
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)->
let env() =
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d))
env
next env : 'Tail
)
)
static member Chained5<'A, 'B, 'C, 'D, 'E, 'Tail>
(
s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5,
next
) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)->
let env() =
let env = env()
Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e))
env
next env : 'Tail
)
)
static member TFinal(s1 : string, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (f : 'State -> 'Residue) ->
let env = env()
env.Write(s1)
env.WriteT(f env.State)
env.Write s2
env.Finalize()
)
)
static member TChained<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (f : 'State -> 'Residue) ->
let env() =
let env = env()
env.Write(s1)
env.WriteT(f env.State)
env
next(env) : 'Tail
)
)
static member LittleAFinal<'A>(s1 : string, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (f : 'State -> 'A ->'Residue) (a : 'A) ->
let env = env()
env.Write s1
env.WriteT(f env.State a)
env.Write s2
env.Finalize()
)
)
static member LittleAChained<'A, 'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (f : 'State -> 'A ->'Residue) (a : 'A) ->
let env() =
let env = env()
env.Write s1
env.WriteT(f env.State a)
env
next env : 'Tail
)
)
static member StarFinal1<'A>(s1 : string, conv, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (star1 : int) (a : 'A) ->
let env = env()
env.Write s1
env.Write (conv a star1 : string)
env.Write s2
env.Finalize()
)
)
static member PercentStarFinal1(s1 : string, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (_star1 : int) ->
let env = env()
env.Write s1
env.Write("%")
env.Write s2
env.Finalize()
)
)
static member StarFinal2<'A>(s1 : string, conv, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (star1 : int) (star2 : int) (a : 'A) ->
let env = env()
env.Write s1
env.Write (conv a star1 star2: string)
env.Write s2
env.Finalize()
)
)
/// Handles case when '%*.*%' is used at the end of string
static member PercentStarFinal2(s1 : string, s2 : string) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (_star1 : int) (_star2 : int) ->
let env = env()
env.Write s1
env.Write("%")
env.Write s2
env.Finalize()
)
)
static member StarChained1<'A, 'Tail>(s1 : string, conv, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (star1 : int) (a : 'A) ->
let env() =
let env = env()
env.Write s1
env.Write(conv a star1 : string)
env
next env : 'Tail
)
)
/// Handles case when '%*%' is used in the middle of the string so it needs to be chained to another printing block
static member PercentStarChained1<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (_star1 : int) ->
let env() =
let env = env()
env.Write s1
env.Write("%")
env
next env : 'Tail
)
)
static member StarChained2<'A, 'Tail>(s1 : string, conv, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (star1 : int) (star2 : int) (a : 'A) ->
let env() =
let env = env()
env.Write s1
env.Write(conv a star1 star2 : string)
env
next env : 'Tail
)
)
/// Handles case when '%*.*%' is used in the middle of the string so it needs to be chained to another printing block
static member PercentStarChained2<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) =
(fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) ->
(fun (_star1 : int) (_star2 : int) ->
let env() =
let env = env()
env.Write s1
env.Write("%")
env
next env : 'Tail
)
)
let inline (===) a b = Object.ReferenceEquals(a, b)
let invariantCulture = System.Globalization.CultureInfo.InvariantCulture
let inline boolToString v = if v then "true" else "false"
let inline stringToSafeString v = if v = null then "" else v
[<Literal>]
let DefaultPrecision = 6
let getFormatForFloat (ch : char) (prec : int) = ch.ToString() + prec.ToString()
let normalizePrecision prec = min (max prec 0) 99
/// Contains helpers to convert printer functions to functions that prints value with respect to specified justification
/// There are two kinds to printers:
/// 'T -> string - converts value to string - used for strings, basic integers etc..
/// string -> 'T -> string - converts value to string with given format string - used by numbers with floating point, typically precision is set via format string
/// To support both categories there are two entry points:
/// - withPadding - adapts first category
/// - withPaddingFormatted - adapts second category
module Padding =
/// pad here is function that converts T to string with respect of justification
/// basic - function that converts T to string without appying justification rules
/// adaptPaddedFormatted returns boxed function that has various number of arguments depending on if width\precision flags has '*' value
let inline adaptPaddedFormatted (spec : FormatSpecifier) getFormat (basic : string -> 'T -> string) (pad : string -> int -> 'T -> string) =
if spec.IsStarWidth then
if spec.IsStarPrecision then
// width=*, prec=*
box(fun v width prec ->
let fmt = getFormat (normalizePrecision prec)
pad fmt width v
)
else
// width=*, prec=?
let prec = if spec.IsPrecisionSpecified then normalizePrecision spec.Precision else DefaultPrecision
let fmt = getFormat prec
box(fun v width ->
pad fmt width v
)
elif spec.IsStarPrecision then
if spec.IsWidthSpecified then
// width=val, prec=*
box(fun v prec ->
let fmt = getFormat prec
pad fmt spec.Width v
)
else
// width=X, prec=*
box(fun v prec ->
let fmt = getFormat prec
basic fmt v
)
else
let prec = if spec.IsPrecisionSpecified then normalizePrecision spec.Precision else DefaultPrecision
let fmt = getFormat prec
if spec.IsWidthSpecified then
// width=val, prec=*
box(fun v ->
pad fmt spec.Width v
)
else
// width=X, prec=*
box(fun v ->
basic fmt v
)
/// pad here is function that converts T to string with respect of justification
/// basic - function that converts T to string without appying justification rules
/// adaptPadded returns boxed function that has various number of arguments depending on if width flags has '*' value
let inline adaptPadded (spec : FormatSpecifier) (basic : 'T -> string) (pad : int -> 'T -> string) =
if spec.IsStarWidth then
// width=*, prec=?
box(fun v width ->
pad width v
)
else
if spec.IsWidthSpecified then
// width=val, prec=*
box(fun v ->
pad spec.Width v
)
else
// width=X, prec=*
box(fun v ->
basic v
)
let inline withPaddingFormatted (spec : FormatSpecifier) getFormat (defaultFormat : string) (f : string -> 'T -> string) left right =
if not (spec.IsWidthSpecified || spec.IsPrecisionSpecified) then
box (f defaultFormat)
else
if isLeftJustify spec.Flags then
adaptPaddedFormatted spec getFormat f left
else
adaptPaddedFormatted spec getFormat f right
let inline withPadding (spec : FormatSpecifier) (f : 'T -> string) left right =
if not (spec.IsWidthSpecified) then
box f
else
if isLeftJustify spec.Flags then
adaptPadded spec f left
else
adaptPadded spec f right
let inline isNumber (x: ^T) =
not (^T: (static member IsPositiveInfinity: 'T -> bool) x) && not (^T: (static member IsNegativeInfinity: 'T -> bool) x) && not (^T: (static member IsNaN: 'T -> bool) x)
let inline isInteger n =
n % LanguagePrimitives.GenericOne = LanguagePrimitives.GenericZero
let inline isPositive n =
n >= LanguagePrimitives.GenericZero
/// contains functions to handle left\right justifications for non-numeric types (strings\bools)
module Basic =
let inline leftJustify f padChar =
fun (w : int) v ->
(f v : string).PadRight(w, padChar)
let inline rightJustify f padChar =
fun (w : int) v ->
(f v : string).PadLeft(w, padChar)
/// contains functions to handle left\right and no justification case for numbers
module GenericNumber =
/// handles right justification when pad char = '0'
/// this case can be tricky:
/// - negative numbers, -7 should be printed as '-007', not '00-7'
/// - positive numbers when prefix for positives is set: 7 should be '+007', not '00+7'
let inline rightJustifyWithZeroAsPadChar (str : string) isNumber isPositive w (prefixForPositives : string) =
System.Diagnostics.Debug.Assert(prefixForPositives.Length = 0 || prefixForPositives.Length = 1)
if isNumber then
if isPositive then
prefixForPositives + (if w = 0 then str else str.PadLeft(w - prefixForPositives.Length, '0')) // save space to
else
if str.[0] = '-' then
let str = str.Substring(1)
"-" + (if w = 0 then str else str.PadLeft(w - 1, '0'))
else
str.PadLeft(w, '0')
else
str.PadLeft(w, ' ')
/// handler right justification when pad char = ' '
let inline rightJustifyWithSpaceAsPadChar (str : string) isNumber isPositive w (prefixForPositives : string) =
System.Diagnostics.Debug.Assert(prefixForPositives.Length = 0 || prefixForPositives.Length = 1)
(if isNumber && isPositive then prefixForPositives + str else str).PadLeft(w, ' ')
/// handles left justification with formatting with 'G'\'g' - either for decimals or with 'g'\'G' is explicitly set
let inline leftJustifyWithGFormat (str : string) isNumber isInteger isPositive w (prefixForPositives : string) padChar =
if isNumber then
let str = if isPositive then prefixForPositives + str else str
// NOTE: difference - for 'g' format we use isInt check to detect situations when '5.0' is printed as '5'
// in this case we need to override padding and always use ' ', otherwise we'll produce incorrect results
if isInteger then
str.PadRight(w, ' ') // don't pad integer numbers with '0' when 'g' format is specified (may yield incorrect results)
else
str.PadRight(w, padChar) // non-integer => string representation has point => can pad with any character
else
str.PadRight(w, ' ') // pad NaNs with ' '
let inline leftJustifyWithNonGFormat (str : string) isNumber isPositive w (prefixForPositives : string) padChar =
if isNumber then
let str = if isPositive then prefixForPositives + str else str
str.PadRight(w, padChar)
else
str.PadRight(w, ' ') // pad NaNs with ' '
/// processes given string based depending on values isNumber\isPositive
let inline noJustificationCore (str : string) isNumber isPositive prefixForPositives =
if isNumber && isPositive then prefixForPositives + str
else str
/// noJustification handler for f : 'T -> string - basic integer types
let inline noJustification f (prefix : string) isUnsigned =
if isUnsigned then
fun v -> noJustificationCore (f v) true true prefix
else
fun v -> noJustificationCore (f v) true (isPositive v) prefix
/// noJustification handler for f : string -> 'T -> string - floating point types
let inline noJustificationWithFormat f (prefix : string) =
fun (fmt : string) v -> noJustificationCore (f fmt v) true (isPositive v) prefix
/// leftJustify handler for f : 'T -> string - basic integer types
let inline leftJustify isGFormat f (prefix : string) padChar isUnsigned =
if isUnsigned then
if isGFormat then
fun (w : int) v ->
leftJustifyWithGFormat (f v) true (isInteger v) true w prefix padChar
else
fun (w : int) v ->
leftJustifyWithNonGFormat (f v) true true w prefix padChar
else
if isGFormat then
fun (w : int) v ->
leftJustifyWithGFormat (f v) true (isInteger v) (isPositive v) w prefix padChar
else
fun (w : int) v ->
leftJustifyWithNonGFormat (f v) true (isPositive v) w prefix padChar
/// leftJustify handler for f : string -> 'T -> string - floating point types
let inline leftJustifyWithFormat isGFormat f (prefix : string) padChar =
if isGFormat then
fun (fmt : string) (w : int) v ->
leftJustifyWithGFormat (f fmt v) true (isInteger v) (isPositive v) w prefix padChar
else
fun (fmt : string) (w : int) v ->
leftJustifyWithNonGFormat (f fmt v) true (isPositive v) w prefix padChar
/// rightJustify handler for f : 'T -> string - basic integer types
let inline rightJustify f (prefixForPositives : string) padChar isUnsigned =
if isUnsigned then
if padChar = '0' then
fun (w : int) v ->
rightJustifyWithZeroAsPadChar (f v) true true w prefixForPositives
else
System.Diagnostics.Debug.Assert((padChar = ' '))
fun (w : int) v ->
rightJustifyWithSpaceAsPadChar (f v) true true w prefixForPositives
else
if padChar = '0' then
fun (w : int) v ->
rightJustifyWithZeroAsPadChar (f v) true (isPositive v) w prefixForPositives
else
System.Diagnostics.Debug.Assert((padChar = ' '))
fun (w : int) v ->
rightJustifyWithSpaceAsPadChar (f v) true (isPositive v) w prefixForPositives
/// rightJustify handler for f : string -> 'T -> string - floating point types
let inline rightJustifyWithFormat f (prefixForPositives : string) padChar =
if padChar = '0' then
fun (fmt : string) (w : int) v ->
rightJustifyWithZeroAsPadChar (f fmt v) true (isPositive v) w prefixForPositives
else
System.Diagnostics.Debug.Assert((padChar = ' '))
fun (fmt : string) (w : int) v ->
rightJustifyWithSpaceAsPadChar (f fmt v) true (isPositive v) w prefixForPositives
module Float =
let inline noJustification f (prefixForPositives : string) =
fun (fmt : string) v ->
GenericNumber.noJustificationCore (f fmt v) (isNumber v) (isPositive v) prefixForPositives
let inline leftJustify isGFormat f (prefix : string) padChar =
if isGFormat then
fun (fmt : string) (w : int) v ->
GenericNumber.leftJustifyWithGFormat (f fmt v) (isNumber v) (isInteger v) (isPositive v) w prefix padChar
else
fun (fmt : string) (w : int) v ->
GenericNumber.leftJustifyWithNonGFormat (f fmt v) (isNumber v) (isPositive v) w prefix padChar
let inline rightJustify f (prefixForPositives : string) padChar =
if padChar = '0' then
fun (fmt : string) (w : int) v ->
GenericNumber.rightJustifyWithZeroAsPadChar (f fmt v) (isNumber v) (isPositive v) w prefixForPositives
else
System.Diagnostics.Debug.Assert((padChar = ' '))
fun (fmt : string) (w : int) v ->
GenericNumber.rightJustifyWithSpaceAsPadChar (f fmt v) (isNumber v) (isPositive v) w prefixForPositives
let isDecimalFormatSpecifier (spec : FormatSpecifier) =
spec.TypeChar = 'M'
let getPadAndPrefix allowZeroPadding (spec : FormatSpecifier) =
let padChar = if allowZeroPadding && isPadWithZeros spec.Flags then '0' else ' ';
let prefix =
if isPlusForPositives spec.Flags then "+"
elif isSpaceForPositives spec.Flags then " "
else ""
padChar, prefix
let isGFormat(spec : FormatSpecifier) =
isDecimalFormatSpecifier spec || System.Char.ToLower(spec.TypeChar) = 'g'
let inline basicWithPadding (spec : FormatSpecifier) f =
let padChar, _ = getPadAndPrefix false spec
Padding.withPadding spec f (Basic.leftJustify f padChar) (Basic.rightJustify f padChar)
let inline numWithPadding (spec : FormatSpecifier) isUnsigned f =
let allowZeroPadding = not (isLeftJustify spec.Flags) || isDecimalFormatSpecifier spec
let padChar, prefix = getPadAndPrefix allowZeroPadding spec
let isGFormat = isGFormat spec
Padding.withPadding spec (GenericNumber.noJustification f prefix isUnsigned) (GenericNumber.leftJustify isGFormat f prefix padChar isUnsigned) (GenericNumber.rightJustify f prefix padChar isUnsigned)
let inline decimalWithPadding (spec : FormatSpecifier) getFormat defaultFormat f =
let padChar, prefix = getPadAndPrefix true spec
let isGFormat = isGFormat spec
Padding.withPaddingFormatted spec getFormat defaultFormat (GenericNumber.noJustificationWithFormat f prefix) (GenericNumber.leftJustifyWithFormat isGFormat f prefix padChar) (GenericNumber.rightJustifyWithFormat f prefix padChar)
let inline floatWithPadding (spec : FormatSpecifier) getFormat defaultFormat f =
let padChar, prefix = getPadAndPrefix true spec
let isGFormat = isGFormat spec
Padding.withPaddingFormatted spec getFormat defaultFormat (Float.noJustification f prefix) (Float.leftJustify isGFormat f prefix padChar) (Float.rightJustify f prefix padChar)
let inline identity v = v
let inline toString v = (^T : (member ToString : IFormatProvider -> string)(v, invariantCulture))
let inline toFormattedString fmt = fun (v : ^T) -> (^T : (member ToString : string * IFormatProvider -> string)(v, fmt, invariantCulture))
let inline numberToString c spec alt unsignedConv =
if c = 'd' || c = 'i' then
numWithPadding spec false (alt >> toString : ^T -> string)
elif c = 'u' then
numWithPadding spec true (alt >> unsignedConv >> toString : ^T -> string)
elif c = 'x' then
numWithPadding spec true (alt >> toFormattedString "x" : ^T -> string)
elif c = 'X' then
numWithPadding spec true (alt >> toFormattedString "X" : ^T -> string )
elif c = 'o' then
numWithPadding spec true (fun (v : ^T) -> Convert.ToString(int64(unsignedConv (alt v)), 8))
else raise (ArgumentException())
type ObjectPrinter =
static member ObjectToString<'T>(spec : FormatSpecifier) =
basicWithPadding spec (fun (v : 'T) -> match box v with null -> "<null>" | x -> x.ToString())
static member GenericToStringCore(v : 'T, opts : Microsoft.FSharp.Text.StructuredPrintfImpl.FormatOptions, bindingFlags) =
// printfn %0A is considered to mean 'print width zero'
match box v with
| null -> "<null>"
| _ -> Microsoft.FSharp.Text.StructuredPrintfImpl.Display.anyToStringForPrintf opts bindingFlags v
static member GenericToString<'T>(spec : FormatSpecifier) =
let bindingFlags =
#if FX_RESHAPED_REFLECTION
isPlusForPositives spec.Flags // true - show non-public
#else
if isPlusForPositives spec.Flags then BindingFlags.Public ||| BindingFlags.NonPublic
else BindingFlags.Public
#endif
let useZeroWidth = isPadWithZeros spec.Flags
let opts =
let o = Microsoft.FSharp.Text.StructuredPrintfImpl.FormatOptions.Default
let o =
if useZeroWidth then { o with PrintWidth = 0}
elif spec.IsWidthSpecified then { o with PrintWidth = spec.Width}
else o
if spec.IsPrecisionSpecified then { o with PrintSize = spec.Precision}
else o
match spec.IsStarWidth, spec.IsStarPrecision with
| true, true ->
box (fun (v : 'T) (width : int) (prec : int) ->
let opts = { opts with PrintSize = prec }
let opts = if not useZeroWidth then { opts with PrintWidth = width} else opts
ObjectPrinter.GenericToStringCore(v, opts, bindingFlags)
)
| true, false ->
box (fun (v : 'T) (width : int) ->
let opts = if not useZeroWidth then { opts with PrintWidth = width} else opts
ObjectPrinter.GenericToStringCore(v, opts, bindingFlags)
)
| false, true ->
box (fun (v : 'T) (prec : int) ->
let opts = { opts with PrintSize = prec }
ObjectPrinter.GenericToStringCore(v, opts, bindingFlags)
)
| false, false ->
box (fun (v : 'T) ->
ObjectPrinter.GenericToStringCore(v, opts, bindingFlags)
)
let basicNumberToString (ty : Type) (spec : FormatSpecifier) =
System.Diagnostics.Debug.Assert(not spec.IsPrecisionSpecified, "not spec.IsPrecisionSpecified")
let ch = spec.TypeChar
match Type.GetTypeCode(ty) with
| TypeCode.Int32 -> numberToString ch spec identity (uint32 : int -> uint32)
| TypeCode.Int64 -> numberToString ch spec identity (uint64 : int64 -> uint64)
| TypeCode.Byte -> numberToString ch spec identity (byte : byte -> byte)
| TypeCode.SByte -> numberToString ch spec identity (byte : sbyte -> byte)
| TypeCode.Int16 -> numberToString ch spec identity (uint16 : int16 -> uint16)
| TypeCode.UInt16 -> numberToString ch spec identity (uint16 : uint16 -> uint16)
| TypeCode.UInt32 -> numberToString ch spec identity (uint32 : uint32 -> uint32)
| TypeCode.UInt64 -> numberToString ch spec identity (uint64 : uint64 -> uint64)
| _ ->
if ty === typeof<nativeint> then
if IntPtr.Size = 4 then
numberToString ch spec (fun (v : IntPtr) -> v.ToInt32()) uint32
else
numberToString ch spec (fun (v : IntPtr) -> v.ToInt64()) uint64
elif ty === typeof<unativeint> then
if IntPtr.Size = 4 then
numberToString ch spec (fun (v : UIntPtr) -> v.ToUInt32()) uint32
else
numberToString ch spec (fun (v : UIntPtr) -> v.ToUInt64()) uint64
else raise (ArgumentException(ty.Name + " not a basic integer type"))
let basicFloatToString ty spec =
let defaultFormat = getFormatForFloat spec.TypeChar DefaultPrecision
match Type.GetTypeCode(ty) with
| TypeCode.Single -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : float32) -> toFormattedString fmt v)
| TypeCode.Double -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : float) -> toFormattedString fmt v)
| TypeCode.Decimal -> decimalWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : decimal) -> toFormattedString fmt v)
| _ -> raise (ArgumentException(ty.Name + " not a basic floating point type"))
let private NonPublicStatics = BindingFlags.NonPublic ||| BindingFlags.Static
let private getValueConverter (ty : Type) (spec : FormatSpecifier) : obj =
match spec.TypeChar with
| 'b' ->
System.Diagnostics.Debug.Assert(ty === typeof<bool>, "ty === typeof<bool>")
basicWithPadding spec boolToString
| 's' ->
System.Diagnostics.Debug.Assert(ty === typeof<string>, "ty === typeof<string>")
basicWithPadding spec stringToSafeString
| 'c' ->
System.Diagnostics.Debug.Assert(ty === typeof<char>, "ty === typeof<char>")
basicWithPadding spec (fun (c : char) -> c.ToString())
| 'M' ->
System.Diagnostics.Debug.Assert(ty === typeof<decimal>, "ty === typeof<decimal>")
decimalWithPadding spec (fun _ -> "G") "G" (fun fmt (v : decimal) -> toFormattedString fmt v) // %M ignores precision
| 'd' | 'i' | 'x' | 'X' | 'u' | 'o'->
basicNumberToString ty spec
| 'e' | 'E'
| 'f' | 'F'
| 'g' | 'G' ->
basicFloatToString ty spec
| 'A' ->
let mi = typeof<ObjectPrinter>.GetMethod("GenericToString", NonPublicStatics)
let mi = mi.MakeGenericMethod(ty)
mi.Invoke(null, [| box spec |])
| 'O' ->
let mi = typeof<ObjectPrinter>.GetMethod("ObjectToString", NonPublicStatics)
let mi = mi.MakeGenericMethod(ty)
mi.Invoke(null, [| box spec |])
| _ ->
raise (ArgumentException(SR.GetString(SR.printfBadFormatSpecifier)))
let extractCurriedArguments (ty : Type) n =
System.Diagnostics.Debug.Assert(n = 1 || n = 2 || n = 3, "n = 1 || n = 2 || n = 3")
let buf = Array.zeroCreate (n + 1)
let rec go (ty : Type) i =
if i < n then
match ty.GetGenericArguments() with
| [| argTy; retTy|] ->
buf.[i] <- argTy
go retTy (i + 1)
| _ -> failwith (String.Format("Expected function with {0} arguments", n))
else
System.Diagnostics.Debug.Assert((i = n), "i = n")
buf.[i] <- ty
buf
go ty 0
[<Literal>]
let ContinuationOnStack = -1
type private PrintfBuilderStack() =
let args = Stack(10)
let types = Stack(5)
let stackToArray size start count (s : Stack<_>) =
let arr = Array.zeroCreate size
for i = 0 to count - 1 do
arr.[start + i] <- s.Pop()
arr
member this.GetArgumentAndTypesAsArrays
(
argsArraySize, argsArrayStartPos, argsArrayTotalCount,
typesArraySize, typesArrayStartPos, typesArrayTotalCount
) =
let argsArray = stackToArray argsArraySize argsArrayStartPos argsArrayTotalCount args
let typesArray = stackToArray typesArraySize typesArrayStartPos typesArrayTotalCount types
argsArray, typesArray
member this.PopContinuationWithType() =
System.Diagnostics.Debug.Assert(args.Count = 1, "args.Count = 1")
System.Diagnostics.Debug.Assert(types.Count = 1, "types.Count = 1")
let cont = args.Pop()
let contTy = types.Pop()
cont, contTy
member this.PopValueUnsafe() = args.Pop()
member this.PushContinuationWithType (cont : obj, contTy : Type) =
System.Diagnostics.Debug.Assert(this.IsEmpty, "this.IsEmpty")
System.Diagnostics.Debug.Assert(
(
let _arg, retTy = Microsoft.FSharp.Reflection.FSharpType.GetFunctionElements(cont.GetType())
contTy.IsAssignableFrom retTy
),
"incorrect type"
)
this.PushArgumentWithType(cont, contTy)
member this.PushArgument(value : obj) =
args.Push value
member this.PushArgumentWithType(value : obj, ty) =
args.Push value
types.Push ty
member this.HasContinuationOnStack(expectedNumberOfArguments) =
types.Count = expectedNumberOfArguments + 1
member this.IsEmpty =
System.Diagnostics.Debug.Assert(args.Count = types.Count, "args.Count = types.Count")
args.Count = 0
/// Parses format string and creates result printer function.
/// First it recursively consumes format string up to the end, then during unwinding builds printer using PrintfBuilderStack as storage for arguments.
/// idea of implementation is very simple: every step can either push argument to the stack (if current block of 5 format specifiers is not yet filled)
// or grab the content of stack, build intermediate printer and push it back to stack (so it can later be consumed by as argument)