├── .gitignore ├── extraParams.hxml ├── test ├── run.hxml ├── test_signatures.sh ├── .vscode │ └── settings.json ├── SignatureTest.hx ├── pkg │ ├── VariableReturn.hx │ └── MyStringTools.hx ├── JSishString.hx ├── VariableReturnTest.hx ├── TestJSishString.hx ├── Test.hx └── ShadowTest.hx ├── haxelib.json ├── submit_haxelib.sh ├── LICENSE ├── README.md └── OverloadMacro.hx /.gitignore: -------------------------------------------------------------------------------- 1 | test/Test.n 2 | hxoverload.zip 3 | -------------------------------------------------------------------------------- /extraParams.hxml: -------------------------------------------------------------------------------- 1 | --macro addGlobalMetadata("", "@:build(OverloadMacro.build_all())") 2 | -------------------------------------------------------------------------------- /test/run.hxml: -------------------------------------------------------------------------------- 1 | -cp .. 2 | -cp . 3 | --macro addGlobalMetadata("", "@:build(OverloadMacro.build_all())") 4 | 5 | -x Test 6 | -------------------------------------------------------------------------------- /test/test_signatures.sh: -------------------------------------------------------------------------------- 1 | 2 | haxe --cwd /home/jward/dev/haxe-seoverload/test run.hxml -D display-details --display '/home/jward/dev/haxe-seoverload/test/Test.hx@144@signature' 3 | -------------------------------------------------------------------------------- /test/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "haxe.displayConfigurations": [ 3 | ["run.hxml"] 4 | ], 5 | "haxe.displayServer": { 6 | "arguments": [ 7 | "-v" 8 | ] 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/SignatureTest.hx: -------------------------------------------------------------------------------- 1 | using pkg.MyStringTools; 2 | 3 | class Test 4 | { 5 | public static function main() 6 | { 7 | trace("Haxe is great!"); 8 | var s = "my string"; 9 | 10 | s.replace( 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/pkg/VariableReturn.hx: -------------------------------------------------------------------------------- 1 | package pkg; 2 | 3 | class VariableReturn implements OverloadMacro.IOverloaded 4 | { 5 | public static function multi_return(s:String):Int { return 123; } 6 | public static function multi_return(s:String):String { return 'abc'; } 7 | 8 | } 9 | -------------------------------------------------------------------------------- /haxelib.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "overload", 3 | "url": "http://github.com/jcward/haxe-overload", 4 | "license": "MIT", 5 | "tags": ["cross","macro","utility"], 6 | "description": "Haxe macro library to support overloaded functions.", 7 | "version": "0.0.5", 8 | "releasenote": "See recently closed issues in github.", 9 | "contributors": [ "jeff.ward" ], 10 | "dependencies": {} 11 | } 12 | -------------------------------------------------------------------------------- /test/JSishString.hx: -------------------------------------------------------------------------------- 1 | @:forward 2 | abstract JSishString(String) from String to String 3 | { 4 | // FYI: non-static macro secretly passes 'this' as first arg. 5 | public macro function replace(thys:haxe.macro.Expr, params:Array):haxe.macro.Expr 6 | { 7 | var as_str:haxe.macro.Expr = macro ($e{ thys }:String); 8 | return macro OverloadMacro.check_se($e{ as_str }, 'replace', 'pkg.MyStringTools', $v{ 3 }, $a{ params }); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/VariableReturnTest.hx: -------------------------------------------------------------------------------- 1 | using pkg.VariableReturn; 2 | 3 | class Test 4 | { 5 | public static function main() 6 | { 7 | trace("Haxe is great!"); 8 | 9 | // Testing variable return types. Not currently possible... 10 | // but we *could* try to type the containing expression ;) 11 | 12 | var i:Int = s.multi_return(); 13 | trace('Got int: $i'); 14 | 15 | var s:String = s.multi_return(); 16 | trace('Got str: $s'); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /submit_haxelib.sh: -------------------------------------------------------------------------------- 1 | echo "Be sure to check version number in haxelib.json:" 2 | cat haxelib.json | grep -i version 3 | echo "lib.haxe.org currently has:" 4 | curl -Ls http://lib.haxe.org/p/overload | grep '' 5 | sleep 1 6 | read -r -p "Are you sure? [y/N] " response 7 | if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]] 8 | then 9 | rm -f hxoverload.zip 10 | zip -r hxoverload.zip OverloadMacro.hx haxelib.json extraParams.hxml README.md LICENSE 11 | haxelib submit hxoverload.zip 12 | else 13 | echo "Cancelled" 14 | fi 15 | -------------------------------------------------------------------------------- /test/TestJSishString.hx: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | public static function main() 4 | { 5 | trace("Haxe is great!"); 6 | var s:JSishString = "my string"; 7 | 8 | // uses the first signature 9 | s = s.replace('my', 'our'); 10 | trace(s); // our string 11 | 12 | // uses the second signature 13 | s = s.replace(~/str/, 'th'); 14 | trace(s); // our thing 15 | 16 | // uses the third signature 17 | s = s.replace(~/[aeiou]/g, function(match) { return match.toUpperCase(); }); 18 | trace(s); // OUr thIng 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /test/pkg/MyStringTools.hx: -------------------------------------------------------------------------------- 1 | package pkg; 2 | 3 | class MyStringTools implements OverloadMacro.IOverloaded 4 | { 5 | public static function replace(haystack:String, needle:String, by:String):String { 6 | return StringTools.replace(haystack, needle, by); 7 | } 8 | 9 | public static function replace(haystack:String, needle:EReg, by:String):String { 10 | return needle.replace(haystack, by); 11 | } 12 | 13 | public static function replace(haystack:String, needle:EReg, replacer:String->String):String { 14 | return needle.map(haystack, function(e) { 15 | return replacer(e.matched(0)); 16 | }); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/Test.hx: -------------------------------------------------------------------------------- 1 | using pkg.MyStringTools; 2 | 3 | class Test 4 | { 5 | public static function main() 6 | { 7 | trace("Haxe is great!"); 8 | var s = "my string"; 9 | 10 | // uses the first signature 11 | s = s.replace('my', 'our'); 12 | trace(s); // our string 13 | 14 | // uses the second signature 15 | s = s.replace(~/str/, 'th'); 16 | trace(s); // our thing 17 | 18 | // uses the third signature 19 | s = s.replace(~/[aeiou]/g, function(match) { return match.toUpperCase(); }); 20 | trace(s); // OUr thIng 21 | 22 | var q = new Foo(); 23 | q.replace(); 24 | } 25 | } 26 | 27 | class Foo extends Base 28 | { 29 | public function new() { super(); } 30 | } 31 | 32 | class Base 33 | { 34 | public function new() { } 35 | public function replace() { 36 | trace('Oh no, I got shadowed!'); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/ShadowTest.hx: -------------------------------------------------------------------------------- 1 | using pkg.MyStringTools; 2 | 3 | class Test 4 | { 5 | public static function main() 6 | { 7 | trace("Haxe is great!"); 8 | var s = "my string"; 9 | 10 | // uses the first signature 11 | s = s.replace('my', 'our'); 12 | trace(s); // our string 13 | 14 | // uses the second signature 15 | s = s.replace(~/str/, 'th'); 16 | trace(s); // our thing 17 | 18 | // uses the third signature 19 | s = s.replace(~/[aeiou]/g, function(match) { return match.toUpperCase(); }); 20 | trace(s); // OUr thIng 21 | 22 | var q = new Foo(); 23 | q.replace(); 24 | } 25 | } 26 | 27 | class Foo extends Base 28 | { 29 | public function new() { super(); } 30 | } 31 | 32 | class Base 33 | { 34 | public function new() { } 35 | public function replace() { 36 | trace('Oh no, I got shadowed!'); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Jeff Ward 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # haxe-overload 2 | Haxe macro library to support overloaded functions (via static extension, or abstract.) 3 | 4 | - Status: beta / exploratory 5 | - [Discussion thread](https://community.haxe.org/t/toying-with-a-macro-for-overloading-via-static-extension/840/) 6 | 7 | ## Purpose 8 | 9 | Haxe doesn't natively support overloaded functions. That's probably for the best. But some 10 | APIs just feel nicer with overloaded methods. 11 | 12 | For example, I suggest JavaScript's [String.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) 13 | API -- which takes strings, regular expressions, and a replacement string or a replacer function -- is rather tidy. I don't have 14 | to remember that, in Haxe's native API, these capabilities are spread out under `StringTools.replace`, `EReg.replace`, 15 | and `EReg.map`. 16 | 17 | But to achieve this in native, staticly typed Haxe, I'd need 1) some way to map my calls to the correct 18 | function signature, and 2) proper VSCode completion support. That is precisely what this library does. 19 | 20 | It lets you write libraries that look like this: 21 | 22 | ![image](https://user-images.githubusercontent.com/2192439/42594874-bb05089c-850d-11e8-90b8-7e5cd50ab7d9.png) 23 | 24 | And by `using MyStringTools` it provides overloaded functions via static extension, even with proper code completion: 25 | 26 | ![compl](https://user-images.githubusercontent.com/2192439/42593316-54306188-8509-11e8-86ed-cea293722f59.gif) 27 | 28 | ## Limitations 29 | 30 | - The functions are renamed under the hood, so you can't call them dynamically at runtime. Let me know if you're interested in runtime invocation. 31 | - Currently return types must always be the same. 32 | - See issues. 33 | 34 | ## Terminology 35 | 36 | Let's use the simple phrase "tools class" to mean, a class with (zero or more) overloaded methods, 37 | intended to be used as a static extension. 38 | 39 | ## Requirements 40 | 41 | - Your tools class must implement `OverloadMacro.IOverloaded` 42 | - Overloaded methods must be static functions of a tools class. 43 | 44 | ## Install 45 | 46 | ### Via Haxelib: 47 | 48 | 1) Install: `haxelib install overload` 49 | 50 | 2) Add to your build.hxml file: `-lib overload` 51 | 52 | ### Manually: 53 | 54 | 1) Copy `OverloadMacro.hx` into your class path 55 | 56 | 2) Add to your build.hxml file the contents of extraParams.hxml: 57 | 58 | ```haxe 59 | --macro addGlobalMetadata("", "@:build(OverloadMacro.build_all())") 60 | ``` 61 | 62 | ## Usage 63 | 64 | The overload library doesn't include any tools classes by default. You're expected 65 | to write them. Here's an example tools class: 66 | 67 | ```haxe 68 | package some.pkg; 69 | 70 | // Provides three replace methods on String, similar to JavaScript's str.replace() 71 | class MyStringTools implements OverloadMacro.IOverloaded 72 | { 73 | public static function replace(haystack:String, needle:String, by:String):String { 74 | return StringTools.replace(haystack, needle, by); 75 | } 76 | 77 | public static function replace(haystack:String, needle:EReg, by:String):String { 78 | return needle.replace(haystack, by); 79 | } 80 | 81 | public static function replace(haystack:String, needle:EReg, replacer:String->String):String { 82 | return needle.map(haystack, function(e) { 83 | return replacer(e.matched(0)); 84 | }); 85 | } 86 | } 87 | ``` 88 | 89 | And now you can use this tools class like so: 90 | 91 | ```haxe 92 | using some.pkg.MyStringTools; 93 | 94 | class Test 95 | { 96 | public static function main() 97 | { 98 | trace("Haxe is great!"); 99 | var s = "my string"; 100 | 101 | // uses the first signature 102 | s = s.replace('my', 'our'); 103 | trace(s); // our string 104 | 105 | // uses the second signature 106 | s = s.replace(~/str/, 'th'); 107 | trace(s); // our thing 108 | 109 | // uses the third signature 110 | s = s.replace(~/[aeiou]/g, function(match) { return match.toUpperCase(); }); 111 | trace(s); // OUr thIng 112 | } 113 | } 114 | ``` 115 | -------------------------------------------------------------------------------- /OverloadMacro.hx: -------------------------------------------------------------------------------- 1 | #if macro 2 | 3 | import haxe.macro.Compiler; 4 | import haxe.macro.Context; 5 | import haxe.macro.Expr; 6 | import haxe.macro.ExprTools; 7 | 8 | import haxe.ds.StringMap; 9 | 10 | using haxe.macro.ExprTools; 11 | using haxe.macro.TypeTools; 12 | 13 | using Lambda; 14 | 15 | typedef OVInfoType = { 16 | se_cls : haxe.macro.Type.ClassType, 17 | cnt_per_field : StringMap<Int>, 18 | cls_name:String 19 | } 20 | 21 | class OverloadMacro 22 | { 23 | 24 | private static inline var OVERLOAD_META_NAME = 'overload_macro'; 25 | private static inline function overload_suffix(i:Int) return '__ovr_${i}'; 26 | 27 | // Build macro that runs on the overloaded SE Tools classes 28 | public static macro function build_overloaded():Array<Field> 29 | { 30 | var cls = Context.getLocalClass().get(); 31 | var fields:Array<Field> = Context.getBuildFields(); 32 | 33 | var fields_by_name = new StringMap<Array<Field>>(); 34 | for (field in fields) { 35 | // only applies to static functions 36 | if (field.access.has(AStatic)) { 37 | switch field.kind { 38 | case FFun(f): 39 | if (!fields_by_name.exists(field.name)) fields_by_name.set(field.name, []); 40 | fields_by_name.get(field.name).push(field); 41 | default: 42 | } 43 | } 44 | } 45 | 46 | var overload_metadata = []; 47 | for (name in fields_by_name.keys()) { 48 | // Only fields with more than 1 instance 49 | if (fields_by_name.get(name).length<2) continue; 50 | 51 | // Hmm, can't push a Map<String, Int> through meta... 52 | // overload_cnt.set(name, fields_by_name.get(name).length); 53 | overload_metadata.push(macro $v{ name }); 54 | overload_metadata.push(macro $v{ fields_by_name.get(name).length }); 55 | var i = 0; 56 | for (field in fields_by_name.get(name)) { 57 | // Need to rename the fields. 58 | field.name = '${ name }${ overload_suffix(i) }'; 59 | 60 | // TODO? Could possible ensure unique args here... 61 | i++; 62 | } 63 | } 64 | 65 | // Add overload metadata (StringMap<Int> didn't work in getValue... using Dynamic) 66 | // Could map this way... 67 | // var meta_expr = Context.parse('[ '+[ for (key in overload_cnt.keys()) '"$key" => ${ overload_cnt.get(key) }' ].join(',')+']', Context.currentPos()); 68 | cls.meta.add(OVERLOAD_META_NAME, overload_metadata, Context.currentPos()); 69 | 70 | #if display // In display mode, generate a custom class with @:overload metadata 71 | var cls_name = (cls.pack.length>0 ? cls.pack.join('.') : '') + '.' + cls.name; 72 | handle_display_mode(cls_name, fields_by_name); 73 | #end 74 | 75 | return fields; 76 | } 77 | 78 | 79 | #if display 80 | // In display mode, we need to populate a method with the proper @:overload 81 | // so that we can display multiple function signatures: 82 | private static function handle_display_mode(cls_name:String, fields_by_name:StringMap<Array<Field>>) 83 | { 84 | var dcn = display_class_name(cls_name); 85 | var ot = macro class $dcn { }; 86 | for (name in fields_by_name.keys()) { 87 | // Only fields with more than 1 instance 88 | var overloads = fields_by_name.get(name); 89 | if (overloads.length<2) continue; 90 | // Take the first field, and put it on the display class 91 | var first = overloads.shift(); 92 | first = { 93 | name:name, 94 | access:first.access, 95 | kind:first.kind, 96 | pos:first.pos, 97 | meta:first.meta 98 | }; 99 | ot.fields.push(first); 100 | // Take the remaining fields, and set @:overload metadata with them: 101 | for (other in overloads) { 102 | switch other.kind { 103 | case FFun(f): 104 | var signature = { expr:EFunction(null, { args:f.args, ret:f.ret, expr:{ expr:EBlock([]), pos:first.pos} }), pos:first.pos }; 105 | var overload_meta = { name:':overload', params:[signature], pos:first.pos }; 106 | first.meta.push(overload_meta); 107 | default: 108 | } 109 | } 110 | } 111 | 112 | // Define the for-display-only class: 113 | Context.defineType(ot); 114 | } 115 | private static function display_class_name(n:String):String 116 | { 117 | return 'Overloaded__${ n.split(".").join("_") }'; 118 | } 119 | #end 120 | 121 | // Build macro added to *all* classes be extraParams.hxml -- careful, 122 | // be extremely performance minded 123 | public static macro function build_all():Array<Field> 124 | { 125 | var fields:Array<Field> = Context.getBuildFields(); 126 | 127 | var cref = Context.getLocalClass(); 128 | if (cref==null) return fields; 129 | var cls = cref.get(); 130 | if (cls==null) return fields; 131 | 132 | // Examine each class in the 'using' declarations 133 | for (used in Context.getLocalUsing()) { 134 | var se_cls = used.get(); 135 | 136 | // Check for the overloaded metadata 137 | var meta = se_cls.meta.extract(OVERLOAD_META_NAME)[0]; 138 | if (!(meta!=null && meta.params!=null && meta.params.length>0)) continue; 139 | 140 | // Convert metadata to StringMap<Int> (why doesn't $v{} support ["foo"=>5] ?) 141 | var overload_cnt = new StringMap<Int>(); 142 | var i = 0; 143 | while (i<meta.params.length) { 144 | overload_cnt.set( meta.params[i].getValue(), meta.params[i+1].getValue() ); 145 | i += 2; 146 | } 147 | // trace(overload_cnt); // e.g. { replace=>5, to_array=>3 } 148 | 149 | // trace('In ${ cls.name } using: ${ se_cls.name }'); 150 | var cls_name = (se_cls.pack.length>0 ? se_cls.pack.join('.') : '') + '.' + se_cls.name; 151 | var se_info = { se_cls:se_cls, cnt_per_field:overload_cnt, cls_name:cls_name }; 152 | 153 | for(field in fields) { 154 | switch (field.kind) { 155 | case FVar(t, e): 156 | field.kind = FVar(t, modifyExpr(e, se_info)); 157 | case FProp(get, set, t, e): 158 | field.kind = FProp(get, set, t, modifyExpr(e, se_info)); 159 | case FFun(f): 160 | f.expr = modifyExpr(f.expr, se_info); 161 | } 162 | } 163 | } 164 | 165 | return fields; 166 | } 167 | 168 | 169 | private static function modifyExpr(expr:Expr, se_info:OVInfoType):Expr 170 | { 171 | if (expr == null) return null; 172 | 173 | switch (expr.expr) { 174 | case ECall({ expr:EField(subject, field_name) }, params): 175 | if (se_info.cnt_per_field.exists(field_name)) { 176 | var mapped_params = [ for (e in params) modifyExpr(e, se_info) ]; 177 | var pe:Expr = macro $a{ mapped_params }; 178 | #if display 179 | // In display mode, we bounce the call to a generated Overload__<cls_name> clss, 180 | // which has a <field_name> function with the proper @:overload metadata. 181 | var disp_cls = display_class_name(se_info.cls_name); 182 | var rtn = macro $i{ disp_cls }.$field_name(($pe : Array<Expr>)); 183 | #else 184 | var rtn = macro OverloadMacro.check_se($subject, $v{ field_name }, $v{ se_info.cls_name }, $v{ se_info.cnt_per_field.get(field_name) }, ($pe : Array<Expr>)); 185 | #end 186 | rtn.pos = expr.pos; // Report type errors at the site of the function call 187 | // trace(rtn.toString()); 188 | return rtn; 189 | } 190 | default: 191 | } 192 | 193 | return ExprTools.map(expr, function(e) { return modifyExpr(e, se_info); }); 194 | } 195 | 196 | private static function unwrap_to_array(expr:ExprDef):Array<Expr> { 197 | return switch expr { 198 | case EArrayDecl(ps): ps; 199 | case EParenthesis(e): return unwrap_to_array(e.expr); 200 | case ECheckType(e, _): return unwrap_to_array(e.expr); 201 | case EUntyped(e): return unwrap_to_array(e.expr); 202 | default: throw 'Error: unexpected expr looking for EArrayDecl: $expr'; 203 | } 204 | } 205 | 206 | public static function check_se(subject:Expr, field_name:String, cls_name:String, num:Int, params:Expr):Expr 207 | { 208 | var ps = unwrap_to_array(params.expr); 209 | 210 | // First, check if subject function call is valid (without overloading) 211 | try { 212 | var eval = macro ${ subject }.$field_name($a{ ps }); 213 | //trace('${ eval.toString() }'); 214 | var t = Context.typeof(eval); 215 | //trace('WITHOUT OVERLOADING, TYPE IS: $t'); 216 | return eval; 217 | } catch (e:Dynamic) { } 218 | 219 | // No? Ok, let's check overloads... 220 | 221 | // Put the subject expression first in the list (ala static extension) 222 | ps.unshift( subject ); 223 | 224 | // We will simply try typing each function call. 225 | for (i in 0...num) { 226 | 227 | // Note: we could try to see if subject was the same type as the first 228 | // function arg... but the compiler will already do that for us. 229 | var expanded_field = '${ field_name }${ overload_suffix(i) }'; 230 | var eval = macro $p{ cls_name.split('.') }.$expanded_field($a{ ps }); 231 | 232 | try { 233 | //trace('${ eval.toString() }'); 234 | var t = Context.typeof(eval); 235 | //trace('WITH OVERLOADING, TYPE IS: $t'); 236 | return eval; 237 | } catch (e:Dynamic) { 238 | // Not correctly typed, try the next signature 239 | } 240 | } 241 | 242 | Context.error('No suitable overload found for ${ subject.toString() }.$field_name, params: ${ ps.toString() }', Context.currentPos()); 243 | return macro null; 244 | } 245 | 246 | } 247 | 248 | 249 | #else 250 | 251 | import haxe.macro.Expr; 252 | 253 | class OverloadMacro 254 | { 255 | public static macro function check_se(subject:Expr, field_name:String, cls_name:String, num:Int, params:Expr):Expr 256 | { 257 | return null; 258 | } 259 | } 260 | 261 | #end 262 | 263 | @:autoBuild(OverloadMacro.build_overloaded()) 264 | interface IOverloaded 265 | { 266 | } 267 | --------------------------------------------------------------------------------