Skip to content

Commit

Permalink
Silence declared but unused warnings when there is no loggging code g… (
Browse files Browse the repository at this point in the history
#143)

* Silence declared but unused warnings when there is no loggging code generated

* Create custom 'used' magic

* Also disable warning for eventName
  • Loading branch information
jangko authored Feb 16, 2024
1 parent 4669266 commit ab3ab54
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions chronicles.nim
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,13 @@ else:
else:
proc getLogThreadId*(): int = 0

template formatItIMPL*(value: any): auto =
template formatItIMPL*(value: auto): auto =
value

template formatIt*(T: type, body: untyped) {.dirty.} =
template formatItIMPL*(it: T): auto = body

template expandItIMPL*[R](record: R, field: static string, value: any) =
template expandItIMPL*[R](record: R, field: static string, value: auto) =
mixin setProperty, formatItIMPL
setProperty(record, field, formatItIMPL(value))

Expand Down Expand Up @@ -216,14 +216,18 @@ macro expandIt*(T: type, expandedProps: untyped): untyped =
when defined(debugLogImpl):
echo result.repr

template chroniclesUsedMagic(x: untyped) =
# Force the compiler to mark any symbol in the x
# as used without actually generate any code.
when compiles(x): discard

macro logIMPL(lineInfo: static InstInfo,
Stream: typed,
RecordType: type,
eventName: static[string],
severity: static[LogLevel],
scopes: typed,
logStmtBindings: varargs[untyped]): untyped =
if not loggingEnabled: return
clearEmptyVarargs logStmtBindings

# First, we merge the lexical bindings with the additional
Expand All @@ -237,6 +241,17 @@ macro logIMPL(lineInfo: static InstInfo,
for k, v in assignments(lexicalBindings, acLogStatement):
finalBindings[k] = v

result = newStmtList()
# This statement is to silence compiler warnings
# `declared but not used` when there is no logging code generated.
# push/pop pragma pairs cannot be used in this situation
# because the variables are declared outside of this function.
result.add quote do: chroniclesUsedMagic(`eventName`)
for k, v in finalBindings:
result.add quote do: chroniclesUsedMagic(`v`)

if not loggingEnabled: return

# This is the compile-time topic filtering code, which has a similar
# logic to the generated run-time filtering code:
var enabledTopicsMatch = enabledTopics.len == 0 and severity >= enabledLogLevel
Expand Down Expand Up @@ -314,7 +329,7 @@ macro logIMPL(lineInfo: static InstInfo,
code.add newCall("logAllDynamicProperties", Stream, record)
code.add newCall("flushRecord", record)

result = quote do:
result.add quote do:
try:
block `chroniclesBlockName`:
`code`
Expand Down

0 comments on commit ab3ab54

Please sign in to comment.