Chapter 6. Dynamic Load

In ATS, dynamic load (or dynload for short) refers to some form of initialization of a loaded package.

Suppose that a file named foo.dats contains the following code:

// val x = 1000 val y = x + x // = 2000 val z = y * y // = 4000000 // extern fun sum_x_y_z (): int // implement sum_x_y_z () = x + y + z //

Clearly, the names x, y, and z must be bound to some values before a call to the function sum_x_y_z can be evaluated. In order to create such bindings, some form of initialization is required. Let us further suppose that a file named foo2.dats contains the following code:

staload "./foo.dats" dynload "./foo.dats" // for initialization implement main0 () = { val () = assertloc (4003000 = sum_x_y_z()) } (* end of [main0] *)

We can now generate an executable file mytest by issuing the following command-line:

atscc -o mytest foo.dats foo2.dats

Note that atscc may need to be changed to patscc.

The line starting with the keyword dynload is referred to as a dynload-declaration. If it is deleted from the file foo2.dats, then executing the above command-line leads to link-time reporting of undefined reference to a variable of certain name ending with the string __dynloadflag. The dynload-declaration for foo.dats introduces this special variable and then makes a call to a special function associated with foo.dats for the purpose of performing some form of initialization. This special function is referred as a dynload-function (for foo.dats), which is always idempotent.

There is also a dynload-function generated for foo2.dats. As the function main0, a variant of the special function main, is implemented in foo2.dats, the dynload-function for foo2.dats is automatically called inside the body of the main function.

If there is a reason to suppress the generation of a dynload-function, one can set the value of the flag ATS_DYNLOADFLAG to 0. For instance, no dynload-function for foo.dats is generated if the following line is added into foo.dats:


Of course, skipping proper initialization for foo.dats means that an erroneous result is expected if the function sum_x_y_z is ever called.

If there is a reason to call the dynload-function for foo2.dats explicitly, one can introduce an alias for it and then call the alias. For instance, if the following line is added to foo2.dats:

#define ATS_DYNLOADNAME "foo2_dynload"

then the dynload-function for foo2.dats is given an alias foo2_dynload.

Please find on-line the entirety of the code used in this chapter.