Proposal for scoped const contracts

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 24 10:34:16 PDT 2008


"Steven Schveighoffer" wrote in message
> This idea has come from the discussion on the const debacle thread.
>
> It is basically an idea for scoped const.  The main goal is so that one 
> can specify that a function does not modify an argument without affecting 
> the constness of the input.
> ...

I have thought of an additional specification that I've left out, regarding 
calling functions from within a scoped const function.

If a function with scoped const calls another function, the following rules 
apply:

 - if the second function is a scoped const function, and the parameters 
passed to the scoped const function are declared with 'in', then the 
resulting 'out' of the second function can be returned from the outer 
function, or can be assigned to another 'in' variable.
 - if the second function is not a scoped const function, or the parameters 
passed to the second function are not declared with 'in', then the result of 
the second function cannot be assigned to an 'in' variable.

For example:

out(T) g(in(T) t){...}
const(T) h(const(T) t) {...}

out(T) f(in(T) t)
{
  t = g(t); // OK, g is scoped const
  in(T) a = g(t); // ok, assigning to scoped const variable
  const(T) b = g(t); // ok, in(T) is implicitly castable to const.
  in(T) c = h(t); // Error, cannot implicitly cast const to in.
  in(T) d = h(b); // Error, b is not in(T), so the result is the type of b, 
even if f was called with a const(T)
  const(T) d = h(t); // OK, can cast in(T) to const(T) before calling h
  return a; // OK
}

-Steve 





More information about the Digitalmars-d mailing list