aboutsummaryrefslogtreecommitdiff
path: root/std/prelude/format.pk
blob: 4f4746d27d03f15ab1f830bc9cda4f83ff2ffc82 (plain) (blame)
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
## std.format: Niceties around printing and debugging.
## This module is imported by default.

## The Display interface. Any type implementing `str` is printable.
## Any type that is Display must necessarily also implement Debug.
pub type Display = interface
  str(Self): str
  dbg(Self): str

## The Debug interface. Broadly implemented for every type with compiler magic.
## Types can (and should) override the generic implementations.
pub type Debug = interface
  dbg(Self): str

## Prints all of its arguments to the command line.
pub func print(params: varargs[Display]) =
  stdout.write(params.map(x => x.str).join(" "), "\n")

## Prints all of its arguments to the command line, in Debug form.
## Note: this function is special! does not count as a side effect
pub func dbg(params: varargs[Debug]) =
  stdout.write(params.map(x => x.dbg).join(" "), "\n")

## A dummy implementation of the Display interface for strings.
pub func str(self: str): str = self
## An implementation of the Debug interface for strings.
pub func dbg(self: str): str = "\"" & self & "\""

## An implementation of the Debug interface for all structs.
## Uses the special `struct` typeclass.
pub func dbg(self: struct): str =
  "{{}}".fmt(self.fields.map((key, val) => key & ":" & val.dbg))

## An implementation of the Debug interface for all tuples.
## Uses the special `tuple` typeclass.
pub func dbg(self: tuple): str =
  "({})".fmt(self.fields.map((key, val) =>
    key.map(x => x & ":").get_or("") & val.dbg).join(", "))

## An implementation of the Debug interface for all arrays and lists.
pub func dbg[T: Debug](self: Iter[T]): str =
  "[{}]".fmt(self.map(x => x.dbg).join(", "))

## The fmt macro. Builds a formatted string from its arguments.
pub macro fmt(self: static[str], args: varargs[Display]): str =
  let parts = self.split("{}")
  if parts.len != args.len + 1:
    macro_error("wrong number of arguments")
  use std.ast
  result = parts.get(0)!
  for i, arg in args:
    result &= quote(`parts` & str(`arg`) &) # fixme
  result &= parts.last()!