strformat.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. (None) Similar to `g`, except that it prints at least one
  212. digit after the decimal point.
  213. ================= ====================================================
  214. # Limitations
  215. Because of the well defined order how templates and macros are
  216. expanded, strformat cannot expand template arguments:
  217. ```nim
  218. template myTemplate(arg: untyped): untyped =
  219. echo "arg is: ", arg
  220. echo &"--- {arg} ---"
  221. let x = "abc"
  222. myTemplate(x)
  223. ```
  224. First the template `myTemplate` is expanded, where every identifier
  225. `arg` is substituted with its argument. The `arg` inside the
  226. format string is not seen by this process, because it is part of a
  227. quoted string literal. It is not an identifier yet. Then the strformat
  228. macro creates the `arg` identifier from the string literal, an
  229. identifier that cannot be resolved anymore.
  230. The workaround for this is to bind the template argument to a new local variable.
  231. ```nim
  232. template myTemplate(arg: untyped): untyped =
  233. block:
  234. let arg1 {.inject.} = arg
  235. echo "arg is: ", arg1
  236. echo &"--- {arg1} ---"
  237. ```
  238. The use of `{.inject.}` here is necessary again because of template
  239. expansion order and hygienic templates. But since we generally want to
  240. keep the hygiene of `myTemplate`, and we do not want `arg1`
  241. to be injected into the context where `myTemplate` is expanded,
  242. everything is wrapped in a `block`.
  243. # Future directions
  244. A curly expression with commas in it like `{x, argA, argB}` could be
  245. transformed to `formatValue(result, x, argA, argB)` in order to support
  246. formatters that do not need to parse a custom language within a custom
  247. language but instead prefer to use Nim's existing syntax. This would also
  248. help with readability, since there is only so much you can cram into
  249. single letter DSLs.
  250. ]##
  251. import macros, parseutils, unicode
  252. import strutils except format
  253. when defined(nimPreviewSlimSystem):
  254. import std/assertions
  255. proc mkDigit(v: int, typ: char): string {.inline.} =
  256. assert(v < 26)
  257. if v < 10:
  258. result = $chr(ord('0') + v)
  259. else:
  260. result = $chr(ord(if typ == 'x': 'a' else: 'A') + v - 10)
  261. proc alignString*(s: string, minimumWidth: int; align = '\0'; fill = ' '): string =
  262. ## Aligns `s` using the `fill` char.
  263. ## This is only of interest if you want to write a custom `format` proc that
  264. ## should support the standard format specifiers.
  265. if minimumWidth == 0:
  266. result = s
  267. else:
  268. let sRuneLen = if s.validateUtf8 == -1: s.runeLen else: s.len
  269. let toFill = minimumWidth - sRuneLen
  270. if toFill <= 0:
  271. result = s
  272. elif align == '<' or align == '\0':
  273. result = s & repeat(fill, toFill)
  274. elif align == '^':
  275. let half = toFill div 2
  276. result = repeat(fill, half) & s & repeat(fill, toFill - half)
  277. else:
  278. result = repeat(fill, toFill) & s
  279. type
  280. StandardFormatSpecifier* = object ## Type that describes "standard format specifiers".
  281. fill*, align*: char ## Desired fill and alignment.
  282. sign*: char ## Desired sign.
  283. alternateForm*: bool ## Whether to prefix binary, octal and hex numbers
  284. ## with `0b`, `0o`, `0x`.
  285. padWithZero*: bool ## Whether to pad with zeros rather than spaces.
  286. minimumWidth*, precision*: int ## Desired minimum width and precision.
  287. typ*: char ## Type like 'f', 'g' or 'd'.
  288. endPosition*: int ## End position in the format specifier after
  289. ## `parseStandardFormatSpecifier` returned.
  290. proc formatInt(n: SomeNumber; radix: int; spec: StandardFormatSpecifier): string =
  291. ## Converts `n` to a string. If `n` is `SomeFloat`, it casts to `int64`.
  292. ## Conversion is done using `radix`. If result's length is less than
  293. ## `minimumWidth`, it aligns result to the right or left (depending on `a`)
  294. ## with the `fill` char.
  295. when n is SomeUnsignedInt:
  296. var v = n.uint64
  297. let negative = false
  298. else:
  299. let n = n.int64
  300. let negative = n < 0
  301. var v =
  302. if negative:
  303. # `uint64(-n)`, but accounts for `n == low(int64)`
  304. uint64(not n) + 1
  305. else:
  306. uint64(n)
  307. var xx = ""
  308. if spec.alternateForm:
  309. case spec.typ
  310. of 'X': xx = "0x"
  311. of 'x': xx = "0x"
  312. of 'b': xx = "0b"
  313. of 'o': xx = "0o"
  314. else: discard
  315. if v == 0:
  316. result = "0"
  317. else:
  318. result = ""
  319. while v > typeof(v)(0):
  320. let d = v mod typeof(v)(radix)
  321. v = v div typeof(v)(radix)
  322. result.add(mkDigit(d.int, spec.typ))
  323. for idx in 0..<(result.len div 2):
  324. swap result[idx], result[result.len - idx - 1]
  325. if spec.padWithZero:
  326. let sign = negative or spec.sign != '-'
  327. let toFill = spec.minimumWidth - result.len - xx.len - ord(sign)
  328. if toFill > 0:
  329. result = repeat('0', toFill) & result
  330. if negative:
  331. result = "-" & xx & result
  332. elif spec.sign != '-':
  333. result = spec.sign & xx & result
  334. else:
  335. result = xx & result
  336. if spec.align == '<':
  337. for i in result.len..<spec.minimumWidth:
  338. result.add(spec.fill)
  339. else:
  340. let toFill = spec.minimumWidth - result.len
  341. if spec.align == '^':
  342. let half = toFill div 2
  343. result = repeat(spec.fill, half) & result & repeat(spec.fill, toFill - half)
  344. else:
  345. if toFill > 0:
  346. result = repeat(spec.fill, toFill) & result
  347. proc parseStandardFormatSpecifier*(s: string; start = 0;
  348. ignoreUnknownSuffix = false): StandardFormatSpecifier =
  349. ## An exported helper proc that parses the "standard format specifiers",
  350. ## as specified by the grammar:
  351. ##
  352. ## [[fill]align][sign][#][0][minimumwidth][.precision][type]
  353. ##
  354. ## This is only of interest if you want to write a custom `format` proc that
  355. ## should support the standard format specifiers. If `ignoreUnknownSuffix` is true,
  356. ## an unknown suffix after the `type` field is not an error.
  357. const alignChars = {'<', '>', '^'}
  358. result.fill = ' '
  359. result.align = '\0'
  360. result.sign = '-'
  361. var i = start
  362. if i + 1 < s.len and s[i+1] in alignChars:
  363. result.fill = s[i]
  364. result.align = s[i+1]
  365. inc i, 2
  366. elif i < s.len and s[i] in alignChars:
  367. result.align = s[i]
  368. inc i
  369. if i < s.len and s[i] in {'-', '+', ' '}:
  370. result.sign = s[i]
  371. inc i
  372. if i < s.len and s[i] == '#':
  373. result.alternateForm = true
  374. inc i
  375. if i + 1 < s.len and s[i] == '0' and s[i+1] in {'0'..'9'}:
  376. result.padWithZero = true
  377. inc i
  378. let parsedLength = parseSaturatedNatural(s, result.minimumWidth, i)
  379. inc i, parsedLength
  380. if i < s.len and s[i] == '.':
  381. inc i
  382. let parsedLengthB = parseSaturatedNatural(s, result.precision, i)
  383. inc i, parsedLengthB
  384. else:
  385. result.precision = -1
  386. if i < s.len and s[i] in {'A'..'Z', 'a'..'z'}:
  387. result.typ = s[i]
  388. inc i
  389. result.endPosition = i
  390. if i != s.len and not ignoreUnknownSuffix:
  391. raise newException(ValueError,
  392. "invalid format string, cannot parse: " & s[i..^1])
  393. proc formatValue*[T: SomeInteger](result: var string; value: T;
  394. specifier: string) =
  395. ## Standard format implementation for `SomeInteger`. It makes little
  396. ## sense to call this directly, but it is required to exist
  397. ## by the `&` macro.
  398. if specifier.len == 0:
  399. result.add $value
  400. return
  401. let spec = parseStandardFormatSpecifier(specifier)
  402. var radix = 10
  403. case spec.typ
  404. of 'x', 'X': radix = 16
  405. of 'd', '\0': discard
  406. of 'b': radix = 2
  407. of 'o': radix = 8
  408. else:
  409. raise newException(ValueError,
  410. "invalid type in format string for number, expected one " &
  411. " of 'x', 'X', 'b', 'd', 'o' but got: " & spec.typ)
  412. result.add formatInt(value, radix, spec)
  413. proc formatValue*(result: var string; value: SomeFloat; specifier: string) =
  414. ## Standard format implementation for `SomeFloat`. It makes little
  415. ## sense to call this directly, but it is required to exist
  416. ## by the `&` macro.
  417. if specifier.len == 0:
  418. result.add $value
  419. return
  420. let spec = parseStandardFormatSpecifier(specifier)
  421. var fmode = ffDefault
  422. case spec.typ
  423. of 'e', 'E':
  424. fmode = ffScientific
  425. of 'f', 'F':
  426. fmode = ffDecimal
  427. of 'g', 'G':
  428. fmode = ffDefault
  429. of '\0': discard
  430. else:
  431. raise newException(ValueError,
  432. "invalid type in format string for number, expected one " &
  433. " of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
  434. var f = formatBiggestFloat(value, fmode, spec.precision)
  435. var sign = false
  436. if value >= 0.0:
  437. if spec.sign != '-':
  438. sign = true
  439. if value == 0.0:
  440. if 1.0 / value == Inf:
  441. # only insert the sign if value != negZero
  442. f.insert($spec.sign, 0)
  443. else:
  444. f.insert($spec.sign, 0)
  445. else:
  446. sign = true
  447. if spec.padWithZero:
  448. var signStr = ""
  449. if sign:
  450. signStr = $f[0]
  451. f = f[1..^1]
  452. let toFill = spec.minimumWidth - f.len - ord(sign)
  453. if toFill > 0:
  454. f = repeat('0', toFill) & f
  455. if sign:
  456. f = signStr & f
  457. # the default for numbers is right-alignment:
  458. let align = if spec.align == '\0': '>' else: spec.align
  459. let res = alignString(f, spec.minimumWidth, align, spec.fill)
  460. if spec.typ in {'A'..'Z'}:
  461. result.add toUpperAscii(res)
  462. else:
  463. result.add res
  464. proc formatValue*(result: var string; value: string; specifier: string) =
  465. ## Standard format implementation for `string`. It makes little
  466. ## sense to call this directly, but it is required to exist
  467. ## by the `&` macro.
  468. let spec = parseStandardFormatSpecifier(specifier)
  469. var value = value
  470. case spec.typ
  471. of 's', '\0': discard
  472. else:
  473. raise newException(ValueError,
  474. "invalid type in format string for string, expected 's', but got " &
  475. spec.typ)
  476. if spec.precision != -1:
  477. if spec.precision < runeLen(value):
  478. setLen(value, runeOffset(value, spec.precision))
  479. result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
  480. proc formatValue[T: not SomeInteger](result: var string; value: T; specifier: string) =
  481. mixin `$`
  482. formatValue(result, $value, specifier)
  483. template formatValue(result: var string; value: char; specifier: string) =
  484. result.add value
  485. template formatValue(result: var string; value: cstring; specifier: string) =
  486. result.add value
  487. proc strformatImpl(f: string; openChar, closeChar: char,
  488. lineInfoNode: NimNode = nil): NimNode =
  489. template missingCloseChar =
  490. error("invalid format string: missing closing character '" & closeChar & "'")
  491. if openChar == ':' or closeChar == ':':
  492. error "openChar and closeChar must not be ':'"
  493. var i = 0
  494. let res = genSym(nskVar, "fmtRes")
  495. result = newNimNode(nnkStmtListExpr, lineInfoNode)
  496. # XXX: https://github.com/nim-lang/Nim/issues/8405
  497. # When compiling with -d:useNimRtl, certain procs such as `count` from the strutils
  498. # module are not accessible at compile-time:
  499. let expectedGrowth = when defined(useNimRtl): 0 else: count(f, openChar) * 10
  500. result.add newVarStmt(res, newCall(bindSym"newStringOfCap",
  501. newLit(f.len + expectedGrowth)))
  502. var strlit = ""
  503. while i < f.len:
  504. if f[i] == openChar:
  505. inc i
  506. if f[i] == openChar:
  507. inc i
  508. strlit.add openChar
  509. else:
  510. if strlit.len > 0:
  511. result.add newCall(bindSym"add", res, newLit(strlit))
  512. strlit = ""
  513. var subexpr = ""
  514. var inParens = 0
  515. var inSingleQuotes = false
  516. var inDoubleQuotes = false
  517. template notEscaped:bool = f[i-1]!='\\'
  518. while i < f.len and f[i] != closeChar and (f[i] != ':' or inParens != 0):
  519. case f[i]
  520. of '\\':
  521. if i < f.len-1 and f[i+1] in {openChar,closeChar,':'}: inc i
  522. of '\'':
  523. if not inDoubleQuotes and notEscaped: inSingleQuotes = not inSingleQuotes
  524. of '\"':
  525. if notEscaped: inDoubleQuotes = not inDoubleQuotes
  526. of '(':
  527. if not (inSingleQuotes or inDoubleQuotes): inc inParens
  528. of ')':
  529. if not (inSingleQuotes or inDoubleQuotes): dec inParens
  530. of '=':
  531. let start = i
  532. inc i
  533. i += f.skipWhitespace(i)
  534. if i == f.len:
  535. missingCloseChar
  536. if f[i] == closeChar or f[i] == ':':
  537. result.add newCall(bindSym"add", res, newLit(subexpr & f[start ..< i]))
  538. else:
  539. subexpr.add f[start ..< i]
  540. continue
  541. else: discard
  542. subexpr.add f[i]
  543. inc i
  544. if i == f.len:
  545. missingCloseChar
  546. var x: NimNode
  547. try:
  548. x = parseExpr(subexpr)
  549. except ValueError as e:
  550. error("could not parse `$#` in `$#`.\n$#" % [subexpr, f, e.msg])
  551. x.copyLineInfo(lineInfoNode)
  552. let formatSym = bindSym("formatValue", brOpen)
  553. var options = ""
  554. if f[i] == ':':
  555. inc i
  556. while i < f.len and f[i] != closeChar:
  557. options.add f[i]
  558. inc i
  559. if i == f.len:
  560. missingCloseChar
  561. if f[i] == closeChar:
  562. inc i
  563. result.add newCall(formatSym, res, x, newLit(options))
  564. elif f[i] == closeChar:
  565. if i<f.len-1 and f[i+1] == closeChar:
  566. strlit.add closeChar
  567. inc i, 2
  568. else:
  569. raiseAssert "invalid format string: '$1' instead of '$1$1'" % $closeChar
  570. inc i
  571. else:
  572. strlit.add f[i]
  573. inc i
  574. if strlit.len > 0:
  575. result.add newCall(bindSym"add", res, newLit(strlit))
  576. result.add res
  577. # workaround for #20381
  578. var blockExpr = newNimNode(nnkBlockExpr, lineInfoNode)
  579. blockExpr.add(newEmptyNode())
  580. blockExpr.add(result)
  581. result = blockExpr
  582. when defined(debugFmtDsl):
  583. echo repr result
  584. macro fmt(pattern: static string; openChar: static char, closeChar: static char, lineInfoNode: untyped): string =
  585. ## version of `fmt` with dummy untyped param for line info
  586. strformatImpl(pattern, openChar, closeChar, lineInfoNode)
  587. when not defined(nimHasCallsitePragma):
  588. {.pragma: callsite.}
  589. template fmt*(pattern: static string; openChar: static char, closeChar: static char): string {.callsite.} =
  590. ## Interpolates `pattern` using symbols in scope.
  591. runnableExamples:
  592. let x = 7
  593. assert "var is {x * 2}".fmt == "var is 14"
  594. assert "var is {{x}}".fmt == "var is {x}" # escape via doubling
  595. const s = "foo: {x}"
  596. assert s.fmt == "foo: 7" # also works with const strings
  597. assert fmt"\n" == r"\n" # raw string literal
  598. assert "\n".fmt == "\n" # regular literal (likewise with `fmt("\n")` or `fmt "\n"`)
  599. runnableExamples:
  600. # custom `openChar`, `closeChar`
  601. let x = 7
  602. assert "<x>".fmt('<', '>') == "7"
  603. assert "<<<x>>>".fmt('<', '>') == "<7>"
  604. assert "`x`".fmt('`', '`') == "7"
  605. fmt(pattern, openChar, closeChar, dummyForLineInfo)
  606. template fmt*(pattern: static string): untyped {.callsite.} =
  607. ## Alias for `fmt(pattern, '{', '}')`.
  608. fmt(pattern, '{', '}', dummyForLineInfo)
  609. template `&`*(pattern: string{lit}): string {.callsite.} =
  610. ## `&pattern` is the same as `pattern.fmt`.
  611. ## For a specification of the `&` macro, see the module level documentation.
  612. # pending bug #18275, bug #18278, use `pattern: static string`
  613. # consider deprecating this, it's redundant with `fmt` and `fmt` is strictly
  614. # more flexible, readable (no confusion with the binary `&`), self-documenting,
  615. # not to mention #18275, bug #18278.
  616. runnableExamples:
  617. let x = 7
  618. assert &"{x}\n" == "7\n" # regular string literal
  619. assert &"{x}\n" == "{x}\n".fmt # `fmt` can be used instead
  620. assert &"{x}\n" != fmt"{x}\n" # see `fmt` docs, this would use a raw string literal
  621. fmt(pattern, '{', '}', dummyForLineInfo)