back2dos / tinkerbell

MIT License
83 stars 8 forks source link

Replace parameters with impl parameters #56

Open MetaChrome opened 11 years ago

MetaChrome commented 11 years ago

Hey, just wanted to offer this code which might be useful in having in the toolkit:

function replace_args_with_params(arg_complex_type:ComplexType,impl_complex_type_params:Array<TypeParam>,
    class_type_params:Array<{t:Type,name:String}>):Void {
    switch(arg_complex_type) {
        case TPath(p):
            var i:Int=0;
            for(class_type_param in class_type_params) {
                if(p.name==class_type_param.name) {
                    break;
                }
                i++;
            }
            if(i<class_type_params.length) {
                var impl_param:TypeParam=impl_complex_type_params[i];
                switch(impl_param) {
                    case TPType(impl_param_complex_type):
                        switch(impl_param_complex_type) {
                            case TPath(impl_param_path):
                                p.name=impl_param_path.name;
                                p.pack=impl_param_path.pack;
                                p.params=impl_param_path.params;
                                p.sub=null;
                            default:
                        }
                    default:
                }
            }
            for(param in p.params) {
                switch(param) {
                    case TPType(param_complex_type):
                        replace_args_with_params(param_complex_type,impl_complex_type_params,class_type_params);
                    default:
                }
            }
        default:
    }
}

You have a function(constructor) that requires parametrized arguments:

class <T,T2> {
     new(v:T,v:T2)
 }

You want to generate a second function (singleton constructor) that outputs Class<MyT,MyT2> and so would require an argument signature that is identical to the original function except with the implementation parameters substituted:

function singleton(v1:My2,v2:MyT2):Class<MyT,MyT2>

Of course there are more general forms of the above considering that functions can be parametrized in haxe.

Perhaps there are other forms of this type of thing that might be interesting to explore to its logical conclusion.