Skip to content

Instantly share code, notes, and snippets.

@detunized
Last active June 13, 2018 08:34
Show Gist options
  • Save detunized/91deaf0b70c21a7c11abca0c3b75ff5f to your computer and use it in GitHub Desktop.
Save detunized/91deaf0b70c21a7c11abca0c3b75ff5f to your computer and use it in GitHub Desktop.
Naive t2b (https://github.com/thosakwe/t2b) implementation proof of concept
#!/usr/bin/env ruby
#
# DSL implementation
#
$stack = [""]
def emit x
$stack.last << x
end
def u8 x
emit [x].pack "c"
end
def u32 x
emit [x].pack "l"
end
def i64 x
emit [x].pack "Q"
end
def str x
emit x
end
def strl x
str x
endl
end
def endl
emit "\n"
end
def capture
$stack.push ""
yield
$stack.pop
end
#
# Example from readme
#
u8 10
u8 0x10
i64 25677
str "hello"
strl "hello world!"
str "hello, world!\n"
str "\u{1234}"
endl
5.times do
u8 23
u32 24
10.times do
# We can nest loops
str "50 times!!!"
end
end
foo = capture { u8 33 }
bar = foo
3.times { emit foo }
def emit_twice x
2.times { emit x }
end
emit_twice 24
#
# Final output
#
print $stack.pop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment