Skip to content

Instantly share code, notes, and snippets.

@dirkschumacher
Last active January 30, 2021 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirkschumacher/8fd8f464c049a7c0105442a6e333a01f to your computer and use it in GitHub Desktop.
Save dirkschumacher/8fd8f464c049a7c0105442a6e333a01f to your computer and use it in GitHub Desktop.
# Let's build this expression by hand
# val <- 0
# if (this) {
# val <- 1
# }
constant_pool <- list(
NULL,
as.symbol("val"), # we need a symbol val
as.symbol("this"), # we also need a symbol this,
0, 1 # next we need the two values 0 and 1
)
code <- as.integer(c(
12L, # I believe this is the byte code version
compiler:::LDCONST.OP, 3L, # first let's load the 0 at index 3
compiler:::SETVAR.OP, 1L, # assign last value to symbol at position 1
compiler:::POP.OP, # remove value 0 from the stack
compiler:::GETVAR.OP, 2L, # load variable this
compiler:::BRIFNOT.OP, 0L, 17L, # if last val is true, then proceed, else goto 17
compiler:::LDCONST.OP, 4L, # load the 1 at index 4 from pool
compiler:::SETVAR.OP, 1L, # set that value to symbol at index 1
compiler:::GOTO.OP, 18L, # now go to invisible return (i.e. skip next line)
compiler:::LDNULL.OP, # 17: else target; load null on the stack
compiler:::INVISIBLE.OP, # 18: make the result invisible
compiler:::RETURN.OP # return
))
bc <- .Internal(mkCode(code, constant_pool))
this <- FALSE; eval(bc)
val
#> [1] 0
rm(val); this <- TRUE; eval(bc)
val
#> [1] 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment