catb0t / tart

Automatically exported from code.google.com/p/tart
0 stars 0 forks source link

Design: Conditional casting #1

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
We need a way for dynamic cast to operate on disjoint types.

The C++ dynamic_cast operator is used to do a type-safe downcast, from a base 
class to some 
subclass. If the actual type of the input argument is not compatible with the 
desired type, then 
the cast fails and NULL is returned. The calling code should test for this NULL 
value before 
proceeding to use the result value. The C++ dynamic cast function can only 
operate on pointers.

I would like to generalize the dynamic_cast concept into a "conditional cast" 
operation.

A conditional cast would allow casting of a general type into a more specific 
type. This not only 
includes reference types, but disjoint types as well - so an expression of type 
"int or float" could 
be conditionally-cast to "int", and if the cast succeeds, the assignment is 
performed. If the cast 
fails, then not only should the assignment *not* be performed, but the control 
flow should never 
be allowed to enter a scope where the failed assignment is visible.

This latter part can easily be done by making the conditional cast syntax part 
of the 'if' and 
'while' statements. The test expression will contain a variable declaration - 
similar to the "if let x 
= y" syntax. If the assignment succeeds, then the body of the statement is 
executed, which then 
has access to the assigned variable. If the cast does not succeed, then we skip 
over the body of 
the if-statement, so that the variable is never in scope.

What is missing is some sort of syntax - a variation of the "if" and "while" 
statements - that 
convey to the programmer that this is not a normal test expression, but a 
conditional cast.

It should also convey the idea that what is being tested is not the *value* of 
the condition, but 
rather whether or not the assignment was successful. Take for example the case 
where a disjoint 
type of "bool or float" contains the value "false", and we attempt to 
conditionally cast it to a 
boolean. Normally, an expression that evaluates to false, when used as a test 
expression, would 
cause the if-body not to be executed. However, in this case, the value of 
"false" is not what is 
being tested, but rather the fact that it's a value that can be coerced into a 
boolean. There is 
likely to be some confusion caused by this unless the syntax for conditional 
casts looks 
sufficiently different from a normal if statement.

Original issue reported on code.google.com by viri...@gmail.com on 20 Jul 2009 at 5:57

GoogleCodeExporter commented 8 years ago
Fixed with the addition of the new "classify" statement.

Original comment by viri...@gmail.com on 28 Aug 2009 at 12:35