Skip to content

Instantly share code, notes, and snippets.

@dirkschumacher
Created October 30, 2021 21:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dirkschumacher/fd5b19f4ff5c392e9dc50a7947dd4fa8 to your computer and use it in GitHub Desktop.
# let's construct some byte code
# x <- 42
# y <- x + 42
bcode <- .Internal(mkCode(
c(
12L, # this is an identifier which byte-code version you use (I think)
# each line is an operator, the first item is the operator, followed by operands (aka. arguments)
16L, 0L, # Operator "LDCONST" (load constant) from the index 1 in the constant pool
# now value 1 is on the stack
22L, 1L, # Operator "SETVAR" (set variable) assign the last value on the stack to the name at index 2
# 1 was removed from the stack,
# but the return value of the assignment is now on the stack again
4L, # let's pop that value,
20L, 1L, # Operator "GETVAR": let's load x (get var operator)
# since 1 is now on the stack, we need to add 1 to it and then assign it
# to y
16L, 0L, # Now let's load a constant again from index 1
44L, 2L, # Let's add the last two values. Add has one argument, the original expression. Not sure why
22L, 3L, # now set the value on the stack to the name at index 4
15L, # make the value in visible
1L # return
),
list(# the constant pool (a list of values and some rules)
42,
as.name("x"),
quote(x + 42),
as.name("y")
)
))
print(eval(bcode))
#> [1] 84
print(x)
#> [1] 42
print(y)
#> [1] 84
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment