aboutsummaryrefslogtreecommitdiff
path: root/std/default/format.pk
blob: c7d7ab8656c736a1cf1c624a06f8b8a242c52bb8 (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
## 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 also implement Debug.
pub type Display = interface
  str(Self): str
  dbg(Self): str

## The Debug interface. Broadly implemented for every type with 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.
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 =
  "{" & self.fields.map(field => field.id & field.value.dbg) & "}"

## An implementation of the Debug interface for all tuples.
## Uses the special `tuple` typeclass.
pub func dbg(self: tuple): str =
  result &= "("
  for i, field in self.fields.enumerate():
    result &= field.id.map(id => id & " = ").get_or("")
    if i != self.fields.len:
      result &= ", "
  result &= ")"

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

## The fmt macro. Builds a formatted string from its arguments.
pub macro fmt(formatted: static[str], args: varargs[Display]) =
  # if not formatted of String:
  #   macro_error("fmt must take a static string parameter!")
  ...