Skip to content

Commit

Permalink
stdlib: clean up coloredResult (#962)
Browse files Browse the repository at this point in the history
## Summary

Slightly refactor the implementation of the `colortext.coloredResult`
template and remove its obsolete `endResult` helper template.

## Details

- mention the injected `addf` routine in the documentation
- remove the unnecessary `static` block around the `.error` directive
- shorten the compile-time error message for when no `result` variable
  exists
- remove the `endResult` helper template; the `vmgen` bug that
  necessitated it is fixed
- turn the `addf` procedure into a template and mark it as `.used`,
  preventing `XDeclaredButNotUsed` warnings
  • Loading branch information
zerbina authored Oct 14, 2023
1 parent eead321 commit a0ce294
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 16 deletions.
21 changes: 6 additions & 15 deletions lib/experimental/colortext.nim
Original file line number Diff line number Diff line change
Expand Up @@ -700,27 +700,18 @@ template coloredResult*(indentationStep: int = 2): untyped =
##
## aux(node)
##
## Injected procs
## Injected routines
##
## - `addf(string, varargs)`
## - `add(string)`, `add(string, string)`
## - `addIndent(int)`, `addi(int, string)`
## - `endResult()` - return colored result. Required for proper work
## of the code in the compile-time context, otherwise modification
## of the `addr result` does not work properly.
static:
when not declared(result):
{.error: "'coloredResult' template can only be called inside of the procedure returning 'ColText' as a result, or other environment that has `var result: ColText` defined."}
when not declared(result):
{.error: "'coloredResult' template can only be called in an environment " &
"where a `result` variable is available"}

var outPtr {.used.}: ptr ColText = addr result

template endResult(): untyped {.used.} =
when nimvm:
return outPtr[]

else:
return

proc addf(format: string, args: varargs[ColText, toColText]) =
template addf(format: string, args: varargs[untyped]) {.used.} =
outPtr[].addf(format, args)

template add(arg: untyped): untyped {.used.} = outPtr[].add arg
Expand Down
1 change: 0 additions & 1 deletion tests/stdlib/algorithm/tcolortext.nim
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ let exp: int
add "1" + fgRed
addi 2, "2"
add "]"
endResult()

let col = reesc($colres())
let want = r"[ 0\e[31m1\e[39m 2]"
Expand Down

0 comments on commit a0ce294

Please sign in to comment.