# # # Nim's Runtime Library # (c) Copyright 2017 Nim contributors # # See the file "copying.txt", included in this # distribution, for details about the copyright. # ##[ String `interpolation`:idx: / `format`:idx: inspired by Python's ``f``-strings. ``fmt`` vs. ``&`` ================= You can use either ``fmt`` or the unary ``&`` operator for formatting. The difference between them is subtle but important. The ``fmt"{expr}"`` syntax is more aesthetically pleasing, but it hides a small gotcha. The string is a `generalized raw string literal `_. This has some surprising effects: .. code-block:: nim import strformat let msg = "hello" doAssert fmt"{msg}\n" == "hello\\n" Because the literal is a raw string literal, the ``\n`` is not interpreted as an escape sequence. There are multiple ways to get around this, including the use of the ``&`` operator: .. code-block:: nim import strformat let msg = "hello" doAssert &"{msg}\n" == "hello\n" doAssert fmt"{msg}{'\n'}" == "hello\n" doAssert fmt("{msg}\n") == "hello\n" doAssert "{msg}\n".fmt == "hello\n" The choice of style is up to you. Formatting strings ================== .. code-block:: nim import strformat doAssert &"""{"abc":>4}""" == " abc" doAssert &"""{"abc":<4}""" == "abc " Formatting floats ================= .. code-block:: nim import strformat doAssert fmt"{-12345:08}" == "-0012345" doAssert fmt"{-1:3}" == " -1" doAssert fmt"{-1:03}" == "-01" doAssert fmt"{16:#X}" == "0x10" doAssert fmt"{123.456}" == "123.456" doAssert fmt"{123.456:>9.3f}" == " 123.456" doAssert fmt"{123.456:9.3f}" == " 123.456" doAssert fmt"{123.456:9.4f}" == " 123.4560" doAssert fmt"{123.456:>9.0f}" == " 123." doAssert fmt"{123.456:<9.4f}" == "123.4560 " doAssert fmt"{123.456:e}" == "1.234560e+02" doAssert fmt"{123.456:>13e}" == " 1.234560e+02" doAssert fmt"{123.456:13e}" == " 1.234560e+02" Implementation details ====================== An expression like ``&"{key} is {value:arg} {{z}}"`` is transformed into: .. code-block:: nim var temp = newStringOfCap(educatedCapGuess) format(key, temp) format(" is ", temp) format(value, arg, temp) format(" {z}", temp) temp Parts of the string that are enclosed in the curly braces are interpreted as Nim code, to escape an ``{`` or ``}`` double it. ``&`` delegates most of the work to an open overloaded set of ``format`` procs. The required signature for a type ``T`` that supports formatting is usually ``proc format(x: T; result: var string)`` for efficiency but can also be ``proc format(x: T): string``. ``add`` and ``$`` procs are used as the fallback implementation. This is the concrete lookup algorithm that ``&`` uses: .. code-block:: nim when compiles(format(arg, res)): format(arg, res) elif compiles(format(arg)): res.add format(arg) elif compiles(add(res, arg)): res.add(arg) else: res.add($arg) The subexpression after the colon (``arg`` in ``&"{key} is {value:arg} {{z}}"``) is an optional argument passed to ``format``. If an optional argument is present the following lookup algorithm is used: .. code-block:: nim when compiles(format(arg, option, res)): format(arg, option, res) else: res.add format(arg, option) For strings and numeric types the optional argument is a so-called "standard format specifier". Standard format specifier for strings, integers and floats ========================================================== The general form of a standard format specifier is:: [[fill]align][sign][#][0][minimumwidth][.precision][type] The square brackets ``[]`` indicate an optional element. The optional align flag can be one of the following: '<' Forces the field to be left-aligned within the available space. (This is the default for strings.) '>' Forces the field to be right-aligned within the available space. (This is the default for numbers.) '^' Forces the field to be centered within the available space. Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case. The optional 'fill' character defines the character to be used to pad the field to the minimum width. The fill character, if present, must be followed by an alignment flag. The 'sign' option is only valid for numeric types, and can be one of the following: ================= ==================================================== Sign
discard """
  file: "tclosure.nim"
  output: "1 3 6 11 20"
"""
# Test the closure implementation

proc map(n: var openarray[int], fn: proc (x: int): int {.closure}) =
  for i in 0..n.len-1: n[i] = fn(n[i])

proc foldr(n: openarray[int], fn: proc (x, y: int): int {.closure}): int =
  for i in 0..n.len-1:
    result = fn(result, n[i])

proc each(n: openarray[int], fn: proc(x: int) {.closure.}) =
  for i in 0..n.len-1:
    fn(n[i])

var
  myData: array[0..4, int] = [0, 1, 2, 3, 4]

proc testA() =
  var p = 0
  map(myData, proc (x: int): int =
                result = x + 1 shl (proc (y: int): int =
                  return y + p
                )(0)
                inc(p))

testA()

myData.each do (x: int):
  write(stdout, x)
  write(stdout, " ")

#OUT 2 4 6 8 10

type
  ITest = tuple[
    setter: proc(v: int),
    getter: proc(): int]

proc getInterf(): ITest =
  var shared: int

  return (setter: proc (x: int) = shared = x,
          getter: proc (): int = return shared)
sic tests let s = "string" check &"{0} {s}", "0 string" check &"{s[0..2].toUpperAscii}", "STR" check &"{-10:04}", "-010" check &"{-10:<04}", "-010" check &"{-10:>04}", "-010" check &"0x{10:02X}", "0x0A" check &"{10:#04X}", "0x0A" check &"""{"test":#>5}""", "#test" check &"""{"test":>5}""", " test" check &"""{"test":#^7}""", "#test##" check &"""{"test": <5}""", "test " check &"""{"test":<5}""", "test " check &"{1f:.3f}", "1.000" check &"Hello, {s}!", "Hello, string!" # Tests for identifers without parenthesis check &"{s} works{s}", "string worksstring" check &"{s:>7}", " string" doAssert(not compiles(&"{s_works}")) # parsed as identifier `s_works` # Misc general tests check &"{{}}", "{}" check &"{0}%", "0%" check &"{0}%asdf", "0%asdf" check &("\n{\"\\n\"}\n"), "\n\n\n" check &"""{"abc"}s""", "abcs" # String tests check &"""{"abc"}""", "abc" check &"""{"abc":>4}""", " abc" check &"""{"abc":<4}""", "abc " check &"""{"":>4}""", " " check &"""{"":<4}""", " " # Int tests check &"{12345}", "12345" check &"{ - 12345}", "-12345" check &"{12345:6}", " 12345" check &"{12345:>6}", " 12345" check &"{12345:4}", "12345" check &"{12345:08}", "00012345" check &"{-12345:08}", "-0012345" check &"{0:0}", "0" check &"{0:02}", "00" check &"{-1:3}", " -1" check &"{-1:03}", "-01" check &"{10}", "10" check &"{16:#X}", "0x10" check &"{16:^#7X}", " 0x10 " check &"{16:^+#7X}", " +0x10 " # Hex tests check &"{0:x}", "0" check &"{-0:x}", "0" check &"{255:x}", "ff" check &"{255:X}", "FF" check &"{-255:x}", "-ff" check &"{-255:X}", "-FF" check &"{255:x} uNaffeCteD CaSe", "ff uNaffeCteD CaSe" check &"{255:X} uNaffeCteD CaSe", "FF uNaffeCteD CaSe" check &"{255:4x}", " ff" check &"{255:04x}", "00ff" check &"{-255:4x}", " -ff" check &"{-255:04x}", "-0ff" # Float tests check &"{123.456}", "123.456" check &"{-123.456}", "-123.456" check &"{123.456:.3f}", "123.456" check &"{123.456:+.3f}", "+123.456" check &"{-123.456:+.3f}", "-123.456" check &"{-123.456:.3f}", "-123.456" check &"{123.456:1g}", "123.456" check &"{123.456:.1f}", "123.5" check &"{123.456:.0f}", "123." #check &"{123.456:.0f}", "123." check &"{123.456:>9.3f}", " 123.456" check &"{123.456:9.3f}", " 123.456" check &"{123.456:>9.4f}", " 123.4560" check &"{123.456:>9.0f}", " 123." check &"{123.456:<9.4f}", "123.4560 " # Float (scientific) tests check &"{123.456:e}", "1.234560e+02" check &"{123.456:>13e}", " 1.234560e+02" check &"{123.456:<13e}", "1.234560e+02 " check &"{123.456:.1e}", "1.2e+02" check &"{123.456:.2e}", "1.23e+02" check &"{123.456:.3e}", "1.235e+02" # Note: times.format adheres to the format protocol. Test that this # works: import times var dt = initDateTime(01, mJan, 2000, 00, 00, 00) check &"{dt:yyyy-MM-dd}", "2000-01-01" var tm = fromUnix(0) discard &"{tm}" # Unicode string tests check &"""{"αβγ"}""", "αβγ" check &"""{"αβγ":>5}""", " αβγ" check &"""{"αβγ":<5}""", "αβγ " check &"""a{"a"}α{"α"}€{"€"}𐍈{"𐍈"}""", "aaαα€€𐍈𐍈" check &"""a{"a":2}α{"α":2}€{"€":2}𐍈{"𐍈":2}""", "aa αα €€ 𐍈𐍈 " # Invalid unicode sequences should be handled as plain strings. # Invalid examples taken from: https://stackoverflow.com/a/3886015/1804173 let invalidUtf8 = [ "\xc3\x28", "\xa0\xa1", "\xe2\x28\xa1", "\xe2\x82\x28", "\xf0\x28\x8c\xbc", "\xf0\x90\x28\xbc", "\xf0\x28\x8c\x28" ] for s in invalidUtf8: check &"{s:>5}", repeat(" ", 5-s.len) & s import json doAssert fmt"{'a'} {'b'}" == "a b" echo("All tests ok")