Let us start!

The first program we present in this tutorial is given as follows:

//
%{^
typedef char **charpp ;
%} ;
abstype charpp = $extype"charpp"
//
implement
main0 (argc, argv) =
{
//
var argc: int = argc
var argv: charpp = $UN.castvwtp1{charpp}(argv)
//
val () = $extfcall (void, "gtk_init", addr@(argc), addr@(argv))
//
val win =
  gtk_window_new (GTK_WINDOW_TOPLEVEL)
//
val () = assertloc (ptrcast(win) > 0)
//
val ((*void*)) = gtk_widget_show (win)
//
val ((*void*)) = gtk_main () // entring the main loop of GTK
//
val ((*void*)) = gtk_widget_destroy0 (win) // a type-error if omitted
//
} (* end of [main0] *)
//

This code probably looks rather peculiar at first. As the function gtk_init is currently not included in ATS/GTK, it is called through the use of $extfcall (for handling calls to external functions). In summary, the above code (after gtk_init is called) creates a window (which is a type of GTK-widget), checks that the window is not null, sets some flag to indicate that the window is to be displayed, and then enters the main loop of GTK.

The above code plus some additional lines can be found in chap_start.dats, and there is a Makefile available for compiling the file. A window of 200x200 pixels pops up when the executable program generated from compilation is executed; the running program does not exit except for being killed explicitly (e.g., through shell activities).

ATS is a programming language that distinguishes itself in its practical and effective support for precise resource management. While it may seem that using GTK functions in ATS is nearly identical to using them in C (modulo syntatical difference), what happens at the level of typechecking in ATS is far more sophisticated than in C. In particular, linear types are assigned to GTK objects in ATS to allow them to be tracked statically, that is, at compile-time, preventing potential mismanagement of such objects. For instance, if the following line:

  val ((*void*)) = gtk_widget_destroy0 (win) // a type-error if omitted

is removed from the program in chap_start.dats, then a type-error message is issued at compile-time to indicate that the resource win is not properly freed. While this is not really an issue in this particular example (as the call to gtk_widget_destroy0 can never be executed), a message as such can be of great value in general for correcting potential memory leaks that may otherwise readily go unnoticed.