Automatic argument check
5nord opened this issue · comments
All built-in or external functions have to check their arguments explicitly. Usually this look like this:
func Int2str(args ...runtime.Object) runtime.Object {
if len(args) != 1 {
return runtime.Errorf("wrong number of arguments. got=%d, want=1", len(args))
}
number, ok := args[0].(runtime.Int)
if !ok {
return runtime.Errorf("%s arguments not supported", args[0].Type())
}
if !number.IsInt64() {
return runtime.Errorf("Provided argument is not 64bit-integer")
}
return &runtime.String{Value: []rune(fmt.Sprintf("%d", number.Int64()))}
}
func init() {
runtime.AddBuiltin("int2str", Int2str)
}
Those checks are very repetitive and distract from relevant parts of the implementation.
Proposal
Allow formal parameters to be specified during registration. When formal parameters are specified, decorate built-in function with an argument-checker. Example:
func Int2str(args ...runtime.Object) runtime.Object {
number := args[0].(runtime.Int)
if !number.IsInt64() {
return runtime.Errorf("Provided argument is not 64bit-integer")
}
return &runtime.String{Value: []rune(fmt.Sprintf("%d", number.Int64()))}
}
func init() {
runtime.AddBuiltin("int2str(integer i)", Int2str)
}