summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--lib/js/jsconsole.nim44
-rw-r--r--tests/js/tconsole.nim13
2 files changed, 57 insertions, 0 deletions
diff --git a/lib/js/jsconsole.nim b/lib/js/jsconsole.nim
new file mode 100644
index 000000000..d9ced95f0
--- /dev/null
+++ b/lib/js/jsconsole.nim
@@ -0,0 +1,44 @@
+#
+#
+#            Nim's Runtime Library
+#        (c) Copyright 2012 Andreas Rumpf
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+
+## Wrapper for the `console` object for the `JavaScript backend
+## <backends.html#the-javascript-target>`_.
+
+when not defined(js) and not defined(Nimdoc):
+  {.error: "This module only works on the JavaScript platform".}
+
+import macros
+
+type Console* {.importc.} = ref object of RootObj
+
+proc convertToConsoleLoggable*[T](v: T): RootRef {.importcpp: "#".}
+template convertToConsoleLoggable*(v: string): RootRef = cast[RootRef](cstring(v))
+
+proc logImpl(console: Console) {.importcpp: "log", varargs.}
+proc debugImpl(console: Console) {.importcpp: "debug", varargs.}
+proc infoImpl(console: Console) {.importcpp: "info", varargs.}
+proc errorImpl(console: Console) {.importcpp: "error", varargs.}
+
+proc makeConsoleCall(console: NimNode, procName: NimNode, args: NimNode): NimNode =
+  result = newCall(procName, console)
+  for c in args: result.add(c)
+
+macro log*(console: Console, args: varargs[RootRef, convertToConsoleLoggable]): untyped =
+  makeConsoleCall(console, bindSym "logImpl", args)
+
+macro debug*(console: Console, args: varargs[RootRef, convertToConsoleLoggable]): untyped =
+  makeConsoleCall(console, bindSym "debugImpl", args)
+
+macro info*(console: Console, args: varargs[RootRef, convertToConsoleLoggable]): untyped =
+  makeConsoleCall(console, bindSym "infoImpl", args)
+
+macro error*(console: Console, args: varargs[RootRef, convertToConsoleLoggable]): untyped =
+  makeConsoleCall(console, bindSym "errorImpl", args)
+
+var console* {.importc, nodecl.}: Console
\ No newline at end of file
diff --git a/tests/js/tconsole.nim b/tests/js/tconsole.nim
new file mode 100644
index 000000000..f6da71c20
--- /dev/null
+++ b/tests/js/tconsole.nim
@@ -0,0 +1,13 @@
+discard """
+  output: '''Hello, console
+1 2 3
+1 'hi' 1.1'''
+"""
+
+# This file tests the JavaScript console
+
+import jsconsole
+
+console.log("Hello, console")
+console.log(1, 2, 3)
+console.log(1, "hi", 1.1)
\ No newline at end of file