## 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()!