Const Ideas

Adam D. Ruppe destructionator at gmail.com
Fri Nov 30 10:38:07 PST 2007


I think the new const system makes sense. I think of variables as being
compile time pointers to memory (basically).

Furthermore, const() is like a compile time function that takes a type T and
returns type T that is now a constant.

const (no parenthesis) is telling the compiler something.

Similarly, import; tells the compiler to import a symbol table from a file,
whereas import("file") is a compile time function that reads in a file
and returns its data (just like std.read() but at compile time).

Henceforth, let CTF = 'compile time function'.


Thus:

int a;
Adds an entry to the compiler's variable table named 'a' that references
memory that is an int.

const(int) a;
Add an entry named 'a' that references memory that is a constant int. The
const() CTF takes the type int and returns a new type that is a constant int.

const int a;
Add a *constant* entry named 'a' that references memory that is a mutable
int.

const const(int) a;
Adds a constant entry named 'a' that references a constant integer.

Let's deconstruct that conceptually:
variable declaration := [mutability] type name;
Mutability is if the compiler's name entry can be changed (rebinded). It is
optional, and defaults to being mutable.

Type is the type of memory the variable references.

And name is of course the name.

In the above:
const is the mutability of the compiler's variable table entry.
const(int) is a CTF that returns a type - it is the actual type.
a is obviously the name.


Let's consider const(int) a; again.

a = 10; // the compiler sees this as rewriting its internal table:
// something like this: variableMap['a'] = &10;
// Of course, the address of an immediate is pretty silly, but it is consistent
// with thinking about, say, string literals.
// Let's just say the storage for a literal integer is optimized away later
// so the real program just sees immediates.

++a; // also rewriting the table:
// variableMap['a'] = &(variableMap['a'] + 1);

Once again, with strings, that makes more sense:

const(char[]) str = "hello";
// variableMap['str'] = &"hello";

str = replace(str, "hello", "world");
// variableMap['str'] = &what_replace_returns

The actual literal "hello" string pointed to is not changed, it is just
discarded, and may be left behind for the gc to collect later.


>From a usability standpoint, I think the last case there of reusing variables
for string replaces is why I think I like the current system best:

string a = "hello";
a = replace(a, ...);

Just works, making me pretend I have in place replaces.

With the proposed const(char[]) making everything const, this would break.




-- 
Adam D. Ruppe
http://arsdnet.net



More information about the Digitalmars-d mailing list