[M3devel] function pointers and comparison to nil? mis-typed function pointers?

Rodney M. Bates rodney.bates at wichita.edu
Sun Jun 1 04:32:37 CEST 2008



Jay wrote:
> 
> I don't understand "can only assign a top-level procedure".
> My understanding is that Modula-3 does allow the "unsafe" option -- take 
> the address of a nested function, pass it off to some code, that stores 
> it in a global, and call it later. But of course, "Modula-3 does allow 
> the unsafe option" does not compute. I need to read up and experiment.

No, Modula-3 does not allow the above.  The only thing you can do with
a nested procedure is pass it as a parameter.  The lifetime of the
parameter will always lie within the lifetime of the current activation
of the the nested procedure, so this is safe.

If you try to assign a procedure to a variable/field/array-element, the
language says the procedure value must be top-level.  (See 2.3.1, assignability
of an expression to a variable, second condition.) This is also safe. If
the RHS of the assignment is a procedure constant, this can be checked
statically.  If the RHS is a formal parameter (thus variable at runtime),
this must be a runtime check, because its value could be a nested procedure.

The compiler implements the RT check by checking whether the pointer points
to a closure or not, or rather, whether it points to a closure flag word.
This implementation choice of representation of procedure values correctly
implements the language, while still making global procedure values have
the same representation as C pointers to (global) functions.

>  
> Maybe there is a runtime check whenever I assign a function pointer to 
> either a global or to a field in non-local record, that it isn't a closure?
> That makes a fair amount of sense though hard to not make the check 
> overly strict I think.

Yes, this is not the loosest safe rule.  Hardly anything is, in a safe
language.  The language designers have to make careful tradeoffs among
programmer freedom, efficient implementability, and language simplicity.
This is just the way Modula-3 makes the tradeoff to prevent dangling
environment pointer bugs from happening.

>  
>-- 
-------------------------------------------------------------
Rodney M. Bates, retired assistant professor
Dept. of Computer Science, Wichita State University
Wichita, KS 67260-0083
316-978-3922
rodney.bates at wichita.edu



More information about the M3devel mailing list