From ab3ab545be0b550cca1c2529f7e97fbebf5eba81 Mon Sep 17 00:00:00 2001 From: andri lim Date: Fri, 16 Feb 2024 11:34:42 +0700 Subject: [PATCH] =?UTF-8?q?Silence=20declared=20but=20unused=20warnings=20?= =?UTF-8?q?when=20there=20is=20no=20loggging=20code=20g=E2=80=A6=20(#143)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Silence declared but unused warnings when there is no loggging code generated * Create custom 'used' magic * Also disable warning for eventName --- chronicles.nim | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/chronicles.nim b/chronicles.nim index 95e283a..7b184e3 100644 --- a/chronicles.nim +++ b/chronicles.nim @@ -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)) @@ -216,6 +216,11 @@ 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, @@ -223,7 +228,6 @@ macro logIMPL(lineInfo: static InstInfo, severity: static[LogLevel], scopes: typed, logStmtBindings: varargs[untyped]): untyped = - if not loggingEnabled: return clearEmptyVarargs logStmtBindings # First, we merge the lexical bindings with the additional @@ -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 @@ -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`