String Template processors vs Code Reflection?
Mikael Sterner
msterner at openjdk.mxy.se
Sat Mar 16 04:29:47 UTC 2024
Hi Experts!
What is the relationship between string template processors and code reflection, and would it influence the design of string templates and their literals?
Is the need to process string templates, seen as code snippets aggregating static and dynamic strings, just a special case of a more general pattern of processing code snippets semi-lazily using custom rules? (Such as safe handling of dynamic strings, or contextual operator overloading.)
Examples:
// String template processor
String table = "foo bar";
ResultSet r = s.executeQuery("SELECT * FROM \{table\}"); // Escape dynamic table names
// Code reflection processors
String table = "foo bar";
ResultSet r = s.executeQuery(@CodeReflection () -> "SELECT * FROM " + table); // Escape dynamic table names
String value = "bar";
Pattern p = Pattern.compile(@CodeReflection () -> "foo = " + value); // Quote dynamic strings
Matrix m = Matrix.eval(@CodeReflection () -> Matrix.diag(1, 2, 3) * Matrix.col(2, 3, 4)); // Matrix multiplication
Document d = HTML.compile(@CodeReflection () -> Body.of(Div.of("Hello World!"))); // Escape strings
Each such code reflecting processor API defining it's own rules for how to handle code snippets, including processing of any raw string templates when/if they are added to the language. Other types than String and StringTemplate being handled as fits each API, and to the level of type safety wanted by the API user. Evaluation being done lazily or eagerly as appropriate.
(In the above "@CodeReflection () ->" is short for some syntax allowing inline code reflecting snippets, passed to the API processors in a way that allows them to reflect on the snippet code.)
Yours,
Mikael Sterner
More information about the amber-spec-observers
mailing list