strformat.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ##[
  10. String `interpolation`:idx: / `format`:idx: inspired by
  11. Python's f-strings.
  12. # `fmt` vs. `&`
  13. You can use either `fmt` or the unary `&` operator for formatting. The
  14. difference between them is subtle but important.
  15. The `fmt"{expr}"` syntax is more aesthetically pleasing, but it hides a small
  16. gotcha. The string is a
  17. `generalized raw string literal <manual.html#lexical-analysis-generalized-raw-string-literals>`_.
  18. This has some surprising effects:
  19. ]##
  20. runnableExamples:
  21. let msg = "hello"
  22. assert fmt"{msg}\n" == "hello\\n"
  23. ##[
  24. Because the literal is a raw string literal, the `\n` is not interpreted as
  25. an escape sequence.
  26. There are multiple ways to get around this, including the use of the `&` operator:
  27. ]##
  28. runnableExamples:
  29. let msg = "hello"
  30. assert &"{msg}\n" == "hello\n"
  31. assert fmt"{msg}{'\n'}" == "hello\n"
  32. assert fmt("{msg}\n") == "hello\n"
  33. assert "{msg}\n".fmt == "hello\n"
  34. ##[
  35. The choice of style is up to you.
  36. # Formatting strings
  37. ]##
  38. runnableExamples:
  39. assert &"""{"abc":>4}""" == " abc"
  40. assert &"""{"abc":<4}""" == "abc "
  41. ##[
  42. # Formatting floats
  43. ]##
  44. runnableExamples:
  45. assert fmt"{-12345:08}" == "-0012345"
  46. assert fmt"{-1:3}" == " -1"
  47. assert fmt"{-1:03}" == "-01"
  48. assert fmt"{16:#X}" == "0x10"
  49. assert fmt"{123.456}" == "123.456"
  50. assert fmt"{123.456:>9.3f}" == " 123.456"
  51. assert fmt"{123.456:9.3f}" == " 123.456"
  52. assert fmt"{123.456:9.4f}" == " 123.4560"
  53. assert fmt"{123.456:>9.0f}" == " 123."
  54. assert fmt"{123.456:<9.4f}" == "123.4560 "
  55. assert fmt"{123.456:e}" == "1.234560e+02"
  56. assert fmt"{123.456:>13e}" == " 1.234560e+02"
  57. assert fmt"{123.456:13e}" == " 1.234560e+02"
  58. ##[
  59. # Expressions
  60. ]##
  61. runnableExamples:
  62. let x = 3.14
  63. assert fmt"{(if x!=0: 1.0/x else: 0):.5}" == "0.31847"
  64. assert fmt"""{(block:
  65. var res: string
  66. for i in 1..15:
  67. res.add (if i mod 15 == 0: "FizzBuzz"
  68. elif i mod 5 == 0: "Buzz"
  69. elif i mod 3 == 0: "Fizz"
  70. else: $i) & " "
  71. res)}""" == "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz "
  72. ##[
  73. # Debugging strings
  74. `fmt"{expr=}"` expands to `fmt"expr={expr}"` namely the text of the expression,
  75. an equal sign and the results of evaluated expression.
  76. ]##
  77. runnableExamples:
  78. assert fmt"{123.456=}" == "123.456=123.456"
  79. assert fmt"{123.456=:>9.3f}" == "123.456= 123.456"
  80. let x = "hello"
  81. assert fmt"{x=}" == "x=hello"
  82. assert fmt"{x =}" == "x =hello"
  83. let y = 3.1415926
  84. assert fmt"{y=:.2f}" == fmt"y={y:.2f}"
  85. assert fmt"{y=}" == fmt"y={y}"
  86. assert fmt"{y = : <8}" == fmt"y = 3.14159 "
  87. proc hello(a: string, b: float): int = 12
  88. assert fmt"{hello(x, y) = }" == "hello(x, y) = 12"
  89. assert fmt"{x.hello(y) = }" == "x.hello(y) = 12"
  90. assert fmt"{hello x, y = }" == "hello x, y = 12"
  91. ##[
  92. Note that it is space sensitive:
  93. ]##
  94. runnableExamples:
  95. let x = "12"
  96. assert fmt"{x=}" == "x=12"
  97. assert fmt"{x =:}" == "x =12"
  98. assert fmt"{x =}" == "x =12"
  99. assert fmt"{x= :}" == "x= 12"
  100. assert fmt"{x= }" == "x= 12"
  101. assert fmt"{x = :}" == "x = 12"
  102. assert fmt"{x = }" == "x = 12"
  103. assert fmt"{x = :}" == "x = 12"
  104. assert fmt"{x = }" == "x = 12"
  105. ##[
  106. # Implementation details
  107. An expression like `&"{key} is {value:arg} {{z}}"` is transformed into:
  108. .. code-block:: nim
  109. var temp = newStringOfCap(educatedCapGuess)
  110. temp.formatValue(key, "")
  111. temp.add(" is ")
  112. temp.formatValue(value, arg)
  113. temp.add(" {z}")
  114. temp
  115. Parts of the string that are enclosed in the curly braces are interpreted
  116. as Nim code. To escape a `{` or `}`, double it.
  117. Within a curly expression, however, `{`, `}`, must be escaped with a backslash.
  118. To enable evaluating Nim expressions within curlies, colons inside parentheses
  119. do not need to be escaped.
  120. ]##
  121. runnableExamples:
  122. let x = "hello"
  123. assert fmt"""{ "\{(" & x & ")\}" }""" == "{(hello)}"
  124. assert fmt"""{{({ x })}}""" == "{(hello)}"
  125. assert fmt"""{ $(\{x:1,"world":2\}) }""" == """[("hello", 1), ("world", 2)]"""
  126. ##[
  127. `&` delegates most of the work to an open overloaded set
  128. of `formatValue` procs. The required signature for a type `T` that supports
  129. formatting is usually `proc formatValue(result: var string; x: T; specifier: string)`.
  130. The subexpression after the colon
  131. (`arg` in `&"{key} is {value:arg} {{z}}"`) is optional. It will be passed as
  132. the last argument to `formatValue`. When the colon with the subexpression it is
  133. left out, an empty string will be taken instead.
  134. For strings and numeric types the optional argument is a so-called
  135. "standard format specifier".
  136. # Standard format specifiers for strings, integers and floats
  137. The general form of a standard format specifier is:
  138. [[fill]align][sign][#][0][minimumwidth][.precision][type]
  139. The square brackets `[]` indicate an optional element.
  140. The optional `align` flag can be one of the following:
  141. `<`
  142. : Forces the field to be left-aligned within the available
  143. space. (This is the default for strings.)
  144. `>`
  145. : Forces the field to be right-aligned within the available space.
  146. (This is the default for numbers.)
  147. `^`
  148. : Forces the field to be centered within the available space.
  149. Note that unless a minimum field width is defined, the field width
  150. will always be the same size as the data to fill it, so that the alignment
  151. option has no meaning in this case.
  152. The optional `fill` character defines the character to be used to pad
  153. the field to the minimum width. The fill character, if present, must be
  154. followed by an alignment flag.
  155. The `sign` option is only valid for numeric types, and can be one of the following:
  156. ================= ====================================================
  157. Sign Meaning
  158. ================= ====================================================
  159. `+` Indicates that a sign should be used for both
  160. positive as well as negative numbers.
  161. `-` Indicates that a sign should be used only for
  162. negative numbers (this is the default behavior).
  163. (space) Indicates that a leading space should be used on
  164. positive numbers.
  165. ================= ====================================================
  166. If the `#` character is present, integers use the 'alternate form' for formatting.
  167. This means that binary, octal and hexadecimal output will be prefixed
  168. with `0b`, `0o` and `0x`, respectively.
  169. `width` is a decimal integer defining the minimum field width. If not specified,
  170. then the field width will be determined by the content.
  171. If the width field is preceded by a zero (`0`) character, this enables
  172. zero-padding.
  173. The `precision` is a decimal number indicating how many digits should be displayed
  174. after the decimal point in a floating point conversion. For non-numeric types the
  175. field indicates the maximum field size - in other words, how many characters will
  176. be used from the field content. The precision is ignored for integer conversions.
  177. Finally, the `type` determines how the data should be presented.
  178. The available integer presentation types are:
  179. ================= ====================================================
  180. Type Result
  181. ================= ====================================================
  182. `b` Binary. Outputs the number in base 2.
  183. `d` Decimal Integer. Outputs the number in base 10.
  184. `o` Octal format. Outputs the number in base 8.
  185. `x` Hex format. Outputs the number in base 16, using
  186. lower-case letters for the digits above 9.
  187. `X` Hex format. Outputs the number in base 16, using
  188. uppercase letters for the digits above 9.
  189. (None) The same as `d`.
  190. ================= ====================================================
  191. The available floating point presentation types are:
  192. ================= ====================================================
  193. Type Result
  194. ================= ====================================================
  195. `e` Exponent notation. Prints the number in scientific
  196. notation using the letter `e` to indicate the
  197. exponent.
  198. `E` Exponent notation. Same as `e` except it converts
  199. the number to uppercase.
  200. `f` Fixed point. Displays the number as a fixed-point
  201. number.
  202. `F` Fixed point. Same as `f` except it converts the
  203. number to uppercase.
  204. `g` General format. This prints the number as a
  205. fixed-point number, unless the number is too
  206. large, in which case it switches to `e`
  207. exponent notation.
  208. `G` General format. Same as `g` except it switches to `E`
  209. if the number gets to large.
  210. (None) Similar to `g`, except that it prints at least one
  211. digit after the decimal point.
  212. ================= ====================================================
  213. # Limitations
  214. Because of the well defined order how templates and macros are
  215. expanded, strformat cannot expand template arguments:
  216. .. code-block:: nim
  217. template myTemplate(arg: untyped): untyped =
  218. echo "arg is: ", arg
  219. echo &"--- {arg} ---"
  220. let x = "abc"
  221. myTemplate(x)
  222. First the template `myTemplate` is expanded, where every identifier
  223. `arg` is substituted with its argument. The `arg` inside the
  224. format string is not seen by this process, because it is part of a
  225. quoted string literal. It is not an identifier yet. Then the strformat
  226. macro creates the `arg` identifier from the string literal, an
  227. identifier that cannot be resolved anymore.
  228. The workaround for this is to bind the template argument to a new local variable.
  229. .. code-block:: nim
  230. template myTemplate(arg: untyped): untyped =
  231. block:
  232. let arg1 {.inject.} = arg
  233. echo "arg is: ", arg1
  234. echo &"--- {arg1} ---"
  235. The use of `{.inject.}` here is necessary again because of template
  236. expansion order and hygienic templates. But since we generally want to
  237. keep the hygiene of `myTemplate`, and we do not want `arg1`
  238. to be injected into the context where `myTemplate` is expanded,
  239. everything is wrapped in a `block`.
  240. # Future directions
  241. A curly expression with commas in it like `{x, argA, argB}` could be
  242. transformed to `formatValue(result, x, argA, argB)` in order to support
  243. formatters that do not need to parse a custom language within a custom
  244. language but instead prefer to use Nim's existing syntax. This would also
  245. help with readability, since there is only so much you can cram into
  246. single letter DSLs.
  247. ]##
  248. import macros, parseutils, unicode
  249. import strutils except format
  250. when defined(nimPreviewSlimSystem):
  251. import std/assertions
  252. proc mkDigit(v: int, typ: char): string {.inline.} =
  253. assert(v < 26)
  254. if v < 10:
  255. result = $chr(ord('0') + v)
  256. else:
  257. result = $chr(ord(if typ == 'x': 'a' else: 'A') + v - 10)
  258. proc alignString*(s: string, minimumWidth: int; align = '\0'; fill = ' '): string =
  259. ## Aligns `s` using the `fill` char.
  260. ## This is only of interest if you want to write a custom `format` proc that
  261. ## should support the standard format specifiers.
  262. if minimumWidth == 0:
  263. result = s
  264. else:
  265. let sRuneLen = if s.validateUtf8 == -1: s.runeLen else: s.len
  266. let toFill = minimumWidth - sRuneLen
  267. if toFill <= 0:
  268. result = s
  269. elif align == '<' or align == '\0':
  270. result = s & repeat(fill, toFill)
  271. elif align == '^':
  272. let half = toFill div 2
  273. result = repeat(fill, half) & s & repeat(fill, toFill - half)
  274. else:
  275. result = repeat(fill, toFill) & s
  276. type
  277. StandardFormatSpecifier* = object ## Type that describes "standard format specifiers".
  278. fill*, align*: char ## Desired fill and alignment.
  279. sign*: char ## Desired sign.
  280. alternateForm*: bool ## Whether to prefix binary, octal and hex numbers
  281. ## with `0b`, `0o`, `0x`.
  282. padWithZero*: bool ## Whether to pad with zeros rather than spaces.
  283. minimumWidth*, precision*: int ## Desired minimum width and precision.
  284. typ*: char ## Type like 'f', 'g' or 'd'.
  285. endPosition*: int ## End position in the format specifier after
  286. ## `parseStandardFormatSpecifier` returned.
  287. proc formatInt(n: SomeNumber; radix: int; spec: StandardFormatSpecifier): string =
  288. ## Converts `n` to a string. If `n` is `SomeFloat`, it casts to `int64`.
  289. ## Conversion is done using `radix`. If result's length is less than
  290. ## `minimumWidth`, it aligns result to the right or left (depending on `a`)
  291. ## with the `fill` char.
  292. when n is SomeUnsignedInt:
  293. var v = n.uint64
  294. let negative = false
  295. else:
  296. let n = n.int64
  297. let negative = n < 0
  298. var v =
  299. if negative:
  300. # `uint64(-n)`, but accounts for `n == low(int64)`
  301. uint64(not n) + 1
  302. else:
  303. uint64(n)
  304. var xx = ""
  305. if spec.alternateForm:
  306. case spec.typ
  307. of 'X': xx = "0x"
  308. of 'x': xx = "0x"
  309. of 'b': xx = "0b"
  310. of 'o': xx = "0o"
  311. else: discard
  312. if v == 0:
  313. result = "0"
  314. else:
  315. result = ""
  316. while v > typeof(v)(0):
  317. let d = v mod typeof(v)(radix)
  318. v = v div typeof(v)(radix)
  319. result.add(mkDigit(d.int, spec.typ))
  320. for idx in 0..<(result.len div 2):
  321. swap result[idx], result[result.len - idx - 1]
  322. if spec.padWithZero:
  323. let sign = negative or spec.sign != '-'
  324. let toFill = spec.minimumWidth - result.len - xx.len - ord(sign)
  325. if toFill > 0:
  326. result = repeat('0', toFill) & result
  327. if negative:
  328. result = "-" & xx & result
  329. elif spec.sign != '-':
  330. result = spec.sign & xx & result
  331. else:
  332. result = xx & result
  333. if spec.align == '<':
  334. for i in result.len..<spec.minimumWidth:
  335. result.add(spec.fill)
  336. else:
  337. let toFill = spec.minimumWidth - result.len
  338. if spec.align == '^':
  339. let half = toFill div 2
  340. result = repeat(spec.fill, half) & result & repeat(spec.fill, toFill - half)
  341. else:
  342. if toFill > 0:
  343. result = repeat(spec.fill, toFill) & result
  344. proc parseStandardFormatSpecifier*(s: string; start = 0;
  345. ignoreUnknownSuffix = false): StandardFormatSpecifier =
  346. ## An exported helper proc that parses the "standard format specifiers",
  347. ## as specified by the grammar:
  348. ##
  349. ## [[fill]align][sign][#][0][minimumwidth][.precision][type]
  350. ##
  351. ## This is only of interest if you want to write a custom `format` proc that
  352. ## should support the standard format specifiers. If `ignoreUnknownSuffix` is true,
  353. ## an unknown suffix after the `type` field is not an error.
  354. const alignChars = {'<', '>', '^'}
  355. result.fill = ' '
  356. result.align = '\0'
  357. result.sign = '-'
  358. var i = start
  359. if i + 1 < s.len and s[i+1] in alignChars:
  360. result.fill = s[i]
  361. result.align = s[i+1]
  362. inc i, 2
  363. elif i < s.len and s[i] in alignChars:
  364. result.align = s[i]
  365. inc i
  366. if i < s.len and s[i] in {'-', '+', ' '}:
  367. result.sign = s[i]
  368. inc i
  369. if i < s.len and s[i] == '#':
  370. result.alternateForm = true
  371. inc i
  372. if i + 1 < s.len and s[i] == '0' and s[i+1] in {'0'..'9'}:
  373. result.padWithZero = true
  374. inc i
  375. let parsedLength = parseSaturatedNatural(s, result.minimumWidth, i)
  376. inc i, parsedLength
  377. if i < s.len and s[i] == '.':
  378. inc i
  379. let parsedLengthB = parseSaturatedNatural(s, result.precision, i)
  380. inc i, parsedLengthB
  381. else:
  382. result.precision = -1
  383. if i < s.len and s[i] in {'A'..'Z', 'a'..'z'}:
  384. result.typ = s[i]
  385. inc i
  386. result.endPosition = i
  387. if i != s.len and not ignoreUnknownSuffix:
  388. raise newException(ValueError,
  389. "invalid format string, cannot parse: " & s[i..^1])
  390. proc formatValue*[T: SomeInteger](result: var string; value: T;
  391. specifier: string) =
  392. ## Standard format implementation for `SomeInteger`. It makes little
  393. ## sense to call this directly, but it is required to exist
  394. ## by the `&` macro.
  395. if specifier.len == 0:
  396. result.add $value
  397. return
  398. let spec = parseStandardFormatSpecifier(specifier)
  399. var radix = 10
  400. case spec.typ
  401. of 'x', 'X': radix = 16
  402. of 'd', '\0': discard
  403. of 'b': radix = 2
  404. of 'o': radix = 8
  405. else:
  406. raise newException(ValueError,
  407. "invalid type in format string for number, expected one " &
  408. " of 'x', 'X', 'b', 'd', 'o' but got: " & spec.typ)
  409. result.add formatInt(value, radix, spec)
  410. proc formatValue*(result: var string; value: SomeFloat; specifier: string) =
  411. ## Standard format implementation for `SomeFloat`. It makes little
  412. ## sense to call this directly, but it is required to exist
  413. ## by the `&` macro.
  414. if specifier.len == 0:
  415. result.add $value
  416. return
  417. let spec = parseStandardFormatSpecifier(specifier)
  418. var fmode = ffDefault
  419. case spec.typ
  420. of 'e', 'E':
  421. fmode = ffScientific
  422. of 'f', 'F':
  423. fmode = ffDecimal
  424. of 'g', 'G':
  425. fmode = ffDefault
  426. of '\0': discard
  427. else:
  428. raise newException(ValueError,
  429. "invalid type in format string for number, expected one " &
  430. " of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
  431. var f = formatBiggestFloat(value, fmode, spec.precision)
  432. var sign = false
  433. if value >= 0.0:
  434. if spec.sign != '-':
  435. sign = true
  436. if value == 0.0:
  437. if 1.0 / value == Inf:
  438. # only insert the sign if value != negZero
  439. f.insert($spec.sign, 0)
  440. else:
  441. f.insert($spec.sign, 0)
  442. else:
  443. sign = true
  444. if spec.padWithZero:
  445. var signStr = ""
  446. if sign:
  447. signStr = $f[0]
  448. f = f[1..^1]
  449. let toFill = spec.minimumWidth - f.len - ord(sign)
  450. if toFill > 0:
  451. f = repeat('0', toFill) & f
  452. if sign:
  453. f = signStr & f
  454. # the default for numbers is right-alignment:
  455. let align = if spec.align == '\0': '>' else: spec.align
  456. let res = alignString(f, spec.minimumWidth, align, spec.fill)
  457. if spec.typ in {'A'..'Z'}:
  458. result.add toUpperAscii(res)
  459. else:
  460. result.add res
  461. proc formatValue*(result: var string; value: string; specifier: string) =
  462. ## Standard format implementation for `string`. It makes little
  463. ## sense to call this directly, but it is required to exist
  464. ## by the `&` macro.
  465. let spec = parseStandardFormatSpecifier(specifier)
  466. var value = value
  467. case spec.typ
  468. of 's', '\0': discard
  469. else:
  470. raise newException(ValueError,
  471. "invalid type in format string for string, expected 's', but got " &
  472. spec.typ)
  473. if spec.precision != -1:
  474. if spec.precision < runeLen(value):
  475. setLen(value, runeOffset(value, spec.precision))
  476. result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
  477. proc formatValue[T: not SomeInteger](result: var string; value: T; specifier: string) =
  478. mixin `$`
  479. formatValue(result, $value, specifier)
  480. template formatValue(result: var string; value: char; specifier: string) =
  481. result.add value
  482. template formatValue(result: var string; value: cstring; specifier: string) =
  483. result.add value
  484. proc strformatImpl(f: string; openChar, closeChar: char): NimNode =
  485. template missingCloseChar =
  486. error("invalid format string: missing closing character '" & closeChar & "'")
  487. if openChar == ':' or closeChar == ':':
  488. error "openChar and closeChar must not be ':'"
  489. var i = 0
  490. let res = genSym(nskVar, "fmtRes")
  491. result = newNimNode(nnkStmtListExpr)
  492. # XXX: https://github.com/nim-lang/Nim/issues/8405
  493. # When compiling with -d:useNimRtl, certain procs such as `count` from the strutils
  494. # module are not accessible at compile-time:
  495. let expectedGrowth = when defined(useNimRtl): 0 else: count(f, openChar) * 10
  496. result.add newVarStmt(res, newCall(bindSym"newStringOfCap",
  497. newLit(f.len + expectedGrowth)))
  498. var strlit = ""
  499. while i < f.len:
  500. if f[i] == openChar:
  501. inc i
  502. if f[i] == openChar:
  503. inc i
  504. strlit.add openChar
  505. else:
  506. if strlit.len > 0:
  507. result.add newCall(bindSym"add", res, newLit(strlit))
  508. strlit = ""
  509. var subexpr = ""
  510. var inParens = 0
  511. var inSingleQuotes = false
  512. var inDoubleQuotes = false
  513. template notEscaped:bool = f[i-1]!='\\'
  514. while i < f.len and f[i] != closeChar and (f[i] != ':' or inParens != 0):
  515. case f[i]
  516. of '\\':
  517. if i < f.len-1 and f[i+1] in {openChar,closeChar,':'}: inc i
  518. of '\'':
  519. if not inDoubleQuotes and notEscaped: inSingleQuotes = not inSingleQuotes
  520. of '\"':
  521. if notEscaped: inDoubleQuotes = not inDoubleQuotes
  522. of '(':
  523. if not (inSingleQuotes or inDoubleQuotes): inc inParens
  524. of ')':
  525. if not (inSingleQuotes or inDoubleQuotes): dec inParens
  526. of '=':
  527. let start = i
  528. inc i
  529. i += f.skipWhitespace(i)
  530. if i == f.len:
  531. missingCloseChar
  532. if f[i] == closeChar or f[i] == ':':
  533. result.add newCall(bindSym"add", res, newLit(subexpr & f[start ..< i]))
  534. else:
  535. subexpr.add f[start ..< i]
  536. continue
  537. else: discard
  538. subexpr.add f[i]
  539. inc i
  540. if i == f.len:
  541. missingCloseChar
  542. var x: NimNode
  543. try:
  544. x = parseExpr(subexpr)
  545. except ValueError as e:
  546. error("could not parse `$#` in `$#`.\n$#" % [subexpr, f, e.msg])
  547. let formatSym = bindSym("formatValue", brOpen)
  548. var options = ""
  549. if f[i] == ':':
  550. inc i
  551. while i < f.len and f[i] != closeChar:
  552. options.add f[i]
  553. inc i
  554. if i == f.len:
  555. missingCloseChar
  556. if f[i] == closeChar:
  557. inc i
  558. result.add newCall(formatSym, res, x, newLit(options))
  559. elif f[i] == closeChar:
  560. if i<f.len-1 and f[i+1] == closeChar:
  561. strlit.add closeChar
  562. inc i, 2
  563. else:
  564. doAssert false, "invalid format string: '$1' instead of '$1$1'" % $closeChar
  565. inc i
  566. else:
  567. strlit.add f[i]
  568. inc i
  569. if strlit.len > 0:
  570. result.add newCall(bindSym"add", res, newLit(strlit))
  571. result.add res
  572. when defined(debugFmtDsl):
  573. echo repr result
  574. macro fmt*(pattern: static string; openChar: static char, closeChar: static char): string =
  575. ## Interpolates `pattern` using symbols in scope.
  576. runnableExamples:
  577. let x = 7
  578. assert "var is {x * 2}".fmt == "var is 14"
  579. assert "var is {{x}}".fmt == "var is {x}" # escape via doubling
  580. const s = "foo: {x}"
  581. assert s.fmt == "foo: 7" # also works with const strings
  582. assert fmt"\n" == r"\n" # raw string literal
  583. assert "\n".fmt == "\n" # regular literal (likewise with `fmt("\n")` or `fmt "\n"`)
  584. runnableExamples:
  585. # custom `openChar`, `closeChar`
  586. let x = 7
  587. assert "<x>".fmt('<', '>') == "7"
  588. assert "<<<x>>>".fmt('<', '>') == "<7>"
  589. assert "`x`".fmt('`', '`') == "7"
  590. strformatImpl(pattern, openChar, closeChar)
  591. template fmt*(pattern: static string): untyped =
  592. ## Alias for `fmt(pattern, '{', '}')`.
  593. fmt(pattern, '{', '}')
  594. macro `&`*(pattern: string{lit}): string =
  595. ## `&pattern` is the same as `pattern.fmt`.
  596. ## For a specification of the `&` macro, see the module level documentation.
  597. # pending bug #18275, bug #18278, use `pattern: static string`
  598. # consider deprecating this, it's redundant with `fmt` and `fmt` is strictly
  599. # more flexible, readable (no confusion with the binary `&`), self-documenting,
  600. # not to mention #18275, bug #18278.
  601. runnableExamples:
  602. let x = 7
  603. assert &"{x}\n" == "7\n" # regular string literal
  604. assert &"{x}\n" == "{x}\n".fmt # `fmt` can be used instead
  605. assert &"{x}\n" != fmt"{x}\n" # see `fmt` docs, this would use a raw string literal
  606. strformatImpl(pattern.strVal, '{', '}')