#!/usr/bin/Rscript

test_eval <- function(c, expr_name, expr_text) {
    expr <- c(charToRaw(expr_text), as.raw(0))
    stopifnot(length(expr) <= 250)
    
    request <- c(as.raw(c(3, 0, 0, 0, length(expr)+4, 0, 0, 0,
                          0, 0, 0, 0, 0, 0, 0, 0,
                          4, length(expr), 0, 0)), expr)
    writeBin(request, c)

    r <- readBin(c, 'int', 4, 'little')
    stopifnot(r[1] == 65537L)

    d <- readBin(c, 'raw', r[2])

    f <- file(paste0(expr_name, '.qap'), open='wb')
    writeBin(d, con=f)

    close(f)
}

# option(warn=2)                          # exit on warnings
c <- socketConnection('localhost', 6311, open = "a+b", blocking = TRUE)
r <- readBin(c, "raw", 32)
stopifnot(grepl('^Rsrv0103QAP1', rawToChar(r)))

tests <- list(
    `noatt-123l`='1:3',
    `abc-123l`='c(a=1L, b=2L, c=3L)',
    `noatt-123456`='1234.56',
    `foo-123456`='c(foo=1234.56)',
    `f-123456`='c(f=1234.56)',
    `noatt-abc`='letters[1:3]',
    `ABC-abc`='c(A="a", B="b", C="c")',
    `noatt-raw`='as.raw(c(1,2,3,255, 0))',
    `noatt-list`="list(1:3, list('a', 'b', 11), 'foo')",
    `foobar-list`="list(foo=1:3, list('a', 'b', 11), bar='foo')",
    `noatt-mat`='matrix(-1:4, 2, 3)',
    `ab-mat`="matrix(-1:4, 2, 3, dimnames=list(c('a', 'b')))",
    `cars`='head(cars)',
    `mtcars`='head(mtcars)',
    `iris`='head(iris)',
    `lang-lm-mpgwt`='lm(mpg ~ wt, data = head(mtcars))$call',
    `mtcars-lm-mpgwt`='lm(mpg ~ wt, data = head(mtcars))')

for (i in seq_along(tests)) {
    test_eval(c, names(tests)[i], tests[[i]])
}

close(c)
