-
Notifications
You must be signed in to change notification settings - Fork 1
/
pprint.gleam
341 lines (297 loc) Β· 8.79 KB
/
pprint.gleam
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
import gleam/io
import gleam/int
import gleam/bool
import gleam/list
import gleam/float
import gleam/dict.{type Dict}
import gleam/string
import gleam/dynamic.{type Dynamic}
import gleam/bit_array
import glam/doc.{type Document}
import pprint/decoder
// --- PUBLIC API --------------------------------------------------------------
/// Configuration for the pretty printer.
///
pub type Config {
Config(
style_mode: StyleMode,
bit_array_mode: BitArrayMode,
label_mode: LabelMode,
)
}
/// Styling can be configured with `StyleMode`.
///
pub type StyleMode {
/// Data structures are styled with ANSI style codes.
///
/// > β οΈ **WARNING:** Styling is subject to change *without* a major release!
/// This means that this option should only be used for debugging purposes and
/// *should not* be used in tests.
Styled
/// Everything remains unstyled.
Unstyled
}
/// Since Erlang handles BitArrays differently than JavaScript does, the
/// `BitArraysAsString` config option enables compatibility between the two targets.
///
/// These options only affect the JS target, which does not convert bit arrays to
/// strings by default like Erlang does.
///
pub type BitArrayMode {
/// Bit arrays will be converted to strings when pretty printed.
BitArraysAsString
/// Bit arrays will be kept the same.
KeepBitArrays
}
/// This option only affects the JavaScript target since Erlang has a different
/// runtime representation of custom types that omits labels.
///
pub type LabelMode {
/// Show field labels in custom types.
/// ```
/// Foo(42, bar: "bar", baz: "baz")
/// ```
Labels
/// Leave out field labels.
/// ```
/// Foo(42, "bar", "baz")
/// ```
NoLabels
}
const max_width = 40
/// Pretty print a value with the config below to stderr for debugging purposes.
/// The value is returned back from the function so it can be used in pipelines.
///
/// ```
/// Config(Styled, KeepBitArrays, Labels)
/// ```
///
/// # Examples
///
/// ```
/// pprint.debug([1, 2, 3])
/// |> list.each(pprint.debug)
///
/// // Prints:
/// // [1, 2, 3]
/// // 1
/// // 2
/// // 3
/// ```
///
pub fn debug(value: a) -> a {
value
|> with_config(Config(Styled, KeepBitArrays, Labels))
|> io.println_error
value
}
/// Pretty print a value as a string with the following config:
/// ```
/// Config(Unstyled, BitArraysAsString, NoLabels)
/// ```
/// This function behaves identically on both targets so it can be relied upon
/// for snapshot testing.
///
pub fn format(value: a) -> String {
with_config(value, Config(Unstyled, BitArraysAsString, NoLabels))
}
/// Pretty print a value as a string with the following config:
/// ```
/// Config(Styled, BitArraysAsString, NoLabels)
/// ```
/// This function behaves identically on both targets.
///
/// > β οΈ **WARNING:** Styling is subject to change *without* a major release!
/// This means that this function should only be used for debugging purposes and
/// *should not* be used in tests.
///
pub fn styled(value: a) -> String {
with_config(value, Config(Styled, BitArraysAsString, NoLabels))
}
/// Pretty print a value as a string with a custom config.
///
/// # Examples
///
/// ```
/// [1, 2, 3, 4]
/// |> pprint.with_config(Config(Styled, KeepBitArrays, Labels))
/// ```
///
pub fn with_config(value: a, config: Config) -> String {
value
|> dynamic.from
|> pretty_dynamic(config)
|> doc.to_string(max_width)
}
// ---- PRETTY PRINTING --------------------------------------------------------
fn pretty_type(value: decoder.Type, config: Config) -> Document {
case value {
decoder.TString(s) -> pretty_string(s, config)
decoder.TInt(i) ->
int.to_string(i)
|> ansi(yellow, config)
decoder.TFloat(f) ->
float.to_string(f)
|> ansi(yellow, config)
decoder.TBool(b) ->
bool.to_string(b)
|> ansi(blue, config)
decoder.TBitArray(b) ->
case config.bit_array_mode {
KeepBitArrays -> pretty_bit_array(b, config)
BitArraysAsString ->
case bit_array.to_string(b) {
Ok(s) -> pretty_string(s, config)
Error(Nil) -> pretty_bit_array(b, config)
}
}
decoder.TNil -> ansi("Nil", blue, config)
decoder.TList(items) -> pretty_list(items, config)
decoder.TDict(d) -> pretty_dict(d, config)
decoder.TTuple(items) -> pretty_tuple(items, config)
decoder.TCustom(name, fields) -> pretty_custom_type(name, fields, config)
decoder.TForeign(f) -> ansi(f, dim, config)
}
}
fn pretty_dynamic(value: Dynamic, config: Config) -> Document {
value
|> decoder.classify
|> pretty_type(config)
}
fn pretty_string(string: String, config: Config) -> Document {
{ "\"" <> string <> "\"" }
|> ansi(green, config)
}
fn pretty_bit_array(bits: BitArray, config: Config) -> Document {
string.inspect(bits)
|> ansi(magenta, config)
}
fn pretty_list(items: List(Dynamic), config: Config) -> Document {
let items = list.map(items, decoder.classify)
// When the list consists only of numbers, the values are joined with flex spaces
// instead of normal ones.
let space = case items {
[decoder.TInt(_), ..] | [decoder.TFloat(_), ..] -> doc.flex_space
_ -> doc.space
}
list.map(items, pretty_type(_, config))
|> doc.concat_join([doc.from_string(","), space])
|> wrap(doc.from_string("["), doc.from_string("]"), trailing: ",")
}
fn pretty_dict(d: Dict(decoder.Type, decoder.Type), config: Config) -> Document {
dict.to_list(d)
|> list.sort(fn(one_field, other_field) {
// We need to sort dicts so that those always have a consistent order.
let #(one_key, _one_value) = one_field
let #(other_key, _other_value) = other_field
string.compare(string.inspect(one_key), string.inspect(other_key))
})
|> list.map(fn(field) {
// Format the dict's items into tuple literals
[
doc.from_string("#("),
pretty_type(field.0, config),
doc.from_string(", "),
pretty_type(field.1, config),
doc.from_string(")"),
]
|> doc.concat
})
|> doc.concat_join([doc.from_string(","), doc.space])
|> wrap(
doc.from_string("dict.from_list(["),
doc.from_string("])"),
trailing: ",",
)
}
fn pretty_tuple(items: List(Dynamic), config: Config) -> Document {
list.map(items, pretty_dynamic(_, config))
|> doc.concat_join([doc.from_string(","), doc.space])
|> wrap(doc.from_string("#("), doc.from_string(")"), trailing: ",")
}
fn pretty_custom_type(
name: String,
fields: List(decoder.Field),
config: Config,
) -> Document {
// Common built-in constructor names are styled
let style = case name {
"Ok" | "Error" | "Some" | "None" -> bold
_ -> ""
}
let fields =
list.map(fields, fn(field) {
case field, config.label_mode {
decoder.Positional(value), Labels
| decoder.Positional(value), NoLabels
| decoder.Labelled(_, value), NoLabels -> pretty_dynamic(value, config)
decoder.Labelled(label, value), Labels ->
doc.concat([
ansi(label <> ": ", dim, config),
pretty_dynamic(value, config),
])
}
})
let name = ansi(name, style, config)
let open = doc.concat([name, doc.from_string("(")])
let close = doc.from_string(")")
case fields {
[] -> name
// If the constructor has only one field, it is formatted without indenting
// its field to improve readability. In other words, it is formatted like this
//
// Ok([
// // ...
// ])
//
// instead of this:
//
// Ok(
// [
// // ...
// ]
// )
//
[single] -> doc.concat([open, single, close])
// However, multiple fields are indented because they would look weird otherwise.
_ ->
fields
|> doc.concat_join([doc.from_string(","), doc.space])
|> wrap(open, close, trailing: ",")
}
}
// ---- ANSI -------------------------------------------------------------------
// Sadly packages like `gleam_community_ansi` cannot be used with Glam since ANSI
// escape codes need to be wrapped with `doc.zero_width_string` calls.
const reset = "\u{001b}[0m"
const green = "\u{001b}[38;5;2m"
const yellow = "\u{001b}[38;5;3m"
const blue = "\u{001b}[38;5;4m"
const magenta = "\u{001b}[38;5;5m"
const bold = "\u{001b}[1m"
const dim = "\u{001b}[2m"
fn ansi(text: String, code: String, config: Config) -> Document {
let text_doc = doc.from_string(text)
case config.style_mode {
Unstyled -> text_doc
Styled ->
doc.concat([
doc.zero_width_string(code),
text_doc,
doc.zero_width_string(reset),
])
}
}
// ---- UTILS ------------------------------------------------------------------
fn wrap(
document: Document,
open: Document,
close: Document,
trailing trailing: String,
) -> Document {
document
|> doc.prepend_docs([open, doc.soft_break])
|> doc.nest(by: 2)
|> doc.append_docs([doc.break("", trailing), close])
|> doc.group
}