strformat.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. ```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. ```
  116. Parts of the string that are enclosed in the curly braces are interpreted
  117. as Nim code. To escape a `{` or `}`, double it.
  118. Within a curly expression, however, `{`, `}`, must be escaped with a backslash.
  119. To enable evaluating Nim expressions within curlies, colons inside parentheses
  120. do not need to be escaped.
  121. ]##
  122. runnableExamples:
  123. let x = "hello"
  124. assert fmt"""{ "\{(" & x & ")\}" }""" == "{(hello)}"
  125. assert fmt"""{{({ x })}}""" == "{(hello)}"
  126. assert fmt"""{ $(\{x:1,"world":2\}) }""" == """[("hello", 1), ("world", 2)]"""
  127. ##[
  128. `&` delegates most of the work to an open overloaded set
  129. of `formatValue` procs. The required signature for a type `T` that supports
  130. formatting is usually `proc formatValue(result: var string; x: T; specifier: string)`.
  131. The subexpression after the colon
  132. (`arg` in `&"{key} is {value:arg} {{z}}"`) is optional. It will be passed as
  133. the last argument to `formatValue`. When the colon with the subexpression it is
  134. left out, an empty string will be taken instead.
  135. For strings and numeric types the optional argument is a so-called
  136. "standard format specifier".
  137. # Standard format specifiers for strings, integers and floats
  138. The general form of a standard format specifier is:
  139. [[fill]align][sign][#][0][minimumwidth][.precision][type]
  140. The square brackets `[]` indicate an optional element.
  141. The optional `align` flag can be one of the following:
  142. `<`
  143. : Forces the field to be left-aligned within the available
  144. space. (This is the default for strings.)
  145. `>`
  146. : Forces the field to be right-aligned within the available space.
  147. (This is the default for numbers.)
  148. `^`
  149. : Forces the field to be centered within the available space.
  150. Note that unless a minimum field width is defined, the field width
  151. will always be the same size as the data to fill it, so that the alignment
  152. option has no meaning in this case.
  153. The optional `fill` character defines the character to be used to pad
  154. the field to the minimum width. The fill character, if present, must be
  155. followed by an alignment flag.
  156. The `sign` option is only valid for numeric types, and can be one of the following:
  157. ================= ====================================================
  158. Sign Meaning
  159. ================= ====================================================
  160. `+` Indicates that a sign should be used for both
  161. positive as well as negative numbers.
  162. `-` Indicates that a sign should be used only for
  163. negative numbers (this is the default behavior).
  164. (space) Indicates that a leading space should be used on
  165. positive numbers.
  166. ================= ====================================================
  167. If the `#` character is present, integers use the 'alternate form' for formatting.
  168. This means that binary, octal and hexadecimal output will be prefixed
  169. with `0b`, `0o` and `0x`, respectively.
  170. `width` is a decimal integer defining the minimum field width. If not specified,
  171. then the field width will be determined by the content.
  172. If the width field is preceded by a zero (`0`) character, this enables
  173. zero-padding.
  174. The `precision` is a decimal number indicating how many digits should be displayed
  175. after the decimal point in a floating point conversion. For non-numeric types the
  176. field indicates the maximum field size - in other words, how many characters will
  177. be used from the field content. The precision is ignored for integer conversions.
  178. Finally, the `type` determines how the data should be presented.
  179. The available integer presentation types are:
  180. ================= ====================================================
  181. Type Result
  182. ================= ====================================================
  183. `b` Binary. Outputs the number in base 2.
  184. `d` Decimal Integer. Outputs the number in base 10.
  185. `o` Octal format. Outputs the number in base 8.
  186. `x` Hex format. Outputs the number in base 16, using
  187. lower-case letters for the digits above 9.
  188. `X` Hex format. Outputs the number in base 16, using
  189. uppercase letters for the digits above 9.
  190. (None) The same as `d`.
  191. ================= ====================================================
  192. The available floating point presentation types are:
  193. ================= ====================================================
  194. Type Result
  195. ================= ====================================================
  196. `e` Exponent notation. Prints the number in scientific
  197. notation using the letter `e` to indicate the
  198. exponent.
  199. `E` Exponent notation. Same as `e` except it converts
  200. the number to uppercase.
  201. `f` Fixed point. Displays the number as a fixed-point
  202. number.
  203. `F` Fixed point. Same as `f` except it converts the
  204. number to uppercase.
  205. `g` General format. This prints the number as a
  206. fixed-point number, unless the number is too
  207. large, in which case it switches to `e`
  208. exponent notation.
  209. `G` General format. Same as `g` except it switches to `E`
  210. if the number gets to large.
  211. `i` Complex General format. This is only supported for
  212. complex numbers, which it prints using the mathematical
  213. (RE+IMj) format. The real and imaginary parts are printed
  214. using the general format `g` by default, but it is
  215. possible to combine this format with one of the other
  216. formats (e.g `jf`).
  217. (None) Similar to `g`, except that it prints at least one
  218. digit after the decimal point.
  219. ================= ====================================================
  220. # Limitations
  221. Because of the well defined order how templates and macros are
  222. expanded, strformat cannot expand template arguments:
  223. ```nim
  224. template myTemplate(arg: untyped): untyped =
  225. echo "arg is: ", arg
  226. echo &"--- {arg} ---"
  227. let x = "abc"
  228. myTemplate(x)
  229. ```
  230. First the template `myTemplate` is expanded, where every identifier
  231. `arg` is substituted with its argument. The `arg` inside the
  232. format string is not seen by this process, because it is part of a
  233. quoted string literal. It is not an identifier yet. Then the strformat
  234. macro creates the `arg` identifier from the string literal, an
  235. identifier that cannot be resolved anymore.
  236. The workaround for this is to bind the template argument to a new local variable.
  237. ```nim
  238. template myTemplate(arg: untyped): untyped =
  239. block:
  240. let arg1 {.inject.} = arg
  241. echo "arg is: ", arg1
  242. echo &"--- {arg1} ---"
  243. ```
  244. The use of `{.inject.}` here is necessary again because of template
  245. expansion order and hygienic templates. But since we generally want to
  246. keep the hygiene of `myTemplate`, and we do not want `arg1`
  247. to be injected into the context where `myTemplate` is expanded,
  248. everything is wrapped in a `block`.
  249. # Future directions
  250. A curly expression with commas in it like `{x, argA, argB}` could be
  251. transformed to `formatValue(result, x, argA, argB)` in order to support
  252. formatters that do not need to parse a custom language within a custom
  253. language but instead prefer to use Nim's existing syntax. This would also
  254. help with readability, since there is only so much you can cram into
  255. single letter DSLs.
  256. ]##
  257. import std/[macros, parseutils, unicode]
  258. import std/strutils except format
  259. when defined(nimPreviewSlimSystem):
  260. import std/assertions
  261. proc mkDigit(v: int, typ: char): string {.inline.} =
  262. assert(v < 26)
  263. if v < 10:
  264. result = $chr(ord('0') + v)
  265. else:
  266. result = $chr(ord(if typ == 'x': 'a' else: 'A') + v - 10)
  267. proc alignString*(s: string, minimumWidth: int; align = '\0'; fill = ' '): string =
  268. ## Aligns `s` using the `fill` char.
  269. ## This is only of interest if you want to write a custom `format` proc that
  270. ## should support the standard format specifiers.
  271. if minimumWidth == 0:
  272. result = s
  273. else:
  274. let sRuneLen = if s.validateUtf8 == -1: s.runeLen else: s.len
  275. let toFill = minimumWidth - sRuneLen
  276. if toFill <= 0:
  277. result = s
  278. elif align == '<' or align == '\0':
  279. result = s & repeat(fill, toFill)
  280. elif align == '^':
  281. let half = toFill div 2
  282. result = repeat(fill, half) & s & repeat(fill, toFill - half)
  283. else:
  284. result = repeat(fill, toFill) & s
  285. type
  286. StandardFormatSpecifier* = object ## Type that describes "standard format specifiers".
  287. fill*, align*: char ## Desired fill and alignment.
  288. sign*: char ## Desired sign.
  289. alternateForm*: bool ## Whether to prefix binary, octal and hex numbers
  290. ## with `0b`, `0o`, `0x`.
  291. padWithZero*: bool ## Whether to pad with zeros rather than spaces.
  292. minimumWidth*, precision*: int ## Desired minimum width and precision.
  293. typ*: char ## Type like 'f', 'g' or 'd'.
  294. endPosition*: int ## End position in the format specifier after
  295. ## `parseStandardFormatSpecifier` returned.
  296. proc formatInt(n: SomeNumber; radix: int; spec: StandardFormatSpecifier): string =
  297. ## Converts `n` to a string. If `n` is `SomeFloat`, it casts to `int64`.
  298. ## Conversion is done using `radix`. If result's length is less than
  299. ## `minimumWidth`, it aligns result to the right or left (depending on `a`)
  300. ## with the `fill` char.
  301. when n is SomeUnsignedInt:
  302. var v = n.uint64
  303. let negative = false
  304. else:
  305. let n = n.int64
  306. let negative = n < 0
  307. var v =
  308. if negative:
  309. # `uint64(-n)`, but accounts for `n == low(int64)`
  310. uint64(not n) + 1
  311. else:
  312. uint64(n)
  313. var xx = ""
  314. if spec.alternateForm:
  315. case spec.typ
  316. of 'X': xx = "0x"
  317. of 'x': xx = "0x"
  318. of 'b': xx = "0b"
  319. of 'o': xx = "0o"
  320. else: discard
  321. if v == 0:
  322. result = "0"
  323. else:
  324. result = ""
  325. while v > typeof(v)(0):
  326. let d = v mod typeof(v)(radix)
  327. v = v div typeof(v)(radix)
  328. result.add(mkDigit(d.int, spec.typ))
  329. for idx in 0..<(result.len div 2):
  330. swap result[idx], result[result.len - idx - 1]
  331. if spec.padWithZero:
  332. let sign = negative or spec.sign != '-'
  333. let toFill = spec.minimumWidth - result.len - xx.len - ord(sign)
  334. if toFill > 0:
  335. result = repeat('0', toFill) & result
  336. if negative:
  337. result = "-" & xx & result
  338. elif spec.sign != '-':
  339. result = spec.sign & xx & result
  340. else:
  341. result = xx & result
  342. if spec.align == '<':
  343. for i in result.len..<spec.minimumWidth:
  344. result.add(spec.fill)
  345. else:
  346. let toFill = spec.minimumWidth - result.len
  347. if spec.align == '^':
  348. let half = toFill div 2
  349. result = repeat(spec.fill, half) & result & repeat(spec.fill, toFill - half)
  350. else:
  351. if toFill > 0:
  352. result = repeat(spec.fill, toFill) & result
  353. proc parseStandardFormatSpecifier*(s: string; start = 0;
  354. ignoreUnknownSuffix = false): StandardFormatSpecifier =
  355. ## An exported helper proc that parses the "standard format specifiers",
  356. ## as specified by the grammar:
  357. ##
  358. ## [[fill]align][sign][#][0][minimumwidth][.precision][type]
  359. ##
  360. ## This is only of interest if you want to write a custom `format` proc that
  361. ## should support the standard format specifiers. If `ignoreUnknownSuffix` is true,
  362. ## an unknown suffix after the `type` field is not an error.
  363. const alignChars = {'<', '>', '^'}
  364. result.fill = ' '
  365. result.align = '\0'
  366. result.sign = '-'
  367. var i = start
  368. if i + 1 < s.len and s[i+1] in alignChars:
  369. result.fill = s[i]
  370. result.align = s[i+1]
  371. inc i, 2
  372. elif i < s.len and s[i] in alignChars:
  373. result.align = s[i]
  374. inc i
  375. if i < s.len and s[i] in {'-', '+', ' '}:
  376. result.sign = s[i]
  377. inc i
  378. if i < s.len and s[i] == '#':
  379. result.alternateForm = true
  380. inc i
  381. if i + 1 < s.len and s[i] == '0' and s[i+1] in {'0'..'9'}:
  382. result.padWithZero = true
  383. inc i
  384. let parsedLength = parseSaturatedNatural(s, result.minimumWidth, i)
  385. inc i, parsedLength
  386. if i < s.len and s[i] == '.':
  387. inc i
  388. let parsedLengthB = parseSaturatedNatural(s, result.precision, i)
  389. inc i, parsedLengthB
  390. else:
  391. result.precision = -1
  392. if i < s.len and s[i] in {'A'..'Z', 'a'..'z'}:
  393. result.typ = s[i]
  394. inc i
  395. result.endPosition = i
  396. if i != s.len and not ignoreUnknownSuffix:
  397. raise newException(ValueError,
  398. "invalid format string, cannot parse: " & s[i..^1])
  399. proc toRadix(typ: char): int =
  400. case typ
  401. of 'x', 'X': 16
  402. of 'd', '\0': 10
  403. of 'o': 8
  404. of 'b': 2
  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: " & typ)
  409. proc formatValue*[T: SomeInteger](result: var string; value: T;
  410. specifier: static string) =
  411. ## Standard format implementation for `SomeInteger`. It makes little
  412. ## sense to call this directly, but it is required to exist
  413. ## by the `&` macro.
  414. when specifier.len == 0:
  415. result.add $value
  416. else:
  417. const
  418. spec = parseStandardFormatSpecifier(specifier)
  419. radix = toRadix(spec.typ)
  420. result.add formatInt(value, radix, spec)
  421. proc formatValue*[T: SomeInteger](result: var string; value: T;
  422. specifier: string) =
  423. ## Standard format implementation for `SomeInteger`. It makes little
  424. ## sense to call this directly, but it is required to exist
  425. ## by the `&` macro.
  426. if specifier.len == 0:
  427. result.add $value
  428. else:
  429. let
  430. spec = parseStandardFormatSpecifier(specifier)
  431. radix = toRadix(spec.typ)
  432. result.add formatInt(value, radix, spec)
  433. proc formatFloat(
  434. result: var string, value: SomeFloat, fmode: FloatFormatMode,
  435. spec: StandardFormatSpecifier) =
  436. var f = formatBiggestFloat(value, fmode, spec.precision)
  437. var sign = false
  438. if value >= 0.0:
  439. if spec.sign != '-':
  440. sign = true
  441. if value == 0.0:
  442. if 1.0 / value == Inf:
  443. # only insert the sign if value != negZero
  444. f.insert($spec.sign, 0)
  445. else:
  446. f.insert($spec.sign, 0)
  447. else:
  448. sign = true
  449. if spec.padWithZero:
  450. var signStr = ""
  451. if sign:
  452. signStr = $f[0]
  453. f = f[1..^1]
  454. let toFill = spec.minimumWidth - f.len - ord(sign)
  455. if toFill > 0:
  456. f = repeat('0', toFill) & f
  457. if sign:
  458. f = signStr & f
  459. # the default for numbers is right-alignment:
  460. let align = if spec.align == '\0': '>' else: spec.align
  461. let res = alignString(f, spec.minimumWidth, align, spec.fill)
  462. if spec.typ in {'A'..'Z'}:
  463. result.add toUpperAscii(res)
  464. else:
  465. result.add res
  466. proc toFloatFormatMode(typ: char): FloatFormatMode =
  467. case typ
  468. of 'e', 'E': ffScientific
  469. of 'f', 'F': ffDecimal
  470. of 'g', 'G': ffDefault
  471. of '\0': ffDefault
  472. else:
  473. raise newException(ValueError,
  474. "invalid type in format string for number, expected one " &
  475. " of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & typ)
  476. proc formatValue*(result: var string; value: SomeFloat; specifier: static string) =
  477. ## Standard format implementation for `SomeFloat`. It makes little
  478. ## sense to call this directly, but it is required to exist
  479. ## by the `&` macro.
  480. when specifier.len == 0:
  481. result.add $value
  482. else:
  483. const
  484. spec = parseStandardFormatSpecifier(specifier)
  485. fmode = toFloatFormatMode(spec.typ)
  486. formatFloat(result, value, fmode, spec)
  487. proc formatValue*(result: var string; value: SomeFloat; specifier: string) =
  488. ## Standard format implementation for `SomeFloat`. It makes little
  489. ## sense to call this directly, but it is required to exist
  490. ## by the `&` macro.
  491. if specifier.len == 0:
  492. result.add $value
  493. else:
  494. let
  495. spec = parseStandardFormatSpecifier(specifier)
  496. fmode = toFloatFormatMode(spec.typ)
  497. formatFloat(result, value, fmode, spec)
  498. proc formatValue*(result: var string; value: string; specifier: static string) =
  499. ## Standard format implementation for `string`. It makes little
  500. ## sense to call this directly, but it is required to exist
  501. ## by the `&` macro.
  502. const spec = parseStandardFormatSpecifier(specifier)
  503. var value =
  504. when spec.typ in {'s', '\0'}: value
  505. else: static:
  506. raise newException(ValueError,
  507. "invalid type in format string for string, expected 's', but got " &
  508. spec.typ)
  509. when spec.precision != -1:
  510. if spec.precision < runeLen(value):
  511. const precision = cast[Natural](spec.precision)
  512. setLen(value, Natural(runeOffset(value, precision)))
  513. result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
  514. proc formatValue*(result: var string; value: string; specifier: string) =
  515. ## Standard format implementation for `string`. It makes little
  516. ## sense to call this directly, but it is required to exist
  517. ## by the `&` macro.
  518. let spec = parseStandardFormatSpecifier(specifier)
  519. var value =
  520. if spec.typ in {'s', '\0'}: value
  521. else:
  522. raise newException(ValueError,
  523. "invalid type in format string for string, expected 's', but got " &
  524. spec.typ)
  525. if spec.precision != -1:
  526. if spec.precision < runeLen(value):
  527. let precision = cast[Natural](spec.precision)
  528. setLen(value, Natural(runeOffset(value, precision)))
  529. result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
  530. proc formatValue[T: not SomeInteger](result: var string; value: T; specifier: static string) =
  531. mixin `$`
  532. formatValue(result, $value, specifier)
  533. proc formatValue[T: not SomeInteger](result: var string; value: T; specifier: string) =
  534. mixin `$`
  535. formatValue(result, $value, specifier)
  536. template formatValue(result: var string; value: char; specifier: string) =
  537. result.add value
  538. template formatValue(result: var string; value: cstring; specifier: string) =
  539. result.add value
  540. proc strformatImpl(f: string; openChar, closeChar: char,
  541. lineInfoNode: NimNode = nil): NimNode =
  542. template missingCloseChar =
  543. error("invalid format string: missing closing character '" & closeChar & "'")
  544. if openChar == ':' or closeChar == ':':
  545. error "openChar and closeChar must not be ':'"
  546. var i = 0
  547. let res = genSym(nskVar, "fmtRes")
  548. result = newNimNode(nnkStmtListExpr, lineInfoNode)
  549. # XXX: https://github.com/nim-lang/Nim/issues/8405
  550. # When compiling with -d:useNimRtl, certain procs such as `count` from the strutils
  551. # module are not accessible at compile-time:
  552. let expectedGrowth = when defined(useNimRtl): 0 else: count(f, openChar) * 10
  553. result.add newVarStmt(res, newCall(bindSym"newStringOfCap",
  554. newLit(f.len + expectedGrowth)))
  555. var strlit = ""
  556. while i < f.len:
  557. if f[i] == openChar:
  558. inc i
  559. if f[i] == openChar:
  560. inc i
  561. strlit.add openChar
  562. else:
  563. if strlit.len > 0:
  564. result.add newCall(bindSym"add", res, newLit(strlit))
  565. strlit = ""
  566. var subexpr = ""
  567. var inParens = 0
  568. var inSingleQuotes = false
  569. var inDoubleQuotes = false
  570. template notEscaped:bool = f[i-1]!='\\'
  571. while i < f.len and f[i] != closeChar and (f[i] != ':' or inParens != 0):
  572. case f[i]
  573. of '\\':
  574. if i < f.len-1 and f[i+1] in {openChar,closeChar,':'}: inc i
  575. of '\'':
  576. if not inDoubleQuotes and notEscaped: inSingleQuotes = not inSingleQuotes
  577. of '\"':
  578. if notEscaped: inDoubleQuotes = not inDoubleQuotes
  579. of '(':
  580. if not (inSingleQuotes or inDoubleQuotes): inc inParens
  581. of ')':
  582. if not (inSingleQuotes or inDoubleQuotes): dec inParens
  583. of '=':
  584. let start = i
  585. inc i
  586. i += f.skipWhitespace(i)
  587. if i == f.len:
  588. missingCloseChar
  589. if f[i] == closeChar or f[i] == ':':
  590. result.add newCall(bindSym"add", res, newLit(subexpr & f[start ..< i]))
  591. else:
  592. subexpr.add f[start ..< i]
  593. continue
  594. else: discard
  595. subexpr.add f[i]
  596. inc i
  597. if i == f.len:
  598. missingCloseChar
  599. var x: NimNode
  600. try:
  601. x = parseExpr(subexpr)
  602. except ValueError as e:
  603. error("could not parse `$#` in `$#`.\n$#" % [subexpr, f, e.msg])
  604. x.copyLineInfo(lineInfoNode)
  605. let formatSym = bindSym("formatValue", brOpen)
  606. var options = ""
  607. if f[i] == ':':
  608. inc i
  609. while i < f.len and f[i] != closeChar:
  610. options.add f[i]
  611. inc i
  612. if i == f.len:
  613. missingCloseChar
  614. if f[i] == closeChar:
  615. inc i
  616. result.add newCall(formatSym, res, x, newLit(options))
  617. elif f[i] == closeChar:
  618. if i<f.len-1 and f[i+1] == closeChar:
  619. strlit.add closeChar
  620. inc i, 2
  621. else:
  622. raiseAssert "invalid format string: '$1' instead of '$1$1'" % $closeChar
  623. else:
  624. strlit.add f[i]
  625. inc i
  626. if strlit.len > 0:
  627. result.add newCall(bindSym"add", res, newLit(strlit))
  628. result.add res
  629. # workaround for #20381
  630. var blockExpr = newNimNode(nnkBlockExpr, lineInfoNode)
  631. blockExpr.add(newEmptyNode())
  632. blockExpr.add(result)
  633. result = blockExpr
  634. when defined(debugFmtDsl):
  635. echo repr result
  636. macro fmt(pattern: static string; openChar: static char, closeChar: static char, lineInfoNode: untyped): string =
  637. ## version of `fmt` with dummy untyped param for line info
  638. strformatImpl(pattern, openChar, closeChar, lineInfoNode)
  639. when not defined(nimHasCallsitePragma):
  640. {.pragma: callsite.}
  641. template fmt*(pattern: static string; openChar: static char, closeChar: static char): string {.callsite.} =
  642. ## Interpolates `pattern` using symbols in scope.
  643. runnableExamples:
  644. let x = 7
  645. assert "var is {x * 2}".fmt == "var is 14"
  646. assert "var is {{x}}".fmt == "var is {x}" # escape via doubling
  647. const s = "foo: {x}"
  648. assert s.fmt == "foo: 7" # also works with const strings
  649. assert fmt"\n" == r"\n" # raw string literal
  650. assert "\n".fmt == "\n" # regular literal (likewise with `fmt("\n")` or `fmt "\n"`)
  651. runnableExamples:
  652. # custom `openChar`, `closeChar`
  653. let x = 7
  654. assert "<x>".fmt('<', '>') == "7"
  655. assert "<<<x>>>".fmt('<', '>') == "<7>"
  656. assert "`x`".fmt('`', '`') == "7"
  657. fmt(pattern, openChar, closeChar, dummyForLineInfo)
  658. template fmt*(pattern: static string): untyped {.callsite.} =
  659. ## Alias for `fmt(pattern, '{', '}')`.
  660. fmt(pattern, '{', '}', dummyForLineInfo)
  661. template `&`*(pattern: string{lit}): string {.callsite.} =
  662. ## `&pattern` is the same as `pattern.fmt`.
  663. ## For a specification of the `&` macro, see the module level documentation.
  664. # pending bug #18275, bug #18278, use `pattern: static string`
  665. # consider deprecating this, it's redundant with `fmt` and `fmt` is strictly
  666. # more flexible, readable (no confusion with the binary `&`), self-documenting,
  667. # not to mention #18275, bug #18278.
  668. runnableExamples:
  669. let x = 7
  670. assert &"{x}\n" == "7\n" # regular string literal
  671. assert &"{x}\n" == "{x}\n".fmt # `fmt` can be used instead
  672. assert &"{x}\n" != fmt"{x}\n" # see `fmt` docs, this would use a raw string literal
  673. fmt(pattern, '{', '}', dummyForLineInfo)