Skip to content

Commit

Permalink
Add tiny API to make non-allocating tmpl renderers easy. Also update
Browse files Browse the repository at this point in the history
`examples/tmpl.nim` to use this by default with some side comments for
other ways to use. { Tagging @SirNickolas since seems relevant to
#224 }  String compares even in
a `case` theoretically able to use perfect hashes will, of course,
still be slow compared to char-compares like in `bu/tmpls.nim`, but
folks outside the APL/kdb family of PLs sure love >1 char idents. ;-)
The `fmtUncertain*` family should probably use this new `MacroCallX`,
for example as numbers are a thing of which there can be many.
  • Loading branch information
c-blake committed Feb 20, 2024
1 parent ae1b11e commit 60c15b4
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
6 changes: 6 additions & 0 deletions cligen/strUt.nim
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,12 @@ iterator tmplParse*(fmt: openArray[char], meta='$', ids=alphaNum): MacroCall =
proc tmplParsed*(fmt: openArray[char], meta='$', ids=alphaNum): seq[MacroCall] =
## Pre-process a format string template into a `seq[MacroCall]`.
for macCall in tmplParse(fmt, meta, ids): result.add macCall

type MacroCallX* = (Slice[int], Slice[int], Slice[int], string) ## Call & string
proc tmplParses*(fmt: openArray[char], meta='$', ids=alphaNum):seq[MacroCallX] =
## Pre-process a format string template into a `seq[MacroCallX]`.
for mc in tmplParse(fmt, meta, ids):
result.add (mc[0], mc[1], mc[2], fmt[mc[0]].toString)
#*** FORMATTING UNCERTAIN NUMBERS ***
const pmUnicode* = "±" ## for re-assign/param passing ease
const pmUnicodeSpaced* = " ± " ## for re-assign/param passing ease
Expand Down
5 changes: 3 additions & 2 deletions examples/tmpl.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ from std/strutils import toUpperAscii
import cligen/strUt # Example/test text template/macro expand/interpolation.

proc render(fmt: openArray[char]): string =
for (id, arg, call) in tmplParse(fmt):
let fmtParses = fmt.tmplParses # or `fmt.tmplParsed|iterator tmplParse`
for (id, arg, call, idStr) in fmtParses: # or (id, arg, call) with..
if id.idIsLiteral: result.add fmt[arg]
else:
case fmt[id].toString
case idStr #..or `fmt[id].toString`
of "a": result.add "hmm"
of "bc": result.add "hoo"
of "uc": (for i in arg: result.add fmt[i].toUpperAscii)
Expand Down

0 comments on commit 60c15b4

Please sign in to comment.