aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/text/format.lux
blob: 83701c9728b16b5e57ff69e96994c1b678d66f3c (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
(.module:
  [lux #*
   [control
    [monad (#+ do Monad)]
    ["p" parser]]
   [data
    ["." bit]
    ["." name]
    [number
     ["." nat]
     ["." int]
     ["." rev]
     ["." frac]]
    ["." text]
    [format
     ["." xml]
     ["." json]]
    [collection
     ["." list ("#;." monad)]]]
   [time
    ["." instant]
    ["." duration]
    ["." date]]
   [math
    ["." modular]]
   ["." macro
    ["." code]
    ["s" syntax (#+ syntax: Syntax)]]
   ["." 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        Bit               (:: bit.codec encode)]
  [%n        Nat               (:: nat.decimal encode)]
  [%i        Int               (:: int.decimal encode)]
  [%r        Rev               (:: rev.decimal encode)]
  [%f        Frac              (:: frac.decimal encode)]
  [%t        Text              text.encode]
  [%name     Name              (:: name.codec encode)]
  [%code     Code              code.to-text]
  [%type     Type              type.to-text]
  [%bin      Nat               (:: nat.binary encode)]
  [%oct      Nat               (:: nat.octal encode)]
  [%hex      Nat               (:: nat.hex encode)]
  [%xml      xml.XML           (:: xml.codec encode)]
  [%json     json.JSON         (:: json.codec encode)]
  [%instant  instant.Instant   instant.to-text]
  [%date     date.Date         (:: date.codec encode)]
  )

(def: #export %duration
  (Format duration.Duration)
  duration.encode)

(def: #export (%cursor [file line column])
  (Format Cursor)
  (|> (list (%t file) (%n line) (%n column))
      (text.join-with ", ")
      (text.enclose ["[" "]"])))

(def: #export (%mod modular)
  (All [m] (Format (modular.Mod m)))
  (let [[_ modulus] (modular.un-mod modular)]
    (:: (modular.codec 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)) ")"))))