-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Closed
Labels
VMsee also `const` labelsee also `const` label
Description
import macros, typetraits
proc printf(formatstr: cstring) {.importc: "printf", varargs.}
iterator tokenize(format: String): char =
var i = 0
while True:
case format[i]
of '%':
case format[i+1]
of '\0': break
else: yield format[i+1]
i.inc
of '\0': break
else: discard
i.inc
proc `==`(x, y: typedesc): bool = x.name == y.name
macro printf(formatString: string{lit}, args: varargs[expr]): expr =
var i = 0
for c in tokenize(formatString.strVal):
var expectedType = case c
of 'c': char.typedesc
of 'd', 'i', 'x', 'X': int.typedesc
of 'f', 'e', 'E', 'g', 'G': float.typedesc
of 's': string.typedesc
of 'p': pointer.typedesc
else: EOutOfRange
var actualType = args[i].typ
echo(actualType.name)
inc i
if expectedType is EOutOfRange:
error c & " is not a valid format character"
elif expectedType != actualType:
error "type mismatch for argument " & $i & ". expected type: " &
expectedType.name & ", actual type: " & actualType.name
# keep the original callsite, but use cprintf instead
result = callsite()
result[0] = newIdentNode(!"cprintf")
printf("test %d", 10)Metadata
Metadata
Assignees
Labels
VMsee also `const` labelsee also `const` label