%{^
#include <stdio.h>

void* resource_new();
void resource_free(void* r);
void do_something(void (*f)(void* r), void* arg);
void resource_use(void* r);
%}

%{
void* resource_new() { return ATS_MALLOC(10); }
void resource_use(void* r) { printf("using: %p\n", r); }
void resource_free(void* r) { ATS_FREE(r); }
void do_something(void (*f)(void*), void* arg) { printf("a\n"); f(arg); printf("b\n"); }
%}

absviewtype resource (l:addr)
viewtypedef resource1 = [l:addr | l > null] resource l
extern fun resource_new():resource1 = "mac#resource_new"
extern fun resource_use(r: !resource1):void = "mac#resource_use"
extern fun resource_free(r: resource1):void = "mac#resource_free"

viewtypedef env (l1:addr, l2:addr) = @{r1= resource l1, r2= resource l2}
viewtypedef env = [l1,l2:agz] env(l1, l2)
typedef callback = (&env) -<fun1> void
extern fun do_something(f: callback, arg: &env):void = "mac#do_something"

fun mycallback(e: &env): void = let
  val () = resource_use(e.r1);
  val () = resource_use(e.r2);
in
  ()
end
 
implement main() = let
  var env: env(null, null)
  val () = env.r1 := resource_new();
  val () = env.r2 := resource_new();

  val () = do_something(mycallback, env)

  val () = resource_free(env.r1);
  val () = resource_free(env.r2);
in
  ()
end