aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/text/format.lux
blob: 16651957e2be90f351d7310c977934f94c21019f (plain)
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
(.module:
  lux
  (lux (control [monad #+ do Monad]
                ["p" parser])
       (data [bool]
             [number]
             [text]
             [ident]
             (collection [list "list/" Monad<List>])
             (format [xml]
                     [json]))
       (time [instant]
             [duration]
             [date])
       (math [modular])
       [macro]
       (macro [code]
              ["s" syntax #+ syntax: Syntax])
       (language [type])
       ))

## [Syntax]
(syntax: #export (format {fragments (p.many s.any)})
  {#.doc (doc "Text interpolation."
              (format "Static part " (%t static) " does not match URI: " uri))}
  (wrap (list (` ($_ "lux text concat" (~+ fragments))))))

## [Formats]
(type: #export (Format a)
  {#.doc "A way to produce readable text from values."}
  (-> a Text))

(do-template [<name> <type> <formatter>]
  [(def: #export <name>
     (Format <type>)
     <formatter>)]

  [%b        Bool              (:: bool.Codec<Text,Bool> encode)]
  [%n        Nat               (:: number.Codec<Text,Nat> encode)]
  [%i        Int               (:: number.Codec<Text,Int> encode)]
  [%r        Rev               (:: number.Codec<Text,Rev> encode)]
  [%f        Frac              (:: number.Codec<Text,Frac> encode)]
  [%t        Text              text.encode]
  [%ident    Ident             (:: ident.Codec<Text,Ident> encode)]
  [%code     Code              code.to-text]
  [%type     Type              type.to-text]
  [%bin      Nat               (:: number.Binary@Codec<Text,Nat> encode)]
  [%oct      Nat               (:: number.Octal@Codec<Text,Nat> encode)]
  [%hex      Nat               (:: number.Hex@Codec<Text,Nat> encode)]
  [%xml      xml.XML           (:: xml.Codec<Text,XML> encode)]
  [%json     json.JSON         (:: json.Codec<Text,JSON> encode)]
  [%instant  instant.Instant   instant.to-text]
  [%duration duration.Duration (:: duration.Codec<Text,Duration> encode)]
  [%date     date.Date         (:: date.Codec<Text,Date> encode)]
  )

(def: #export (%mod modular)
  (All [m] (Format (modular.Mod m)))
  (let [[_ modulus] (modular.un-mod modular)]
    (:: (modular.Codec<Text,Mod> modulus) encode modular)))

(def: #export (%list formatter)
  (All [a] (-> (Format a) (Format (List a))))
  (function (_ values)
    (case values
      #.Nil
      "(list)"

      _
      (format "(list " (text.join-with " " (list/map formatter values)) ")"))))