2024-02-09 06:05:35 UTC
Modula-2 had this interesting feature where, for example if you had a
pointer variable whose pointed-to objects were of type T
ptr : POINTER TO T;
and you had a statement like
ptr := NEW(T);
then the compiler would translate the “NEW(T)” into “ALLOCATE(TSIZE(T))”,
where the “ALLOCATE” function was not actually provided by the language,
but had to be defined/introduced in the current scope somehow (perhaps
IMPORTed from some implementation-provided library).
This allowed for memory allocations (and also deallocations) to be
expressed in a type-safe fashion, while still leaving the low-level
details of memory management up to some library/user code that was not an
integral part of the language implementation.
So you had a builtin function, NEW(), that could take a type as an
argument and return a result of the appropriate pointer type, which a
normal user-defined function could not do, but the compiler would delegate
the main work to a lower-level function that didn’t need to know anything
about the language type system, it only needed to know how much memory to
allocate, and would return an untyped pointer, which the compiler would
then take care of turning into a pointer of the required type.
C could benefit from some similar high-level+low-level layering like this,
don’t you think?