Version française
Home     About     Download     Resources     Contact us    
Browse thread
Function application implementation
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: skaller <skaller@u...>
Subject: Re: [Caml-list] Function application implementation
On Thu, 2007-04-26 at 10:52 +0200, Tom wrote:
> 
> 
> On 26/04/07, skaller <skaller@users.sourceforge.net> wrote:
>         It knows the type of the function expression, and that is all
>         that is required. Incidentally Ocaml evaluates right to left.
>         So
>         
>                 f x y z
>         
>         will be roughly:
>         
>                 push (eval z)
>                 push (eval y) 
>                 push (eval x)
>                 push (eval f)
>                 apply
>                 apply
>                 apply
> 
> But that doesn't explain how does each apply know what to do, either
> to build a new closure (in the case above, the first two applies) or
> to actually call the code (the third apply). 

push (eval f) calculates the expression f,
which results in a closure. Apply, with the stack:

	closure f <-- top
	value 1
	...

calculates 

	apply(closure f, value 1)

That is how functions are called. In practice, a compiler may do
optimisations.

In the Felix compiler for example, in the expression:

	apply(f,e)

if the subexpresion f is a simple function constant, then the compiler
can inline the function. Otherwise, a closure has to be formed. In Felix
this means instantiating a C++ class (the function f) to make a closure
(an object of the class). In Felix the actual C++ used is:

	(new f(environment)) -> apply (e)

In other words, all compilers will look for optimisations such
as are made possible when a direct call is detected, inlining
in such cases being one possible optimisation which could be applied.

the actual sequence I have above may not be how the Ocaml compiler
organises it: the point is that the model is built to not need
to make the distinction you're asking about: that's just an 
optimisation.

-- 
John Skaller <skaller at users dot sf dot net>
Felix, successor to C++: http://felix.sf.net