Skip to content

Instantly share code, notes, and snippets.

@ReneSac
Last active August 29, 2015 14:00
Show Gist options
  • Save ReneSac/b57811eb4ae8ab39bed1 to your computer and use it in GitHub Desktop.
Save ReneSac/b57811eb4ae8ab39bed1 to your computer and use it in GitHub Desktop.
#import macros
import typetraits
type
TokenKind = enum
FInt, FString, Text
Token = object
case kind: TokenKind
of FInt, FString: nil
of Text: c: String
iterator tokenize(format: string): Token =
var i = 0
while True:
case format[i]
of '%':
case format[i+1]
of 'd': yield Token(kind: FInt)
of 's': yield Token(kind: FString)
of '\0': break
else: echo("Incorrect format string.")
i.inc
of '\0': break
else:
yield Token(kind: Text, c: $format[i])
i.inc
proc printf(format:string, params: varargs[int]): string =
var i = 0
var stringLit = ""
for tok in tokenize(format):
case tok.kind
of FInt:
if i >= params.len: echo("Too many arguments in format string.")
if params[i].type is int: echo("Expected Int got ", params[i].type.name)# " & $params[i].type)
stringLit.add($params[i])
i.inc
of FString:
if i >= params.len: echo("Too many arguments in format string.")
if params[i].type is string: echo("Expected String got ", params[i].type.name)# & $params[i].type)
stringLit.add($params[i])
i.inc
of Text: stringLit.add tok.c
if i < params.len: echo("Too many arguments to printf.")
result = stringLit
echo printf("%d", 1)
#Echos:
# Expected Int got int
# 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment