├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── examples │ └── com │ │ └── github.forax │ │ └── macro │ │ └── example │ │ ├── almostconstant.java │ │ ├── builder1.java │ │ ├── builder2.java │ │ ├── builder3.java │ │ ├── fmt.java │ │ └── multimethods.java └── java │ └── com │ └── github │ └── forax │ └── macro │ └── Macro.java └── test └── java └── com └── github └── forax └── macro ├── DeoptimizableTest.java ├── ExampleTest.java ├── MacroTest.java └── ParameterTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Macro Library 2 | 3 | Unlike a traditional macro system which transform the source code at compile time, 4 | this library provide building bricks to create macros at runtime with no modification to the Java syntax. 5 | 6 | A macro is a method call that is able to extract/separate the constants arguments from 7 | the other live arguments allowing to transform/pre-compute data from the constants. 8 | This is close to the LISP way of doing macro by [quoting](https://en.wikipedia.org/wiki/Lisp_(programming_language)#Self-evaluating_forms_and_quoting) 9 | (here consider as constant) arguments of a method call. 10 | 11 | For example, instead of using reflection to dynamically calls methods 12 | ```java 13 | public class Foo { 14 | public double bar(int value) { ... } 15 | public double baz(int value) { ... } 16 | } 17 | 18 | public static String call(Foo foo, String name, int value) { 19 | Method method = Foo.class.getMethod(name, int.class); 20 | return (double) method.invoke(foo, 3); 21 | } 22 | ``` 23 | 24 | one can use `Macro.createMH` to implement the same idea 25 | ```java 26 | private static final MethodHandle MH; 27 | static { 28 | Lookup lookup = MethodHandles.lookup(); 29 | MH = Macro.createMH(MethodType.methodType(double.class, Foo.class, String.class, int.class), 30 | List.of(Macro.VALUE, Macro.CONSTANT_VALUE.polymorphic(), Macro.VALUE), 31 | (constants, type) -> { 32 | String name = (String) constants.get(0); 33 | return lookup.findVirtual(Foo.class, name, MethodType.methodType(double.class, int.class)).asType(type); 34 | }); 35 | } 36 | 37 | public static double call(Foo foo, String name, int value) { 38 | try { 39 | return (double) MH.invokeExact(foo, name, value); 40 | } catch(Throwable t) { 41 | throw Macro.rethrow(t); 42 | } 43 | } 44 | ``` 45 | 46 | It's a lot of more code, but it's way faster because the VM is able to fully inline all the calls thanks to 47 | the use of an inlining cache. 48 | 49 | `Macro.createMH` takes 3 parameters: 50 | - a method type which are the declared parameter types and the return type of the resulting method handle 51 | - a list of `Parameter` that indicates if a parameter is a constant and how it behaves 52 | In the example above, the class of the second parameter is constant (`CONSTANT_VALUE`) and if there are more 53 | than one constant, a __polymorphic inlining cache__ is used. The first and last parameter as just value (VALUE) 54 | so will not be treated specially. 55 | - a `Linker`, a lambda that takes a list of constants and a method type and returns a method handle of that type 56 | In the example above, the linker will be called at most twice, once per declared method. 57 | 58 | There are 3 kinds of `Parameter` 59 | - a `ConstantParameter` to extract a constant from it. 60 | The general form takes a projection function (`ProjectionFunction`) that is used to extract the constant from a value, 61 | a boolean that indicates if the value should be dropped or not and a `ConstantPolicy` that indicates 62 | how to react if there are several values for the constant (emit an error, re-link or construct a polymorphic 63 | inlining cache). There are two default implementation `Macro.CONSTANT_VALUE` if the value is itself the constant 64 | and `Macro.CONSTANT_CLASS` if the class of the value is the constant. 65 | - an `IgnoreParameter` to ignore an argument. 66 | `Macro.IGNORE` is the singleton instance of an `IgnoreParameter`. 67 | - and a `ValueParameter` to do nothing special on an argument. 68 | `Macro.VALUE` is the singleton instance of a `ValueParameter`. 69 | 70 | 71 | ## How to design an API around the Macro library 72 | 73 | Having an API that provides a method handle is nice for a low level API but not super user-friendly because 74 | `java.lang.invoke.MethodHandle` is not a well known class and it's ergonomics, mostly invoke` or `invokeExact` needs 75 | the return type to be specified by a cast, and they throw a Throwable which does not play well with the rest of 76 | the Java code. 77 | 78 | There is a workaround to not expose a method handle to the use while keeping the performance, the idea 79 | is to store the method handle in an unmodifiable field of either a lambda (as a capture parameter) or 80 | a record (unlike lambda and record, final fields of classes and enum are modifiable by reflection so 81 | are not considered as trully constant by the VM/JIT). 82 | 83 | Exposing the implementation, the lambda or the record is obvously not recommended so we will use an 84 | interface to hide the impelmentation. 85 | 86 | Here is the code template using a lambda 87 | ```java 88 | interface Foo { 89 | String m(Object o, int i); 90 | 91 | static Foo of(Lookup lookup) { 92 | var mh = Macro.createMH(...); 93 | return (o, i) -> { 94 | try { 95 | return (String) mh.invokeExact(o, i); 96 | } catch(Throwable t) { 97 | throw Macro.rethrow(t); 98 | } 99 | }; 100 | } 101 | } 102 | ``` 103 | 104 | `Macro.rethrow()` allows to throw any `Throwable`without the compiler seeing it as checked exception. 105 | This allows to sneak any checked exceptions because it can cause great harm, it should be only use to rethrow 106 | an exception raised by `invoke()` or `invokeExact()`. 107 | 108 | and the code template using a record 109 | ```java 110 | interface Foo { 111 | String m(Object o, int i); 112 | 113 | static Foo of(Lookup lookup) { 114 | record FooImpl(MethodHandle mh) implements Foo { 115 | public String m(Object o, int i) { 116 | try { 117 | return (String) mh.invokeExact(o, i); 118 | } catch(Throwable t) { 119 | throw Macro.rethrow(t); 120 | } 121 | } 122 | } 123 | var mh = Macro.createMH(...); 124 | return new FooImpl(mh); 125 | } 126 | } 127 | ``` 128 | 129 | With that design, performance will be great if the user store the instance of `Foo` in a `static` `final` field. 130 | 131 | 132 | ## More examples 133 | 134 | Several examples are available, 135 | - A record builder [builder1](src/main/examples/com/github.forax/macro/example/builder1.java), 136 | [builder2](src/main/examples/com/github.forax/macro/example/builder2.java) and 137 | [builder3](src/main/examples/com/github.forax/macro/example/builder3.java). 138 | - A string formatter [fmt](src/main/examples/com/github.forax/macro/example/fmt.java) (like `String.format()`). 139 | - A constant that can be changed [almostconstant](src/main/examples/com/github.forax/macro/example/almostconstant.java). 140 | 141 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.forax.macro 8 | macro 9 | 1.0-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | 14 | 15 | 16 | 17 | org.junit.jupiter 18 | junit-jupiter-api 19 | 5.8.2 20 | test 21 | 22 | 23 | org.junit.jupiter 24 | junit-jupiter-params 25 | 5.8.2 26 | test 27 | 28 | 29 | 30 | 31 | 32 | 33 | org.apache.maven.plugins 34 | maven-compiler-plugin 35 | 3.8.1 36 | 37 | 17 38 | 39 | --enable-preview 40 | 41 | 42 | 43 | 44 | org.apache.maven.plugins 45 | maven-surefire-plugin 46 | 3.0.0-M3 47 | 48 | --enable-preview 49 | 50 | 51 | 52 | org.codehaus.mojo 53 | build-helper-maven-plugin 54 | 3.2.0 55 | 56 | 57 | generate-sources 58 | 59 | add-source 60 | 61 | 62 | 63 | src/main/examples 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.apache.maven.plugins 71 | maven-jar-plugin 72 | 3.2.2 73 | 74 | 75 | **/example/* 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/almostconstant.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | 5 | import java.lang.invoke.MethodHandle; 6 | import java.lang.invoke.MethodHandles; 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | import static java.lang.invoke.MethodType.methodType; 11 | 12 | public interface almostconstant { 13 | interface AlmostConstant { 14 | T get(); 15 | void set(T value); 16 | 17 | static AlmostConstant of(T value) { 18 | class Box { 19 | private T value; 20 | 21 | private Box(T value) { 22 | this.value = value; 23 | } 24 | } 25 | record AlmostConstantImpl(MethodHandle mh, Box box, Runnable deoptimize) implements AlmostConstant { 26 | @Override 27 | @SuppressWarnings("unchecked") 28 | public T get() { 29 | try { 30 | return (T) mh.invokeExact(); 31 | } catch (Throwable t) { 32 | throw Macro.rethrow(t); 33 | } 34 | } 35 | 36 | @Override 37 | public void set(T value) { 38 | box.value = value; 39 | deoptimize.run(); 40 | } 41 | } 42 | var box = new Box(value); 43 | var control = Macro.createMHControl(methodType(Object.class), List.of(), 44 | (__, methodType) -> MethodHandles.constant(Object.class, box.value)); 45 | return new AlmostConstantImpl<>(control.createMH(), box, control::deoptimize); 46 | } 47 | } 48 | 49 | // --- 50 | 51 | private static void assertEquals(Object exptected, Object result) { 52 | if (!(Objects.equals(exptected, result))) { 53 | throw new AssertionError("not equals, " + exptected + " != " + result); 54 | } 55 | } 56 | 57 | 58 | AlmostConstant ALMOST_CONSTANT = AlmostConstant.of(42); 59 | 60 | static void main(String[] args){ 61 | assertEquals(42, ALMOST_CONSTANT.get()); 62 | ALMOST_CONSTANT.set(505); 63 | assertEquals(505, ALMOST_CONSTANT.get()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/builder1.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | import com.github.forax.macro.Macro.Linker; 5 | import com.github.forax.macro.Macro.Parameter; 6 | import com.github.forax.macro.example.builder3.Builder; 7 | 8 | import java.lang.invoke.MethodHandle; 9 | import java.lang.invoke.MethodHandles; 10 | import java.lang.invoke.MethodHandles.Lookup; 11 | import java.lang.invoke.MethodType; 12 | import java.lang.reflect.RecordComponent; 13 | import java.util.Arrays; 14 | import java.util.HashSet; 15 | import java.util.List; 16 | import java.util.Objects; 17 | import java.util.stream.Collectors; 18 | import java.util.stream.IntStream; 19 | import java.util.stream.Stream; 20 | 21 | import static com.github.forax.macro.Macro.CONSTANT_VALUE; 22 | import static com.github.forax.macro.Macro.VALUE; 23 | import static java.lang.invoke.MethodType.methodType; 24 | 25 | public interface builder1 { 26 | interface Builder { 27 | T build(String field1, Object val1); 28 | T build(String field1, Object val1, String field2, Object val2); 29 | T build(String field1, Object val1, String field2, Object val2, String field3, Object val3); 30 | T build(String field1, Object val1, String field2, Object val2, String field3, Object val3, String field4, Object val4); 31 | 32 | private static MethodType signature(int fieldCount) { 33 | var parameterTypes = Stream.concat( 34 | IntStream.range(0, fieldCount).mapToObj(__ -> String.class), IntStream.range(0, fieldCount).mapToObj(__ -> Object.class) 35 | ).toList(); 36 | return MethodType.methodType(Object.class, parameterTypes); 37 | } 38 | 39 | private static List parameters(int fieldCount) { 40 | return Stream.concat( 41 | IntStream.range(0, fieldCount).mapToObj(__ -> CONSTANT_VALUE.polymorphic()), IntStream.range(0, fieldCount).mapToObj(__ -> VALUE) 42 | ).toList(); 43 | } 44 | 45 | static Builder of(Lookup lookup, Class recordType) { 46 | record BuilderImpl(MethodHandle mh1, MethodHandle mh2, MethodHandle mh3, MethodHandle mh4) implements Builder { 47 | @Override 48 | @SuppressWarnings("unchecked") 49 | public T build(String field1, Object val1) { 50 | try { 51 | return (T) mh1.invokeExact(field1, val1); 52 | } catch (Throwable t) { 53 | throw Macro.rethrow(t); 54 | } 55 | } 56 | 57 | @Override 58 | @SuppressWarnings("unchecked") 59 | public T build(String field1, Object val1, String field2, Object val2) { 60 | try { 61 | return (T) mh2.invokeExact(field1, field2, val1, val2); 62 | } catch (Throwable t) { 63 | throw Macro.rethrow(t); 64 | } 65 | } 66 | 67 | @Override 68 | @SuppressWarnings("unchecked") 69 | public T build(String field1, Object val1, String field2, Object val2, String field3, Object val3) { 70 | try { 71 | return (T) mh3.invokeExact(field1, field2, field3, val1, val2, val3); 72 | } catch (Throwable t) { 73 | throw Macro.rethrow(t); 74 | } 75 | } 76 | 77 | @Override 78 | @SuppressWarnings("unchecked") 79 | public T build(String field1, Object val1, String field2, Object val2, String field3, Object val3, String field4, Object val4) { 80 | try { 81 | return (T) mh4.invokeExact(field1, field2, field3, field4, val1, val2, val3, val4); 82 | } catch (Throwable t) { 83 | throw Macro.rethrow(t); 84 | } 85 | } 86 | } 87 | 88 | var components = recordType.getRecordComponents(); 89 | var componentTypeMap = Arrays.stream(components) 90 | .collect(Collectors.toMap(RecordComponent::getName, RecordComponent::getType)); 91 | MethodHandle constructor; 92 | try { 93 | constructor = lookup.findConstructor(recordType, 94 | methodType(void.class, Arrays.stream(components).map(RecordComponent::getType).toArray(Class[]::new))); 95 | } catch (NoSuchMethodException e) { 96 | throw (NoSuchMethodError) new NoSuchMethodError().initCause(e); 97 | } catch (IllegalAccessException e) { 98 | throw (IllegalAccessError) new IllegalAccessError().initCause(e); 99 | } 100 | var linker = (Linker) (constants, methodType) -> { 101 | if (!componentTypeMap.keySet().equals(new HashSet<>(constants))) { 102 | throw new IllegalStateException("wrong component names " + componentTypeMap.keySet() + " but was " + constants); 103 | } 104 | var orderMap = IntStream.range(0, constants.size()).boxed() 105 | .collect(Collectors.toMap(i -> (String) constants.get(i), i -> i)); 106 | var reorder = Arrays.stream(components) 107 | .mapToInt(component -> orderMap.get(component.getName())) 108 | .toArray(); 109 | var newMethodType = methodType(recordType, constants.stream() 110 | .map(constant -> componentTypeMap.get((String) constant)) 111 | .toArray(Class[]::new)); 112 | return MethodHandles.permuteArguments(constructor, newMethodType, reorder) 113 | .asType(methodType); 114 | }; 115 | var mh1 = Macro.createMH(signature(1), parameters(1), linker); 116 | var mh2 = Macro.createMH(signature(2), parameters(2), linker); 117 | var mh3 = Macro.createMH(signature(3), parameters(3), linker); 118 | var mh4 = Macro.createMH(signature(4), parameters(4), linker); 119 | return new BuilderImpl<>(mh1, mh2, mh3, mh4); 120 | } 121 | } 122 | 123 | // --- 124 | 125 | private static void assertEquals(Object exptected, Object result) { 126 | if (!(Objects.equals(exptected, result))) { 127 | throw new AssertionError("not equals " + exptected + " != " + result); 128 | } 129 | } 130 | 131 | 132 | record Bar(int value, String text, double weight) {} 133 | 134 | Builder BAR_BUILDER = Builder.of(MethodHandles.lookup(), Bar.class); 135 | 136 | static void main(String[] args){ 137 | var bar1 = BAR_BUILDER.build("text", "hello", "weight", 2.0, "value", 42); 138 | var bar2 = BAR_BUILDER.build("weight", 2.0, "value", 42, "text", "hello"); 139 | assertEquals(new Bar(42, "hello", 2.0), bar1); 140 | assertEquals(new Bar(42, "hello", 2.0), bar2); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/builder2.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | import com.github.forax.macro.Macro.Linker; 5 | import com.github.forax.macro.Macro.Parameter; 6 | 7 | import java.io.Serializable; 8 | import java.lang.invoke.MethodHandle; 9 | import java.lang.invoke.MethodHandles; 10 | import java.lang.invoke.MethodHandles.Lookup; 11 | import java.lang.invoke.MethodType; 12 | import java.lang.reflect.RecordComponent; 13 | import java.util.Arrays; 14 | import java.util.HashSet; 15 | import java.util.List; 16 | import java.util.Objects; 17 | import java.util.stream.Collectors; 18 | import java.util.stream.IntStream; 19 | import java.util.stream.Stream; 20 | 21 | import static com.github.forax.macro.Macro.CONSTANT_VALUE; 22 | import static com.github.forax.macro.Macro.VALUE; 23 | import static java.lang.invoke.MethodType.methodType; 24 | 25 | public interface builder2 { 26 | interface Builder { 27 | @FunctionalInterface 28 | interface Accessor extends Serializable { 29 | V apply(T record); 30 | } 31 | 32 | T build(Accessor field1, V1 val1); 33 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2); 34 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3); 35 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3, Accessor field4, V4 val4); 36 | 37 | private static MethodType signature(int fieldCount) { 38 | var parameterTypes = Stream.concat( 39 | IntStream.range(0, fieldCount).mapToObj(__ -> Accessor.class), IntStream.range(0, fieldCount).mapToObj(__ -> Object.class) 40 | ).toList(); 41 | return MethodType.methodType(Object.class, parameterTypes); 42 | } 43 | 44 | private static List parameters(int fieldCount) { 45 | return Stream.concat( 46 | IntStream.range(0, fieldCount).mapToObj(__ -> CONSTANT_VALUE.polymorphic()), IntStream.range(0, fieldCount).mapToObj(__ -> VALUE) 47 | ).toList(); 48 | } 49 | 50 | static Builder of(Lookup lookup, Class recordType) { 51 | record BuilderImpl(MethodHandle mh1, MethodHandle mh2, MethodHandle mh3, MethodHandle mh4) implements Builder { 52 | @Override 53 | @SuppressWarnings("unchecked") 54 | public T build(Accessor field1, V1 val1) { 55 | try { 56 | return (T) mh1.invokeExact(field1, val1); 57 | } catch (Throwable t) { 58 | throw Macro.rethrow(t); 59 | } 60 | } 61 | 62 | @Override 63 | @SuppressWarnings("unchecked") 64 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2) { 65 | try { 66 | return (T) mh2.invokeExact(field1, field2, val1, val2); 67 | } catch (Throwable t) { 68 | throw Macro.rethrow(t); 69 | } 70 | } 71 | 72 | @Override 73 | @SuppressWarnings("unchecked") 74 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3) { 75 | try { 76 | return (T) mh3.invokeExact(field1, field2, field3, val1, val2, val3); 77 | } catch (Throwable t) { 78 | throw Macro.rethrow(t); 79 | } 80 | } 81 | 82 | @Override 83 | @SuppressWarnings("unchecked") 84 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3, Accessor field4, V4 val4) { 85 | try { 86 | return (T) mh4.invokeExact(field1, field2, field3, field4, val1, val2, val3, val4); 87 | } catch (Throwable t) { 88 | throw Macro.rethrow(t); 89 | } 90 | } 91 | } 92 | 93 | var components = recordType.getRecordComponents(); 94 | var componentTypeMap = Arrays.stream(components) 95 | .collect(Collectors.toMap(RecordComponent::getName, RecordComponent::getType)); 96 | MethodHandle constructor; 97 | try { 98 | constructor = lookup.findConstructor(recordType, 99 | methodType(void.class, Arrays.stream(components).map(RecordComponent::getType).toArray(Class[]::new))); 100 | } catch (NoSuchMethodException e) { 101 | throw (NoSuchMethodError) new NoSuchMethodError().initCause(e); 102 | } catch (IllegalAccessException e) { 103 | throw (IllegalAccessError) new IllegalAccessError().initCause(e); 104 | } 105 | 106 | var linker = (Linker) (constants, methodType) -> { 107 | var methodNames = constants.stream() 108 | .map(lambda -> Macro.crack(lookup, lambda).getImplMethodName()) 109 | .toList(); 110 | if (!componentTypeMap.keySet().equals(new HashSet<>(methodNames))) { 111 | throw new IllegalStateException("wrong component names " + componentTypeMap.keySet() + " but was " + methodNames); 112 | } 113 | var orderMap = IntStream.range(0, methodNames.size()).boxed() 114 | .collect(Collectors.toMap(methodNames::get, i -> i)); 115 | var reorder = Arrays.stream(components) 116 | .mapToInt(component -> orderMap.get(component.getName())) 117 | .toArray(); 118 | var newMethodType = methodType(recordType, methodNames.stream() 119 | .map(componentTypeMap::get) 120 | .toArray(Class[]::new)); 121 | return MethodHandles.permuteArguments(constructor, newMethodType, reorder) 122 | .asType(methodType); 123 | }; 124 | var mh1 = Macro.createMH(signature(1), parameters(1), linker); 125 | var mh2 = Macro.createMH(signature(2), parameters(2), linker); 126 | var mh3 = Macro.createMH(signature(3), parameters(3), linker); 127 | var mh4 = Macro.createMH(signature(4), parameters(4), linker); 128 | return new BuilderImpl<>(mh1, mh2, mh3, mh4); 129 | } 130 | } 131 | 132 | // --- 133 | 134 | private static void assertEquals(Object exptected, Object result) { 135 | if (!(Objects.equals(exptected, result))) { 136 | throw new AssertionError("not equals " + exptected + " != " + result); 137 | } 138 | } 139 | 140 | 141 | record Bar(int value, String text, double weight) {} 142 | 143 | Builder BAR_BUILDER = Builder.of(MethodHandles.lookup(), Bar.class); 144 | 145 | static void main(String[] args){ 146 | var bar1 = BAR_BUILDER.build(Bar::text, "hello", Bar::weight, 2.0, Bar::value, 42); 147 | var bar2 = BAR_BUILDER.build(Bar::weight, 2.0, Bar::value, 42, Bar::text, "hello"); 148 | assertEquals(new Bar(42, "hello", 2.0), bar1); 149 | assertEquals(new Bar(42, "hello", 2.0), bar2); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/builder3.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | import com.github.forax.macro.Macro.Linker; 5 | import com.github.forax.macro.Macro.Parameter; 6 | 7 | import java.io.Serializable; 8 | import java.lang.invoke.MethodHandle; 9 | import java.lang.invoke.MethodHandles; 10 | import java.lang.invoke.MethodHandles.Lookup; 11 | import java.lang.invoke.MethodType; 12 | import java.lang.reflect.RecordComponent; 13 | import java.util.Arrays; 14 | import java.util.Collections; 15 | import java.util.HashSet; 16 | import java.util.List; 17 | import java.util.Objects; 18 | import java.util.stream.Collectors; 19 | import java.util.stream.IntStream; 20 | import java.util.stream.Stream; 21 | 22 | import static com.github.forax.macro.Macro.CONSTANT_VALUE; 23 | import static com.github.forax.macro.Macro.VALUE; 24 | import static java.lang.invoke.MethodType.methodType; 25 | 26 | public interface builder3 { 27 | interface Builder { 28 | @FunctionalInterface 29 | interface Accessor extends Serializable { 30 | V apply(T record); 31 | } 32 | 33 | T build(Accessor field1, V1 val1); 34 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2); 35 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3); 36 | T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3, Accessor field4, V4 val4); 37 | 38 | private static MethodType signature(int fieldCount) { 39 | var parameterTypes = Stream.concat( 40 | IntStream.range(0, fieldCount).mapToObj(__ -> Accessor.class), IntStream.range(0, fieldCount).mapToObj(__ -> Object.class) 41 | ).toList(); 42 | return MethodType.methodType(Object.class, parameterTypes); 43 | } 44 | 45 | private static List parameters(int fieldCount) { 46 | return Stream.concat( 47 | IntStream.range(0, fieldCount).mapToObj(__ -> CONSTANT_VALUE.polymorphic()), IntStream.range(0, fieldCount).mapToObj(__ -> VALUE) 48 | ).toList(); 49 | } 50 | 51 | static Builder of(Lookup lookup, Class recordType) { 52 | record BuilderImpl(MethodHandle mh) implements Builder { 53 | private static final Accessor NO_ACCESSOR = null; 54 | private static final Object NO_VALUE = null; 55 | 56 | @Override 57 | @SuppressWarnings("unchecked") 58 | public T build(Accessor field1, V1 val1) { 59 | try { 60 | return (T) mh.invokeExact(1, field1, val1, NO_ACCESSOR, NO_VALUE, NO_ACCESSOR, NO_VALUE, NO_ACCESSOR, NO_VALUE); 61 | } catch (Throwable t) { 62 | throw Macro.rethrow(t); 63 | } 64 | } 65 | 66 | @Override 67 | @SuppressWarnings("unchecked") 68 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2) { 69 | try { 70 | return (T) mh.invokeExact(2, field1, val1, field2, val2, NO_ACCESSOR, NO_VALUE, NO_ACCESSOR, NO_VALUE); 71 | } catch (Throwable t) { 72 | throw Macro.rethrow(t); 73 | } 74 | } 75 | 76 | @Override 77 | @SuppressWarnings("unchecked") 78 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3) { 79 | try { 80 | return (T) mh.invokeExact(3, field1, val1, field2, val2, field3, val3, NO_ACCESSOR, NO_VALUE); 81 | } catch (Throwable t) { 82 | throw Macro.rethrow(t); 83 | } 84 | } 85 | 86 | @Override 87 | @SuppressWarnings("unchecked") 88 | public T build(Accessor field1, V1 val1, Accessor field2, V2 val2, Accessor field3, V3 val3, Accessor field4, V4 val4) { 89 | try { 90 | return (T) mh.invokeExact(4, field1, val1, field2, val2, field3, val3, field4, val4); 91 | } catch (Throwable t) { 92 | throw Macro.rethrow(t); 93 | } 94 | } 95 | } 96 | 97 | var components = recordType.getRecordComponents(); 98 | var componentTypeMap = Arrays.stream(components) 99 | .collect(Collectors.toMap(RecordComponent::getName, RecordComponent::getType)); 100 | MethodHandle constructor; 101 | try { 102 | constructor = lookup.findConstructor(recordType, 103 | methodType(void.class, Arrays.stream(components).map(RecordComponent::getType).toArray(Class[]::new))); 104 | } catch (NoSuchMethodException e) { 105 | throw (NoSuchMethodError) new NoSuchMethodError().initCause(e); 106 | } catch (IllegalAccessException e) { 107 | throw (IllegalAccessError) new IllegalAccessError().initCause(e); 108 | } 109 | 110 | var mhType = methodType(Object.class, int.class, Accessor.class, Object.class, Accessor.class, Object.class, Accessor.class, Object.class, Accessor.class, Object.class); 111 | var parameters = List.of(CONSTANT_VALUE, CONSTANT_VALUE.polymorphic(), VALUE, CONSTANT_VALUE.polymorphic(), VALUE, CONSTANT_VALUE.polymorphic(), VALUE, CONSTANT_VALUE.polymorphic(), VALUE); 112 | var linker = (Linker) (constants, methodType) -> { 113 | var accessorCount = (int) constants.get(0); 114 | var methodNames = constants.stream() 115 | .skip(1) 116 | .limit(accessorCount) 117 | .map(lambda -> Macro.crack(lookup, lambda).getImplMethodName()) 118 | .toList(); 119 | if (!componentTypeMap.keySet().equals(new HashSet<>(methodNames))) { 120 | throw new IllegalStateException("wrong component names " + componentTypeMap.keySet() + " but was " + methodNames); 121 | } 122 | var orderMap = IntStream.range(0, methodNames.size()).boxed() 123 | .collect(Collectors.toMap(methodNames::get, i -> i)); 124 | var reorder = Arrays.stream(components) 125 | .mapToInt(component -> orderMap.get(component.getName())) 126 | .toArray(); 127 | var newMethodType = methodType(recordType, methodNames.stream() 128 | .map(componentTypeMap::get) 129 | .toArray(Class[]::new)); 130 | var target = MethodHandles.permuteArguments(constructor, newMethodType, reorder); 131 | // drop NO_VALUE values 132 | if (accessorCount != 4) { 133 | target = MethodHandles.dropArguments(target, accessorCount, Collections.nCopies(4 - accessorCount, Object.class)); 134 | } 135 | return target.asType(methodType); 136 | }; 137 | var mh = Macro.createMH(mhType, parameters, linker); 138 | return new BuilderImpl<>(mh); 139 | } 140 | } 141 | 142 | // --- 143 | 144 | private static void assertEquals(Object exptected, Object result) { 145 | if (!(Objects.equals(exptected, result))) { 146 | throw new AssertionError("not equals " + exptected + " != " + result); 147 | } 148 | } 149 | 150 | 151 | record Bar(int value, String text, double weight) {} 152 | 153 | Builder BAR_BUILDER = Builder.of(MethodHandles.lookup(), Bar.class); 154 | 155 | static void main(String[] args){ 156 | var bar1 = BAR_BUILDER.build(Bar::text, "hello", Bar::weight, 2.0, Bar::value, 42); 157 | var bar2 = BAR_BUILDER.build(Bar::weight, 2.0, Bar::value, 42, Bar::text, "hello"); 158 | assertEquals(new Bar(42, "hello", 2.0), bar1); 159 | assertEquals(new Bar(42, "hello", 2.0), bar2); 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/fmt.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | 5 | import java.lang.invoke.MethodHandle; 6 | import java.lang.invoke.MethodHandles; 7 | import java.lang.invoke.MethodType; 8 | import java.lang.invoke.StringConcatException; 9 | import java.lang.invoke.StringConcatFactory; 10 | import java.util.Collections; 11 | import java.util.List; 12 | import java.util.Objects; 13 | import java.util.regex.Pattern; 14 | 15 | public interface fmt { 16 | interface Formatter { 17 | String format(String text, Object... args); 18 | 19 | static Formatter of() { 20 | record FMTImpl(MethodHandle mh) implements Formatter { 21 | public String format(String text, Object... args) { 22 | try { 23 | return (String) mh.invokeExact(text, args); 24 | } catch (Throwable t) { 25 | throw Macro.rethrow(t); 26 | } 27 | } 28 | } 29 | var mh = Macro.createMH(MethodType.methodType(String.class, String.class, Object[].class), 30 | List.of(Macro.CONSTANT_VALUE.polymorphic(), Macro.VALUE), 31 | (constants, methodType) -> { 32 | var text = (String) constants.get(0); 33 | var pattern = Pattern.compile("(%.)"); 34 | var matcher = pattern.matcher(text); 35 | var box = new Object() { int counter; boolean unknown; }; 36 | var recipe = matcher.replaceAll(matchResult -> { 37 | switch (matchResult.group(1)) { 38 | case "%s", "%d" -> box.counter++; 39 | default -> box.unknown = true; 40 | } 41 | return "\u0001"; 42 | }); 43 | var lookup = MethodHandles.lookup(); 44 | if (box.unknown) { 45 | var target = lookup.findStatic(String.class, "format", MethodType.methodType(String.class, String.class, Object[].class)); 46 | return target.bindTo(text); 47 | } 48 | var count = box.counter; 49 | var concatType = MethodType.methodType(String.class, Collections.nCopies(count, Object.class)); 50 | MethodHandle target = null; 51 | try { 52 | target = StringConcatFactory.makeConcatWithConstants(lookup, "concat", concatType, recipe).dynamicInvoker(); 53 | } catch (StringConcatException e) { 54 | throw new AssertionError(e); 55 | } 56 | target = target.asSpreader(Object[].class, count); 57 | return target.asType(methodType); 58 | }); 59 | return new FMTImpl(mh); 60 | } 61 | } 62 | 63 | // --- 64 | 65 | 66 | private static void assertEquals(Object exptected, Object result) { 67 | if (!(Objects.equals(exptected, result))) { 68 | throw new AssertionError("not equals, " + exptected + " != " + result); 69 | } 70 | } 71 | 72 | Formatter FMT = Formatter.of(); 73 | 74 | static void main(String[] args){ 75 | assertEquals("hello FMT 42", FMT.format("hello %s %d", "FMT", 42)); 76 | assertEquals("42.00", FMT.format("%.2f", 42.0)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/examples/com/github.forax/macro/example/multimethods.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro.example; 2 | 3 | import com.github.forax.macro.Macro; 4 | import com.github.forax.macro.Macro.ConstantParameter; 5 | import com.github.forax.macro.Macro.ConstantPolicy; 6 | 7 | import java.lang.invoke.MethodHandle; 8 | import java.lang.invoke.MethodHandles; 9 | import java.lang.invoke.MethodHandles.Lookup; 10 | import java.lang.invoke.MethodType; 11 | import java.util.Arrays; 12 | import java.util.Collections; 13 | import java.util.List; 14 | import java.util.Objects; 15 | import java.util.stream.Stream; 16 | 17 | import static com.github.forax.macro.Macro.CONSTANT_VALUE; 18 | 19 | public interface multimethods { 20 | interface Multimethod { 21 | T call(String name, Object o1); 22 | T call(String name, Object o1, Object o2); 23 | T call(String name, Object o1, Object o2, Object o3); 24 | T call(String name, Object o1, Object o2, Object o3, Object o4); 25 | T call(String name, Object o1, Object o2, Object o3, Object o4, Object o5); 26 | 27 | static Multimethod of(Lookup lookup) { 28 | record MultimethodImpl(MethodHandle mh) implements Multimethod { 29 | private static final Object NONE = new Object(); 30 | 31 | @Override 32 | public T call(String name, Object o1) { 33 | return dispatch(1, name, o1, NONE, NONE, NONE, NONE); 34 | } 35 | 36 | @Override 37 | public T call(String name, Object o1, Object o2) { 38 | return dispatch(2, name, o1, o2, NONE, NONE, NONE); 39 | } 40 | 41 | @Override 42 | public T call(String name, Object o1, Object o2, Object o3) { 43 | return dispatch(3, name, o1, o2, o3, NONE, NONE); 44 | } 45 | 46 | @Override 47 | public T call(String name, Object o1, Object o2, Object o3, Object o4) { 48 | return dispatch(4, name, o1, o2, o3, o4, NONE); 49 | } 50 | 51 | @Override 52 | public T call(String name, Object o1, Object o2, Object o3, Object o4, Object o5) { 53 | return dispatch(5, name, o1, o2, o3, o4, o5); 54 | } 55 | 56 | @SuppressWarnings("unchecked") 57 | private T dispatch(int arity, String name, Object o1, Object o2, Object o3, Object o4, Object o5) { 58 | try { 59 | return (T) mh.invokeExact(arity, name, o1, o2, o3, o4, o5); 60 | } catch (Throwable t) { 61 | throw Macro.rethrow(t); 62 | } 63 | } 64 | } 65 | var dyn = new ConstantParameter((__, value) -> value.getClass(), false, ConstantPolicy.POLYMORPHIC); 66 | var mh = Macro.createMH(MethodType.methodType(Object.class, int.class, String.class, Object.class, Object.class, Object.class, Object.class, Object.class), 67 | List.of(CONSTANT_VALUE, CONSTANT_VALUE, dyn, dyn, dyn, dyn, dyn), 68 | (constants, methodType) -> { 69 | var arity = (int) constants.get(0); 70 | var name = (String) constants.get(1); 71 | var type1 = (Class) constants.get(2); 72 | var type2 = (Class) constants.get(3); 73 | var type3 = (Class) constants.get(4); 74 | var type4 = (Class) constants.get(5); 75 | var type5 = (Class) constants.get(6); 76 | var parameterTypes = switch (arity) { 77 | case 1 -> List.>of(); 78 | case 2 -> List.>of(type2); 79 | case 3 -> List.of(type2, type3); 80 | case 4 -> List.of(type2, type3, type4); 81 | case 5 -> List.of(type2, type3, type4, type5); 82 | default -> throw new AssertionError(); 83 | }; 84 | var mhs = applicableMethods(lookup, type1, name, parameterTypes); 85 | if (mhs.isEmpty()) { 86 | throw new IllegalStateException("no methods matching !"); 87 | } 88 | var target = mostSpecific(mhs); 89 | if (target == null) { 90 | throw new IllegalStateException("no method is more specific than the others ! " + mhs); 91 | } 92 | if (arity != 5) { 93 | target = MethodHandles.dropArguments(target, target.type().parameterCount(), Collections.nCopies(5 - arity, Object.class)); 94 | } 95 | return target.asType(methodType); 96 | }); 97 | return new MultimethodImpl(mh); 98 | } 99 | 100 | private static Class box(Class type) { 101 | if (!type.isPrimitive()) { 102 | return type; 103 | } 104 | return switch (type.getName()) { 105 | case "boolean" -> Boolean.class; 106 | case "byte" -> Byte.class; 107 | case "char" -> Character.class; 108 | case "short" -> Short.class; 109 | case "int" -> Integer.class; 110 | case "long" -> Long.class; 111 | case "float" -> Float.class; 112 | case "double" -> Double.class; 113 | default -> throw new AssertionError(); 114 | }; 115 | } 116 | 117 | private static MethodType box(MethodType methodType) { 118 | for(var i =0; i < methodType.parameterCount(); i++) { 119 | var parameterType = methodType.parameterType(i); 120 | methodType = methodType.changeParameterType(i, box(parameterType)); 121 | } 122 | return methodType; 123 | } 124 | 125 | private static List applicableMethods(Lookup lookup, Class declaringClass, String name, List> parameterTypes) { 126 | return Arrays.stream(declaringClass.getDeclaredMethods()) // we do not support inheritance 127 | .filter(m -> !m.isBridge() && 128 | m.getName().equals(name) && 129 | ((m.isVarArgs() && m.getParameterCount() <= parameterTypes.size()) || m.getParameterCount() == parameterTypes.size())) 130 | .flatMap(m -> { 131 | MethodHandle mh; 132 | try { 133 | mh = lookup.unreflect(m); 134 | } catch (IllegalAccessException e) { 135 | return null; 136 | } 137 | 138 | // convert varargs 139 | if (m.isVarArgs()) { 140 | var lastParameter = mh.type().parameterType(mh.type().parameterCount() - 1); 141 | mh = mh.asSpreader(lastParameter, 1 + parameterTypes.size() - mh.type().parameterCount()); 142 | } 143 | 144 | // box if necessary (we don't support primitive types) 145 | mh = mh.asType(box(mh.type())); 146 | 147 | // applicable test 148 | if (!moreSpecific(MethodType.methodType(Object.class, parameterTypes), mh.type().dropParameterTypes(0, 1))) { 149 | return null; 150 | } 151 | 152 | return Stream.of(mh); 153 | }) 154 | .toList(); 155 | } 156 | 157 | private static boolean moreSpecific(Class parameter1, Class parameter2) { 158 | return parameter2.isAssignableFrom(parameter1); 159 | } 160 | 161 | private static boolean moreSpecific(MethodType type1, MethodType type2) { 162 | for(var i = 0; i < type1.parameterCount(); i++) { 163 | var parameter1 = type1.parameterType(i); 164 | var parameter2 = type2.parameterType(i); 165 | if (type1 == type2) { 166 | continue; 167 | } 168 | if (!moreSpecific(parameter1, parameter2)) { 169 | return false; 170 | } 171 | } 172 | return true; 173 | } 174 | 175 | private static MethodHandle mostSpecific(List mhs) { 176 | loop: for(var mh1: mhs) { 177 | for(var mh2: mhs) { 178 | if (mh1 == mh2) { 179 | continue; 180 | } 181 | if (!moreSpecific(mh1.type(), mh2.type())) { 182 | continue loop; 183 | } 184 | } 185 | return mh1; 186 | } 187 | return null; 188 | } 189 | } 190 | 191 | 192 | // --- 193 | 194 | private static void assertEquals(Object exptected, Object result) { 195 | if (!(Objects.equals(exptected, result))) { 196 | throw new AssertionError("not equals, " + exptected + " != " + result); 197 | } 198 | } 199 | 200 | sealed interface Shape {} 201 | record Rectangle() implements Shape {} 202 | record Circle() implements Shape {} 203 | 204 | class Test { 205 | public int m1(Shape shape) { throw new AssertionError(); } 206 | public int m1(Rectangle rectangle) { return 1; } 207 | public int m1(Circle circle) { return 2; } 208 | 209 | public int m2(Rectangle r1, Rectangle r2) { return 10; } 210 | public int m2(Rectangle r1, Circle c2) { return 20; } 211 | public int m2(Circle c1, Rectangle r2) { return 30; } 212 | public int m2(Circle c1, Circle c2) { return 40; } 213 | } 214 | 215 | Multimethod MULTI_METHOD = Multimethod.of(MethodHandles.lookup()); 216 | 217 | static void main(String[] args){ 218 | var rectangle = new Rectangle(); 219 | var circle = new Circle(); 220 | 221 | assertEquals(1, MULTI_METHOD.call("m1", new Test(), rectangle)); 222 | assertEquals(2, MULTI_METHOD.call("m1", new Test(), circle)); 223 | 224 | assertEquals(10, MULTI_METHOD.call("m2", new Test(), rectangle, rectangle)); 225 | assertEquals(20, MULTI_METHOD.call("m2", new Test(), rectangle, circle)); 226 | assertEquals(30, MULTI_METHOD.call("m2", new Test(), circle, rectangle)); 227 | assertEquals(40, MULTI_METHOD.call("m2", new Test(), circle, circle)); 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /src/main/java/com/github/forax/macro/Macro.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro; 2 | 3 | import java.io.Serializable; 4 | import java.lang.invoke.MethodHandle; 5 | import java.lang.invoke.MethodHandles; 6 | import java.lang.invoke.MethodHandles.Lookup; 7 | import java.lang.invoke.MethodType; 8 | import java.lang.invoke.MutableCallSite; 9 | import java.lang.invoke.SerializedLambda; 10 | import java.lang.invoke.WrongMethodTypeException; 11 | import java.util.ArrayList; 12 | import java.util.Collections; 13 | import java.util.List; 14 | 15 | import static java.lang.invoke.MethodHandles.dropArguments; 16 | import static java.lang.invoke.MethodHandles.insertArguments; 17 | import static java.lang.invoke.MethodType.methodType; 18 | import static java.util.Objects.requireNonNull; 19 | 20 | /** 21 | * A way to defines macro at runtime in Java. 22 | * 23 | * A macro is a method that pre-compute a list of constants from some the arguments and ask a linker 24 | * to provide a method handle from the list of constants to be called with the resting arguments. 25 | * 26 | *
 27 |  * mh(arg1, arg2, arg3) + macro(param1, param2, param3) -> linker(const1, const2)(arg2, arg3)
 28 |  * 
29 | * 30 | * The {@link Parameter macro parameters} describes how to extract a constant from an argument, 31 | * how to react if subsequent calls found new constants and if the argument are used or dropped 32 | * by the method handle retuend by the linker. 33 | * 34 | * @see #createMH(MethodType, List, Linker) 35 | */ 36 | public class Macro { 37 | /** 38 | * Describe the parameters of a function call of a macro. 39 | * Instead of a classical function call where all arguments are sent to the function, a macro separate the arguments 40 | * in two categories, the constants and the values, the constants are extracted and a linker is called 41 | * to provide a method handle that will be called with the values. 42 | * 43 | * The fact that the constant are computed earlier than the arguments allows data structures and 44 | * method linkage to be computed resulting in a code more efficient than using reflection. 45 | * 46 | * {@link Macro#createMH(MethodType, List, Linker)} create a macro, as a method handle, 47 | * from a method type, a list of parameters and a {@link Linker}. 48 | * 49 | * There are 3 kinds of parameters 50 | *
    51 | *
  • {@link ConstantParameter a constant parameter}, a parameter from which a 52 | * {@link ConstantParameter#function() constant can be extracted}, 53 | * the argument itself will be @link {@link ConstantParameter#dropValue() kept or not} and 54 | * {@link ConstantParameter#policy() one or more constants} can be extracted from a parameter. 55 | *
  • {@link ValueParameter a value parameter}, a simple argument. 56 | *
  • {@link IgnoreParameter an ignore parameter}, the corresponding argument is ignored. 57 | *
58 | * 59 | * The {@link Linker} defines the function called with the constants to provide the method handle 60 | * that will be called with the argument. 61 | * 62 | * @see Macro 63 | */ 64 | public sealed interface Parameter {} 65 | 66 | /** 67 | * A parameter indicating that the corresponding argument is a constant. 68 | */ 69 | public record ConstantParameter(ProjectionFunction function, boolean dropValue, ConstantPolicy policy) implements Parameter { 70 | /** 71 | * Creates a constant parameter with a projection function to compute the constant from a value, 72 | * a boolean indicating if the value should be dropped ot not and 73 | * an enum indicating the operation to do if there are different values for the constant 74 | * ({@link ConstantPolicy#ERROR}: emits an error, {@link ConstantPolicy#RELINK}: calls the linker again, 75 | * {@link ConstantPolicy#POLYMORPHIC}:install a polymorphic inlining cache). 76 | * 77 | * @param function the projection function, can be a lambda, {@link ProjectionFunction#VALUE} or 78 | * {@link ProjectionFunction#GET_CLASS} 79 | * @param dropValue a boolean indicating if the value should be dropped given it appears as a constant 80 | * @param policy policy when there are several constants for a parameter 81 | */ 82 | public ConstantParameter { 83 | requireNonNull(function); 84 | requireNonNull(policy); 85 | } 86 | 87 | /** 88 | * Returns a new constant parameter using the {@link ConstantPolicy#ERROR} 89 | * @return a new constant parameter using the {@link ConstantPolicy#ERROR} 90 | */ 91 | public ConstantParameter error() { 92 | return new ConstantParameter(function, dropValue, ConstantPolicy.ERROR); 93 | } 94 | 95 | /** 96 | * Returns a new constant parameter using the {@link ConstantPolicy#RELINK} 97 | * @return a new constant parameter using the {@link ConstantPolicy#RELINK} 98 | */ 99 | public ConstantParameter relink() { 100 | return new ConstantParameter(function, dropValue, ConstantPolicy.RELINK); 101 | } 102 | 103 | /** 104 | * Returns a new constant parameter using the {@link ConstantPolicy#POLYMORPHIC} 105 | * @return a new constant parameter using the {@link ConstantPolicy#POLYMORPHIC} 106 | */ 107 | public ConstantParameter polymorphic() { 108 | return new ConstantParameter(function, dropValue, ConstantPolicy.POLYMORPHIC); 109 | } 110 | 111 | /** 112 | * Returns a new constant parameter that drop/retain the value of the constant 113 | * If the value is dropped it will not be an argument of the method handle returned 114 | * by the {@link Linker} 115 | * 116 | * @param dropValue drop or retain the value of a constant 117 | * @return a new constant parameter that drop/retain the value of the constant 118 | */ 119 | public ConstantParameter dropValue(boolean dropValue) { 120 | return new ConstantParameter(function, dropValue, policy); 121 | } 122 | } 123 | 124 | /** 125 | * The projection function used to extract the constant from a value. 126 | */ 127 | @FunctionalInterface 128 | public interface ProjectionFunction { 129 | /** 130 | * Returns a constant from the value and its declared type. 131 | * 132 | * @param declaredType the declared type of the argument 133 | * @param value the value of the argument 134 | * @return a constant 135 | */ 136 | Object computeConstant(Class declaredType, Object value); 137 | 138 | /** 139 | * A projection function that returns the value as constant. 140 | */ 141 | ProjectionFunction VALUE = (declaredType, value) -> value; 142 | 143 | /** 144 | * A projection function that return the class of the value as a constant. 145 | */ 146 | ProjectionFunction GET_CLASS = (declaredType, value) -> declaredType.isPrimitive()? declaredType: value.getClass(); 147 | } 148 | 149 | /** 150 | * The behavior when the macro system detects that a constant has several different values. 151 | */ 152 | public enum ConstantPolicy { 153 | /** 154 | * Emits an exception 155 | */ 156 | ERROR, 157 | 158 | /** 159 | * Calls the linker again, trashing all previous computation 160 | */ 161 | RELINK, 162 | 163 | /** 164 | * Use a polymorphic inlining cache to remember all the linkages of the constants 165 | */ 166 | POLYMORPHIC 167 | } 168 | 169 | /** 170 | * A parameter indicating that the corresponding argument should be ignored. 171 | */ 172 | public enum IgnoreParameter implements Parameter { 173 | /** 174 | * The singleton instance. 175 | * 176 | * @see #IGNORE 177 | */ 178 | INSTANCE 179 | } 180 | 181 | /** 182 | * A parameter indicating that the corresponding argument is just a value (not a constant). 183 | */ 184 | public enum ValueParameter implements Parameter { 185 | /** 186 | * The singleton instance. 187 | * 188 | * @see #VALUE 189 | */ 190 | INSTANCE 191 | } 192 | 193 | /** 194 | * A constant parameter that defines the value of the argument as a constant, 195 | * drop the value and throws an exception if the parameter see several values 196 | */ 197 | public static final ConstantParameter CONSTANT_VALUE = new ConstantParameter(ProjectionFunction.VALUE, true, ConstantPolicy.ERROR); 198 | 199 | /** 200 | * A constant parameter that defines the class of the argument as a constant, 201 | * the value is not dropped and throws an exception if the parameter see several classes 202 | */ 203 | public static final ConstantParameter CONSTANT_CLASS = new ConstantParameter(ProjectionFunction.GET_CLASS, false, ConstantPolicy.ERROR); 204 | 205 | /** 206 | * A value parameter 207 | */ 208 | public static final ValueParameter VALUE = ValueParameter.INSTANCE; 209 | 210 | /** 211 | * An ignored parameter 212 | */ 213 | public static final IgnoreParameter IGNORE = IgnoreParameter.INSTANCE; 214 | 215 | /** 216 | * Called by the macro system with the constants and the method handle type 217 | * to get a method handle implementing the behavior. 218 | */ 219 | public interface Linker { 220 | /** 221 | * This method is called by the macro system to find the method handle 222 | * to execute with the arguments. 223 | * 224 | * @param constants the constants gather from the arguments. 225 | * @param methodType the method type that must be the type of the returned method handle 226 | * @return a method handle 227 | * 228 | * @throws ClassNotFoundException if a class is not found 229 | * @throws IllegalAccessException if access is not possible 230 | * @throws InstantiationException if instantiation is not possible 231 | * @throws NoSuchFieldException if no field is found 232 | * @throws NoSuchMethodException if no method is found 233 | */ 234 | MethodHandle apply(List constants, MethodType methodType) 235 | throws ClassNotFoundException, IllegalAccessException, InstantiationException, 236 | NoSuchFieldException, NoSuchMethodException; 237 | } 238 | 239 | /** 240 | * Creates a method handle conforming to the method type taken as parameter which 241 | * separate the constant arguments from the other arguments and call the linker 242 | * one or more time with the constant arguments. 243 | * 244 | * @param methodType a method type 245 | * @param parameters the macro parameters 246 | * @param linker the linker that will be called with the constant to get the corresponding method handles 247 | * @return a method handle 248 | */ 249 | public static MethodHandle createMH(MethodType methodType, 250 | List parameters, 251 | Linker linker) { 252 | return createMHControl(methodType, parameters, linker).createMH(); 253 | } 254 | 255 | /** 256 | * An interface that can create a method handle from the parameters of 257 | * {@link #createMHControl(MethodType, List, Linker)} and reset all created method handles to their initial state. 258 | */ 259 | public interface MethodHandleControl { 260 | /** 261 | * Creates a method handle from the parameter of {@link #createMHControl(MethodType, List, Linker)}. 262 | * @return a new method handle 263 | */ 264 | MethodHandle createMH(); 265 | 266 | /** 267 | * De-optimize all method handles created with {@link #createMH()}. 268 | */ 269 | void deoptimize(); 270 | } 271 | 272 | /** 273 | * Return a method handle control which provides 274 | *
    275 | *
  1. a method {@link MethodHandleControl#createMH()} that create a method handle from a recipe. 276 | *
  2. a method {@link MethodHandleControl#deoptimize()} that can reset the method handle to its initial state 277 | *
278 | * 279 | * @param methodType a method type 280 | * @param parameters the macro parameters 281 | * @param linker the linker that will be called with the constant to get the corresponding method handles 282 | * @return a method handle 283 | */ 284 | public static MethodHandleControl createMHControl(MethodType methodType, 285 | List parameters, 286 | Linker linker) { 287 | requireNonNull(methodType, "linkageType is null"); 288 | requireNonNull(parameters, "parameters is null"); 289 | requireNonNull(linker, "linker is null"); 290 | if (methodType.parameterCount() != parameters.size()) { 291 | throw new IllegalArgumentException("methodType.parameterCount() != parameters.size()"); 292 | } 293 | return new RootCallSite(methodType, List.copyOf(parameters), linker); 294 | } 295 | 296 | private sealed interface Argument { } 297 | 298 | private enum ValueArgument implements Argument { INSTANCE } 299 | private record IgnoredArgument(Class type, int position) implements Argument { } 300 | private record GuardedArgument(Class type, int position, boolean dropValue, ProjectionFunction function, Object constant, ConstantPolicy policy) implements Argument { } 301 | 302 | private record AnalysisResult(List arguments, List constants, List values, MethodType linkageType) { 303 | private AnalysisResult { 304 | arguments = Collections.unmodifiableList(arguments); 305 | constants = Collections.unmodifiableList(constants); 306 | values = Collections.unmodifiableList(values); 307 | } 308 | } 309 | 310 | private static AnalysisResult argumentAnalysis(Object[] args, List parameters, MethodType methodType) { 311 | var arguments = new ArrayList(); 312 | var constants = new ArrayList<>(); 313 | var values = new ArrayList<>(); 314 | var valueTypes = new ArrayList>(); 315 | for(var i = 0; i < args.length; i++) { 316 | var parameter = parameters.get(i); 317 | var arg = args[i]; 318 | var type = methodType.parameterType(i); 319 | var argument = switch (parameter) { 320 | case IgnoreParameter __ -> new IgnoredArgument(type, i); 321 | case ValueParameter __ -> { 322 | values.add(arg); 323 | valueTypes.add(type); 324 | yield ValueArgument.INSTANCE; 325 | } 326 | case ConstantParameter constantParameter -> { 327 | var constant = constantParameter.function().computeConstant(type, arg); 328 | constants.add(constant); 329 | if (!constantParameter.dropValue()) { 330 | values.add(arg); 331 | valueTypes.add(type); 332 | } 333 | yield new GuardedArgument(type, i, constantParameter.dropValue(), 334 | constantParameter.function(), constant, 335 | constantParameter.policy()); 336 | } 337 | }; 338 | arguments.add(argument); 339 | } 340 | return new AnalysisResult(arguments, constants, values, methodType(methodType.returnType(), valueTypes)); 341 | } 342 | 343 | private static MethodHandle link(Linker linker, List constants, MethodType linkageType) { 344 | MethodHandle target; 345 | try { 346 | target = linker.apply(constants, linkageType); 347 | } catch (ClassNotFoundException e) { 348 | throw (NoClassDefFoundError) new NoClassDefFoundError().initCause(e); 349 | } catch (IllegalAccessException e) { 350 | throw (IllegalAccessError) new IllegalAccessError().initCause(e); 351 | } catch (InstantiationException e) { 352 | throw (InstantiationError) new InstantiationError().initCause(e); 353 | } catch (NoSuchFieldException e) { 354 | throw (NoSuchFieldError) new NoSuchFieldError().initCause(e); 355 | } catch (NoSuchMethodException e) { 356 | throw (NoSuchMethodError) new NoSuchMethodError().initCause(e); 357 | } 358 | 359 | requireNonNull(target, "linker return value is null"); 360 | if (!target.type().equals(linkageType)) { 361 | throw new WrongMethodTypeException("linker return value as the wrong type"); 362 | } 363 | return target; 364 | } 365 | 366 | private static final class RootCallSite extends MutableCallSite implements MethodHandleControl { 367 | private static final MethodHandle FALLBACK, DERIVE_CHECK, REQUIRE_CONSTANT; 368 | static { 369 | var lookup = MethodHandles.lookup(); 370 | try { 371 | FALLBACK = lookup.findVirtual(RootCallSite.class, "fallback", methodType(Object.class, Object[].class)); 372 | DERIVE_CHECK = lookup.findStatic(RootCallSite.class, "derivedCheck", methodType(boolean.class, Object.class, Class.class, ProjectionFunction.class, Object.class)); 373 | REQUIRE_CONSTANT = lookup.findStatic(RootCallSite.class, "requireConstant", methodType(Object.class, Object.class, Class.class, ProjectionFunction.class, Object.class)); 374 | } catch (NoSuchMethodException | IllegalAccessException e) { 375 | throw new AssertionError(e); 376 | } 377 | } 378 | 379 | private final List parameters; 380 | private final Linker linker; 381 | private final MethodHandle fallback; 382 | 383 | public RootCallSite(MethodType type, List parameters, Linker linker) { 384 | super(type); 385 | this.parameters = parameters; 386 | this.linker = linker; 387 | var fallback = FALLBACK.bindTo(this).asCollector(Object[].class, type.parameterCount()).asType(type); 388 | this.fallback = fallback; 389 | setTarget(fallback); 390 | } 391 | 392 | @Override 393 | public MethodHandle createMH() { 394 | return dynamicInvoker(); 395 | } 396 | 397 | @Override 398 | public void deoptimize() { 399 | setTarget(fallback); 400 | MutableCallSite.syncAll(new MutableCallSite[] { this }); 401 | } 402 | 403 | private static boolean derivedCheck(Object arg, Class type, ProjectionFunction function, Object constant) { 404 | return function.computeConstant(type, arg) == constant; 405 | } 406 | 407 | private static Object requireConstant(Object arg, Class type, ProjectionFunction function, Object constant) { 408 | if (function.computeConstant(type, arg) != constant) { 409 | throw new IllegalStateException("constant violation for argument " + arg + " != " + constant); 410 | } 411 | return arg; 412 | } 413 | 414 | private MethodHandle dropValuesAndInstallGuards(List arguments, 415 | MethodType methodType, MethodHandle target) { 416 | 417 | // take care of the dropped values 418 | for(var argument: arguments) { 419 | switch (argument) { 420 | case IgnoredArgument ignoredArgument -> { 421 | target = dropArguments(target, ignoredArgument.position, ignoredArgument.type); 422 | } 423 | case GuardedArgument guardedArgument -> { 424 | if (guardedArgument.dropValue) { 425 | target = dropArguments(target, guardedArgument.position, guardedArgument.type); 426 | } 427 | } 428 | case ValueArgument __ -> {} 429 | } 430 | } 431 | 432 | // install guards 433 | for(var argument: arguments) { 434 | switch (argument) { 435 | case IgnoredArgument __ -> {} 436 | case GuardedArgument guardedArgument -> { 437 | var type = guardedArgument.type; 438 | if (guardedArgument.policy == ConstantPolicy.ERROR) { 439 | var requireConstant = insertArguments(REQUIRE_CONSTANT, 1, type, guardedArgument.function, guardedArgument.constant) 440 | .asType(methodType(type, type)); 441 | target = MethodHandles.filterArguments(target, guardedArgument.position, requireConstant); 442 | continue; 443 | } 444 | var deriveCheck = insertArguments(DERIVE_CHECK, 1, type, guardedArgument.function, guardedArgument.constant) 445 | .asType(methodType(boolean.class, type)); 446 | var test = dropArguments(deriveCheck, 0, target.type().parameterList().subList(0, guardedArgument.position)); 447 | var fallback = guardedArgument.policy == ConstantPolicy.RELINK? 448 | this.fallback : 449 | new RootCallSite(methodType, parameters, linker).dynamicInvoker(); 450 | target = MethodHandles.guardWithTest(test, target, fallback); 451 | } 452 | case ValueArgument __ -> {} 453 | } 454 | } 455 | return target; 456 | } 457 | 458 | private Object fallback(Object[] args) throws Throwable { 459 | var analysisResult = argumentAnalysis(args, parameters, type()); 460 | var arguments = analysisResult.arguments; 461 | var constants = analysisResult.constants; 462 | var values = analysisResult.values; 463 | var linkageType = analysisResult.linkageType; 464 | 465 | var linkerTarget = link(linker, constants, linkageType); 466 | var target = dropValuesAndInstallGuards(arguments, type(), linkerTarget); 467 | setTarget(target); 468 | 469 | return linkerTarget.invokeWithArguments(values); 470 | } 471 | } 472 | 473 | /** 474 | * Rethrow any throwable without the compiler considering as a checked exception. 475 | * 476 | * @param cause a throwable to throw 477 | * @return nothing typed as an AssertionError so rethrow can be a parameter of @code throw}. 478 | */ 479 | public static AssertionError rethrow(Throwable cause) { 480 | throw rethrow0(cause); 481 | } 482 | 483 | @SuppressWarnings("unchecked") // allow to erase the exception type, see above 484 | private static AssertionError rethrow0(Throwable cause) throws T { 485 | throw (T) cause; 486 | } 487 | 488 | /** 489 | * Returns a {@code java.lang.invoke.SerializedLambda} from a serializable lambda. 490 | * This operation quite slow, so it should not be done in a fast path. 491 | * 492 | * @param lookup a lookup that can see the lambda 493 | * @param lambda a serializable lambda 494 | * @return a SerializedLambda object containing all the info about a lambda 495 | */ 496 | public static SerializedLambda crack(Lookup lookup, Object lambda) { 497 | if (!(lambda instanceof Serializable)) { 498 | throw new IllegalArgumentException("the lambda is not serializable"); 499 | } 500 | MethodHandle writeReplace; 501 | try { 502 | writeReplace = lookup.findVirtual(lambda.getClass(), "writeReplace", methodType(Object.class)); 503 | } catch (IllegalAccessException e) { 504 | throw (IllegalAccessError) new IllegalAccessError().initCause(e); 505 | } catch (NoSuchMethodException e) { 506 | throw (NoSuchMethodError) new NoSuchMethodError().initCause(e); 507 | } 508 | try { 509 | return (SerializedLambda) writeReplace.invoke(lambda); 510 | } catch (Throwable t) { 511 | throw rethrow(t); 512 | } 513 | } 514 | } 515 | -------------------------------------------------------------------------------- /src/test/java/com/github/forax/macro/DeoptimizableTest.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.lang.invoke.MethodHandle; 6 | import java.lang.invoke.MethodHandles; 7 | import java.lang.invoke.MethodType; 8 | import java.util.List; 9 | 10 | import static java.lang.invoke.MethodType.methodType; 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | 13 | public class DeoptimizableTest { 14 | @Test 15 | public void constantAndDeoptimization() throws Throwable { 16 | var box = new Object() { private int value = 42; }; 17 | var control = Macro.createMHControl(methodType(int.class), List.of(), 18 | (__, methodType) -> MethodHandles.constant(int.class, box.value)); 19 | var mh = control.createMH(); 20 | assertEquals(42, (int)mh.invokeExact()); 21 | 22 | box.value = 747; 23 | assertEquals(42, (int) mh.invokeExact()); 24 | 25 | control.deoptimize(); 26 | assertEquals(747, (int) mh.invokeExact()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/github/forax/macro/ExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro; 2 | 3 | import com.github.forax.macro.example.almostconstant; 4 | import com.github.forax.macro.example.builder1; 5 | import com.github.forax.macro.example.builder2; 6 | import com.github.forax.macro.example.builder3; 7 | import com.github.forax.macro.example.fmt; 8 | import com.github.forax.macro.example.multimethods; 9 | 10 | import org.junit.jupiter.api.Test; 11 | 12 | public class ExampleTest { 13 | @Test 14 | public void builder1() { 15 | builder1.main(new String[0]); 16 | } 17 | 18 | @Test 19 | public void builder2() { 20 | builder2.main(new String[0]); 21 | } 22 | 23 | @Test 24 | public void builder3() { 25 | builder3.main(new String[0]); 26 | } 27 | 28 | @Test 29 | public void fmt() { 30 | fmt.main(new String[0]); 31 | } 32 | 33 | @Test 34 | public void almostconstant() { 35 | almostconstant.main(new String[0]); 36 | } 37 | 38 | @Test 39 | public void multimethod() { 40 | multimethods.main(new String[0]); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/github/forax/macro/MacroTest.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro; 2 | 3 | import com.github.forax.macro.Macro.Linker; 4 | import com.github.forax.macro.Macro.Parameter; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.io.Serializable; 8 | import java.lang.invoke.MethodHandle; 9 | import java.lang.invoke.MethodHandles; 10 | import java.lang.invoke.MethodHandles.Lookup; 11 | import java.lang.invoke.MethodType; 12 | import java.lang.reflect.RecordComponent; 13 | import java.util.Arrays; 14 | import java.util.Collections; 15 | import java.util.HashSet; 16 | import java.util.List; 17 | import java.util.regex.Pattern; 18 | import java.util.stream.Collectors; 19 | import java.util.stream.IntStream; 20 | import java.util.stream.Stream; 21 | 22 | import static com.github.forax.macro.Macro.CONSTANT_CLASS; 23 | import static com.github.forax.macro.Macro.CONSTANT_VALUE; 24 | import static com.github.forax.macro.Macro.VALUE; 25 | import static java.lang.invoke.MethodType.methodType; 26 | import static org.junit.jupiter.api.Assertions.*; 27 | 28 | public class MacroTest { 29 | @Test 30 | public void simple() throws Throwable { 31 | class Foo { 32 | public double bar(int value) { return 1.0; } 33 | public double baz(int value) { return 2.0; } 34 | } 35 | 36 | class Example { 37 | private static final MethodHandle MH; 38 | static { 39 | Lookup lookup = MethodHandles.lookup(); 40 | MH = Macro.createMH(MethodType.methodType(double.class, Foo.class, String.class, int.class), 41 | List.of(Macro.VALUE, Macro.CONSTANT_VALUE.polymorphic(), Macro.VALUE), 42 | (constants, type) -> { 43 | String name = (String) constants.get(0); 44 | return lookup.findVirtual(Foo.class, name, MethodType.methodType(double.class, int.class)).asType(type); 45 | }); 46 | } 47 | 48 | public static double call(Foo foo, String name, int value) { 49 | try { 50 | return (double) MH.invokeExact(foo, name, value); 51 | } catch(Throwable t) { 52 | throw Macro.rethrow(t); 53 | } 54 | } 55 | } 56 | 57 | Foo foo = new Foo(); 58 | assertEquals(1.0, Example.call(foo, "bar", 42)); 59 | assertEquals(1.0, Example.call(foo, "bar", 42)); 60 | assertEquals(2.0, Example.call(foo, "baz", 42)); 61 | assertEquals(2.0, Example.call(foo, "baz", 42)); 62 | } 63 | 64 | @Test 65 | public void pattern() { 66 | interface PatternFactory { 67 | Pattern pattern(String pattern); 68 | 69 | static PatternFactory of() { 70 | record PatternFactoryImpl(MethodHandle mh) implements PatternFactory { 71 | @Override 72 | public Pattern pattern(String pattern) { 73 | try { 74 | return (Pattern) mh.invokeExact(pattern); 75 | } catch(Throwable t) { 76 | throw Macro.rethrow(t); 77 | } 78 | } 79 | } 80 | 81 | var mh = Macro.createMH(methodType(Pattern.class, String.class), 82 | List.of(CONSTANT_VALUE), 83 | (constants, type) -> MethodHandles.constant(Pattern.class, Pattern.compile((String) constants.get(0)))); 84 | return new PatternFactoryImpl(mh); 85 | } 86 | } 87 | 88 | var factory = PatternFactory.of(); 89 | var pattern1 = factory.pattern("foo"); 90 | var pattern2 = factory.pattern("foo"); 91 | assertAll( 92 | () -> assertSame(pattern1, pattern2), 93 | () -> assertThrows(IllegalStateException.class, () -> factory.pattern("bar")) 94 | ); 95 | } 96 | 97 | @Test 98 | public void dynamicDispatch() { 99 | interface Dispatch { 100 | T call(Object receiver, String name, MethodType methodType, Object... args); 101 | 102 | static Dispatch of(Lookup lookup) { 103 | record DispatchImpl(MethodHandle mh) implements Dispatch { 104 | @Override 105 | @SuppressWarnings("unchecked") 106 | public T call(Object receiver, String name, MethodType methodType, Object... args) { 107 | try { 108 | return (T) mh.invokeExact(receiver, name, methodType, args); 109 | } catch(Throwable t) { 110 | throw Macro.rethrow(t); 111 | } 112 | } 113 | } 114 | 115 | var mh = Macro.createMH(methodType(Object.class, Object.class, String.class, MethodType.class, Object[].class), 116 | List.of(CONSTANT_CLASS.polymorphic(), CONSTANT_VALUE, CONSTANT_VALUE, VALUE), 117 | (constants, type) -> { 118 | var receiverClass = (Class) constants.get(0); 119 | var name = (String) constants.get(1); 120 | var methodType = (MethodType) constants.get(2); 121 | return lookup.findVirtual(receiverClass, name, methodType) 122 | .asSpreader(Object[].class, methodType.parameterCount()) 123 | .asType(type); 124 | }); 125 | return new DispatchImpl(mh); 126 | } 127 | } 128 | 129 | record A() { 130 | String m(long value) { return "A"; } 131 | } 132 | record B() { 133 | String m(long value) { return "B"; } 134 | } 135 | 136 | var dispatch = Dispatch.of(MethodHandles.lookup()); 137 | assertEquals("A", dispatch.call(new A(), "m", methodType(String.class, long.class), 3L)); 138 | assertEquals("B", dispatch.call(new B(), "m", methodType(String.class, long.class), 4L)); 139 | assertEquals("A", dispatch.call(new A(), "m", methodType(String.class, long.class), 5L)); 140 | assertEquals("B", dispatch.call(new B(), "m", methodType(String.class, long.class), 6L)); 141 | } 142 | 143 | @Test 144 | public void visitorDispatch() { 145 | interface VisitorCaller { 146 | R call(Object visitor, Object object); 147 | 148 | static VisitorCaller of(Lookup lookup, Class visitorClass, Class returnType) { 149 | record VisitorCallerImpl(MethodHandle mh) implements VisitorCaller { 150 | @Override 151 | @SuppressWarnings("unchecked") 152 | public R call(Object visitor, Object element) { 153 | try { 154 | return (R) mh.invokeExact(visitor, element); 155 | } catch(Throwable t) { 156 | throw Macro.rethrow(t); 157 | } 158 | } 159 | } 160 | 161 | var mh = Macro.createMH(methodType(returnType, visitorClass, Object.class), 162 | List.of(CONSTANT_CLASS.relink(), CONSTANT_CLASS.polymorphic()), 163 | (constants, type) -> { 164 | var visitorType = (Class) constants.get(0); 165 | var elementType = (Class) constants.get(1); 166 | return lookup.findVirtual(visitorType, "visit", methodType(returnType, elementType)).asType(type); 167 | }) 168 | .asType(methodType(Object.class, Object.class, Object.class)); 169 | return new VisitorCallerImpl<>(mh); 170 | } 171 | } 172 | 173 | interface Vehicle {} 174 | record Car() implements Vehicle {} 175 | record Bus() implements Vehicle {} 176 | interface Visitor { 177 | R visit(Car car); 178 | R visit(Bus bus); 179 | } 180 | var visitor = new Visitor() { 181 | @Override 182 | public String visit(Car car) { 183 | return "Car"; 184 | } 185 | @Override 186 | public String visit(Bus bus) { 187 | return "Bus"; 188 | } 189 | }; 190 | 191 | var caller = VisitorCaller.of(MethodHandles.lookup(), visitor.getClass(), String.class); 192 | assertEquals("Car", caller.call(visitor, new Car())); 193 | assertEquals("Bus", caller.call(visitor, new Bus())); 194 | assertEquals("Car", caller.call(visitor, new Car())); 195 | assertEquals("Bus", caller.call(visitor, new Bus())); 196 | } 197 | } -------------------------------------------------------------------------------- /src/test/java/com/github/forax/macro/ParameterTest.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.macro; 2 | 3 | import com.github.forax.macro.Macro.ConstantParameter; 4 | import com.github.forax.macro.Macro.ConstantPolicy; 5 | import com.github.forax.macro.Macro.ProjectionFunction; 6 | import org.junit.jupiter.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.Arguments; 8 | import org.junit.jupiter.params.provider.MethodSource; 9 | 10 | import java.lang.invoke.MethodHandles; 11 | import java.lang.invoke.MethodType; 12 | import java.util.List; 13 | import java.util.stream.Stream; 14 | 15 | import static org.junit.jupiter.api.Assertions.assertEquals; 16 | import static org.junit.jupiter.api.Assertions.assertNull; 17 | 18 | public class ParameterTest { 19 | private static Stream provideArguments() { 20 | return Stream.of(0) 21 | .mapMulti((__, consumer) -> { 22 | for(var projection: new ProjectionFunction[] { ProjectionFunction.VALUE, ProjectionFunction.GET_CLASS }) { 23 | for(var dropValue: new boolean[] { true, false}) { 24 | for(var policy: ConstantPolicy.values()) { 25 | consumer.accept(Arguments.of(projection, dropValue, policy)); 26 | } 27 | } 28 | } 29 | }); 30 | } 31 | 32 | @ParameterizedTest 33 | @MethodSource("provideArguments") 34 | public void macroParameterWithObject(ProjectionFunction function, boolean dropValue, ConstantPolicy policy) throws Throwable { 35 | var parameter = new ConstantParameter(function, dropValue, policy); 36 | var mh = 37 | Macro.createMH( 38 | MethodType.methodType(Object.class, Object.class), List.of(parameter), (constants, methodType) -> { 39 | var expectedConstant = (function == ProjectionFunction.VALUE)? 42: Integer.class; 40 | assertEquals(List.of(expectedConstant), constants); 41 | 42 | var expectedMethodType = dropValue? MethodType.methodType(Object.class): MethodType.methodType(Object.class, Object.class); 43 | assertEquals(expectedMethodType, methodType); 44 | 45 | return MethodHandles.empty(methodType); 46 | }); 47 | assertNull(mh.invoke(42)); 48 | } 49 | 50 | @ParameterizedTest 51 | @MethodSource("provideArguments") 52 | public void macroParameterWithAnInterface(ProjectionFunction function, boolean dropValue, ConstantPolicy policy) throws Throwable { 53 | interface I {} 54 | record R() implements I {} 55 | 56 | var r = new R(); 57 | var parameter = new ConstantParameter(function, dropValue, policy); 58 | var mh = 59 | Macro.createMH( 60 | MethodType.methodType(int.class, I.class), List.of(parameter), (constants, methodType) -> { 61 | var expectedConstant = (function == ProjectionFunction.VALUE)? r: R.class; 62 | assertEquals(List.of(expectedConstant), constants); 63 | 64 | var expectedMethodType = dropValue? MethodType.methodType(int.class): MethodType.methodType(int.class, I.class); 65 | assertEquals(expectedMethodType, methodType); 66 | 67 | return MethodHandles.empty(methodType); 68 | }); 69 | assertEquals(0, mh.invoke(r)); 70 | } 71 | } 72 | --------------------------------------------------------------------------------