Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// A simple example of C-union
//
(* ****** ****** *)
//
// Author: Hongwei Xi
// Authoremail: gmhwxiATgmailDOTcom
// Start time: November, 2013
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
%{^
typedef
union { int i; double f; } intfloat ;
//
#define intfloat_get_int(x) (((intfloat*)x)->i)
#define intfloat_get_float(x) (((intfloat*)x)->f)
#define intfloat_set_int(x, v) (((intfloat*)x)->i = v)
#define intfloat_set_float(x, v) (((intfloat*)x)->f = v)
//
%}
abst@ype
intfloat(tag:int) = $extype"intfloat"
//
typedef intfloat = [tag:int] intfloat (tag)
//
(* ****** ****** *)
//
extern
fun intfloat_get_int (x: &intfloat(0)): int = "mac#"
extern
fun intfloat_get_float (x: &intfloat(1)): double = "mac#"
//
(* ****** ****** *)
//
extern
fun intfloat_set_int
(x: &intfloat? >> intfloat(0), i: int): void = "mac#"
extern
fun intfloat_set_float
(x: &intfloat? >> intfloat(1), f: double): void = "mac#"
//
(* ****** ****** *)
staload "libats/SATS/stkarray.sats"
staload _(*anon*) = "libats/DATS/stkarray.dats"
val () =
{
//
val M = i2sz(2)
//
val stk =
stkarray_make_cap<intfloat> (M)
//
val () = assertloc (stkarray_get_size (stk) = 0)
val () = assertloc (stkarray_get_capacity (stk) = M)
//
var x: intfloat?
//
val () = intfloat_set_int (x, 9)
//
val () = stkarray_insert (stk, x)
// NOTE: unknown tag, and there is no way to figure it out
// but that's not the point of the sample
val-x1 = stkarray_takeout (stk)
//
val () = assertloc (stkarray_get_size (stk) = 0)
//
//
val () = stkarray_free_nil (stk)
//
} (* end of [val] *)
implement
main0 () =
{
var x: intfloat?
//
val () = intfloat_set_int (x, 9)
val () = println! ("x.int = ", intfloat_get_int(x))
//
val () = intfloat_set_float (x, 9.9)
val () = println! ("x.float = ", intfloat_get_float(x))
//
} (* end of [main0] *)
(* ****** ****** *)
(* end of [union.dats] *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment