Skip to content

Unknown opcode opcNGetType #1152

@dom96

Description

@dom96
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

No one assigned

    Labels

    VMsee also `const` label

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions