## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(rzig)
compiler <- find_zig(required = FALSE)
has_zig <- isTRUE(compiler$supported)

## ----find---------------------------------------------------------------------
compiler

## ----create-------------------------------------------------------------------
path <- file.path(tempdir(), "hellozig")
create_rzig_package(path, fields = list(
  Title = "Greetings from Zig",
  Description = "Shows the workflow of 'rzig'."
))

## ----starter, comment = ""----------------------------------------------------
main_zig <- file.path(path, "src", "rzig", "src", "main.zig")
cat(readLines(main_zig), sep = "\n")

## ----add, comment = ""--------------------------------------------------------
cat(
  "",
  "/// The cumulative sum of a numeric vector.",
  "/// @param x A numeric vector.",
  "/// @return A numeric vector of the same length.",
  "/// @examples",
  "/// cumulative(c(1, 2, 3))",
  "/// @export",
  "pub fn cumulative(ctx: *rzig.Ctx, x: []const f64) rzig.Error![]f64 {",
  "    const out = try ctx.alloc(f64, x.len);",
  "    var total: f64 = 0;",
  "    for (x, out) |value, *slot| {",
  "        total += value;",
  "        slot.* = total;",
  "    }",
  "    return out;",
  "}",
  sep = "\n", file = main_zig, append = TRUE
)

## ----scan---------------------------------------------------------------------
scan_exports(path)

## ----document-----------------------------------------------------------------
bindings <- document(path)
cat(bindings$wrappers)

## ----status-------------------------------------------------------------------
rzig_status(path)

## ----build, eval = has_zig----------------------------------------------------
build <- build_zig(path)
build
library(build$package, character.only = TRUE, lib.loc = build$library)
hello_zig("R")
cumulative(c(1, 2, 3, 4))

## ----errors, eval = has_zig---------------------------------------------------
try(cumulative("a"))

## ----zig-tests, comment = ""--------------------------------------------------
writeLines(c(
  "const std = @import(\"std\");",
  "",
  "fn add(a: f64, b: f64) f64 {",
  "    return a + b;",
  "}",
  "",
  "test \"add\" {",
  "    try std.testing.expectEqual(@as(f64, 3), add(1, 2));",
  "}"
), file.path(path, "src", "rzig", "src", "tests.zig"))

## ----run-zig-tests, eval = has_zig--------------------------------------------
tests <- test_zig(path)
tests

## ----zig-function, eval = has_zig---------------------------------------------
twice <- zig_function("pub fn twice(x: f64) f64 { return 2 * x; }")
twice(21)

## ----cleanup, include = FALSE-------------------------------------------------
if (has_zig) unloadNamespace("hellozig")
unlink(path, recursive = TRUE)

