Created
February 24, 2016 05:23
-
-
Save aidansteele/d29b401ca2dfad188088 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import maker | |
import streams | |
makeFormat(MachData): | |
f(firstField, int32, default: 4) | |
f(secondField, string, length: firstFiend) | |
f(thirdField, string, length: firstField + 6, value: abc) | |
let s = "\x05\x00\x00\x00abcxxxdefxxx" | |
let stream = newStringStream(s) | |
let x: MachData = read(stream) | |
echo(x) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import macros | |
import strutils | |
macro makeFormat(name: expr, description: expr): stmt = | |
var typBodyStr = "type $1 = object" % [$name] | |
for ex in description: | |
let s = """ $1: $2""" % [$ex[1], $ex[2]] | |
typBodyStr = "$1\n$2" % [typBodyStr, s] | |
var readStr = "proc read(s: Stream): $1 =" % [$name] | |
var readCons = newSeq[string]() | |
for ex in description: | |
let fName = $ex[1] | |
let fType = $ex[2] | |
if fType == "int32": | |
let s = " let $1 = readInt32(s)" % [fName] | |
readStr = "$1\n$2" % [readStr, s] | |
add(readCons, "$1: $1" % [fName]) | |
elif fType == "string": | |
let s = " let $1 = readStr(s, 6)" % [fName] | |
readStr = "$1\n$2" % [readStr, s] | |
add(readCons, "$1: $1" % [fName]) | |
readStr = "$1\n result = $2($3)" % [readStr, $name, join(readCons, ", ")] | |
result = newStmtList() | |
add(result, parseStmt(typBodyStr)) | |
add(result, parseStmt(readStr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment