AlekId / dwscript

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

Type constraints suggestion #382

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
As a feature suggestion, maybe it could be possible to add type constraints to 
the language?

An example:

type
  Byte = Integer constrained by (Self >= 0) and (Self <= 255);

If the assigned value does not meet the constraint, a constraint failure 
exception could be thrown. Or a handler could be assigned, so in the case of 
the Byte example, the values could be wrapper around, like the behavior in 
Delphi.

Something like:

type
  Byte = Integer constrained (Self >= 0) and (Self <= 255) handled (Self := (Self mod 256 + 256) mod 256);

There's probably a better way of doing this, it's just a first thought. Though 
the limited amount of base types makes things easy, it does occasionally pose 
some issues, when for example writing to a stream. Without a "WriteByte" 
method, or something similar, it wouldn't be possible to write a single byte to 
a stream.

Implementing pre/post conditions might achieve a similar result, but I'm not 
sure these are usually also applied for basic types.

Original issue reported on code.google.com by frederic...@gmail.com on 30 Apr 2013 at 12:47

GoogleCodeExporter commented 9 years ago
Hmmm, this might be possible by providing language extensions the ability to 
specify custom assignment expressions. However the checks would only happen 
when assigning to a variable or a field, not for intermediate computations.

ie. if v was a Byte of initial value 255, "v := v+v-v" would pass while "v := 
v+v" would trigger the constraint violation.

Original comment by zar...@gmail.com on 3 May 2013 at 10:14