[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-dev] closing a function

On Dec 20, 2004, at 1:03 AM, Julian Rohrhuber wrote:
so after the compiler has done its work it would be possible to check
if there is any variable references into the context at compile time.
If there is none, the function is "closed" already and its sourceCode can be
So would it be possible to make a non closed function that has no variable references into its context reproduce as compile string?

the function's context also determines where it returns to with a non local return. If you were to close the function automatically it would change this.

	myMethod {
		var f, g;
		f = #{ ^123 };
		g = { ^456 };
		([f,g] @@ this).value

0.myMethod; // never returns a value because the non local return is made out of context.
1.myMethod; // 456

 x = { arg func;
	var d, l;
	l = [];
	d = func.def.context;
 	while {  d.notNil } {
 		d = d.context;
 		if(d.notNil) { l = l ++ d.varNames };

This checks what variables can be referred to, it doesn't check if any ARE referred to. And it doesn't look at arguments, which can also be referred to in closures. Nor does it look at instance variables which are accessible from closures, but not from closed functions (for which the instance variables in scope are those of the interpreter). And it is going to be very rare that a function has no arguments or variables in its enclosing contexts. To determine if a function has references to free variables, you'd have to decompile the byte code. The compiler could do this check at compile time. But it would have to check a number of other things like whether a nonlocal return is possible from the function.

f = { var a = 1; { var b = 2; { { [a, b].postln; } }.value }.value }.value;


f = { var a = 1; #{ var b = 2; { { [a, b].postln; } }.value }.value }.value;

note that in this case 'a' refers to interpreter variable 'a'.

Just write closed functions when you want closed functions.