001package io.jstach.jstache; 002 003import java.lang.annotation.Documented; 004import java.lang.annotation.ElementType; 005import java.lang.annotation.Retention; 006import java.lang.annotation.RetentionPolicy; 007import java.lang.annotation.Target; 008import java.util.Map; 009import java.util.Optional; 010 011/** 012 * Generates a JStachio Renderer from a template and a model (the annotated class). 013 * <p> 014 * Classes annotated are typically called "models" as they will be the root context for 015 * the template. 016 * 017 * <h2 class="toc-title">Contents</h2> <div class="js-toc"></div> 018 * <div class="js-toc-content"> 019 * <h2 id="_example">Example Usage</h2> 020 * 021 * <pre class="code"> 022 * <code> 023 * @JStache(template = """ 024 * {{#people}} 025 * {{message}} {{name}}! You are {{#ageInfo}}{{age}}{{/ageInfo}} years old! 026 * {{#-last}} 027 * That is all for now! 028 * {{/-last}} 029 * {{/people}} 030 * """) 031 * public record HelloWorld(String message, List<Person> people) implements AgeLambdaSupport {} 032 * 033 * public record Person(String name, LocalDate birthday) {} 034 * 035 * public record AgeInfo(long age, String date) {} 036 * 037 * public interface AgeLambdaSupport { 038 * @JStacheLambda 039 * default AgeInfo ageInfo( 040 * Person person) { 041 * long age = ChronoUnit.YEARS.between(person.birthday(), LocalDate.now()); 042 * String date = person.birthday().format(DateTimeFormatter.ISO_DATE); 043 * return new AgeInfo(age, date); 044 * } 045 * } 046 * </code> </pre> 047 * 048 * <h2 id="_model_and_templates">Models and Templates</h2> 049 * 050 * Because JStachio checks types its best to think of the model and template as married. 051 * With the exception of partials JStachio cannot have a template without a model and vice 052 * versa. The way to create Renderer (what we call the model and template combined) is to 053 * annotate your model with {@link io.jstach.jstache.JStache}. 054 * 055 * <h3 id="_models">Models</h3> <strong>@{@link io.jstach.jstache.JStache}</strong> 056 * <p> 057 * A JStachio model can be any class type including Records and Enums so long as you can 058 * you annotate the type with {@link io.jstach.jstache.JStache}. 059 * <p> 060 * When the compiler runs the annotation processor will create readable java classes that 061 * are suffixed with "Renderer" which will have methods to write the model to an 062 * {@link java.lang.Appendable}. The generated instance methods are named 063 * <code>execute</code> and the corresponding static methods are named 064 * <code>render</code>. 065 * <p> 066 * <em>TIP: If you like to see the generated classes from the annotation processor they 067 * usually get put in <code>target/generated-sources/annotations</code> for Maven 068 * projects.</em> 069 * 070 * <h4 id="_decorating_models">Adding interfaces to models and renderers</h4> 071 * <strong>@{@link io.jstach.jstache.JStacheInterfaces}</strong> 072 * <p> 073 * Java has a huge advantage over JSON and Javascript. <em>You can use interfaces to add 074 * additional variables as well as lambda methods 075 * ({@link io.jstach.jstache.JStacheLambda})!</em> To enforce that certain interfaces are 076 * added to models (the ones annotated) and renderers (the generated classes) you can use 077 * {@link io.jstach.jstache.JStacheInterfaces} on packages or the classes themselves. 078 * <p> 079 * You can also make generated classes have {@link ElementType#TYPE} annotations (see 080 * {@link JStacheInterfaces#templateAnnotations()}) and extend a class 081 * {@link JStacheInterfaces#templateExtends()}) as well which maybe useful for integration 082 * with other frameworks particularly DI frameworks. 083 * 084 * <h3 id="_templates">Templates</h3> 085 * 086 * The format of the templates should by default be Mustache. The syntax is informally 087 * explained by the 088 * <a href="https://jgonggrijp.gitlab.io/wontache/mustache.5.html">mustache manual</a> and 089 * formally explained by the <a href="https://github.com/mustache/spec">spec</a>. There 090 * are some subtle differences in JStachio version of Mustache due to the static nature 091 * that are discussed in <a href="#_context_lookup">context lookup</a>. <strong>Template 092 * finding is as follows:</strong> 093 * <ol> 094 * <li><code>path</code> which is a classpath with slashes following the same format as 095 * the ClassLoader resources. The path maybe augmented with {@link JStachePath}. 096 * <li><code>template</code> which if not empty is used as the template contents 097 * <li>if the above is not set then the name of the class suffixed with ".mustache" is 098 * used as the resource. 099 * </ol> 100 * 101 * <h4 id="_inline_templates">Inline Templates</h4> 102 * <strong>{@link io.jstach.jstache.JStache#template()}</strong> 103 * <p> 104 * Inline templates are pretty straight forward. Just set 105 * {@link io.jstach.jstache.JStache#template()} to a literal string. If you go this route 106 * it is <em>highly recommend you use the new triple quote string literal for inline 107 * templates</em> 108 * 109 * <h4 id="_resource_templates">Resource Templates</h4> 110 * <strong>{@link io.jstach.jstache.JStache#path()} and 111 * @{@link io.jstach.jstache.JStachePath} </strong> 112 * <p> 113 * Resource templates are files that are in the classpath and are more complicated because 114 * of lookup resolution. 115 * <p> 116 * When the annotation processor runs these files usually are in: 117 * <code>javax.tools.StandardLocation#CLASS_OUTPUT</code> and in a Maven or Gradle project 118 * they normally would reside in <code>src/main/resources</code> or 119 * <code>src/test/resources</code> which get copied on build to 120 * <code>target/classes</code> or similar. <em>N.B. becareful not to have resource 121 * filtering turned on for mustache templates.</em> 122 * <p> 123 * Ideally JStachio would use <code>javax.tools.StandardLocation#SOURCE_PATH</code> to 124 * find resource templates but that is currently <a href= 125 * "https://stackoverflow.com/questions/22494596/eclipse-annotation-processor-get-project-path"> 126 * problematic with incremental compilers such as Eclipse</a>. 127 * <p> 128 * Another issue with incremental compiling is that template files are not always copied 129 * after being edited to <code>target/classes</code> and thus are not found by the 130 * annotation processor. To deal with this issue JStachio during compilation fallsback to 131 * direct filesystem access and assumes that your templates are located: 132 * <code>CWD/src/main/resources</code>. That location is configurable via the annotation 133 * processor option {@link #RESOURCES_PATH_OPTION} 134 * (<strong>{@value #RESOURCES_PATH_OPTION}</strong>). 135 * 136 * <p> 137 * Normally you need to specify the full path in {@link #path()} which is a resource path 138 * (and not a file path) as specified by {@link ClassLoader#getResource(String)} however 139 * you can make path expansion happen with {@link io.jstach.jstache.JStachePath} which 140 * allows you to prefix and suffix the path. 141 * 142 * <h4 id="_partials">Partials</h4> 143 * <strong><code>{{> partial }} and {{< parent }}{{/parent}} </code></strong> 144 * <p> 145 * JStachio supports Mustache partials (and parents) and by default works just like 146 * template resources such that {@link io.jstach.jstache.JStachePath} is used for 147 * resolution if specified. 148 * <p> 149 * You may also remap partial names via {@link io.jstach.jstache.JStachePartial} to a 150 * different location as well as to an inline template (string literal). 151 * 152 * 153 * <h4 id="_optional_spec">Optional Spec Support</h4> JStachio implements some optional 154 * parts of the specification. Below shows what is and is not supported. 155 * <table border="1"> 156 * <caption><strong>Optional Spec Features Table</strong></caption> 157 * <tr> 158 * <th>Name</th> 159 * <th>Supported</th> 160 * <th>Manual Description</th> 161 * </tr> 162 * <tr> 163 * <td>Lambda variables (arity 0)</td> 164 * <td style="color:red;">NO</td> 165 * <td>An optional part of the specification states that if the final key in the name is a 166 * lambda that returns a string, then that string should be rendered as a Mustache 167 * template before interpolation. It will be rendered using the default delimiters (see 168 * Set Delimiter below) against the current context.</td> 169 * </tr> 170 * <tr> 171 * <td>Lambda sections (arity 1)</td> 172 * <td style="color:blue;">YES</td> 173 * <td>An optional part of the specification states that if the final key in the name is a 174 * lambda that returns a string, then that string replaces the content of the section. It 175 * will be rendered using the same delimiters (see Set Delimiter below) as the original 176 * section content. In this way you can implement filters or caching.</td> 177 * </tr> 178 * <tr> 179 * <td>Dynamic Names</td> 180 * <td style="color:red;">NO</td> 181 * <td>Partials can be loaded dynamically at runtime using Dynamic Names; an optional part 182 * of the Mustache specification which allows to dynamically determine a tag's content at 183 * runtime.</td> 184 * </tr> 185 * <tr> 186 * <td>Blocks</td> 187 * <td style="color:blue;">YES</td> 188 * <td>A block begins with a dollar and ends with a slash. That is, {{$title}} begins a 189 * "title" block and {{/title}} ends it.</td> 190 * </tr> 191 * <tr> 192 * <td>Parents</td> 193 * <td style="color:blue;">YES</td> 194 * <td>A parent begins with a less than sign and ends with a slash. That is, 195 * {{<article}} begins an "article" parent and {{/article}} ends it.</td> 196 * </tr> 197 * </table> 198 * 199 * <h3 id="_context_lookup">Context Lookup</h3> 200 * 201 * JStachio unlike almost all other Mustache implementations does its context lookup 202 * statically during compile time. Consequently JStachio pedantically is early bound where 203 * as Mustache is traditionally late bound. Most of the time this difference will not 204 * manifest itself so long as you avoid using {@link Map} in your models. 205 * <p> 206 * The other notable difference is JStachio does not like missing variables (a compiler 207 * error will happen) where as many Mustache implementations sometimes allow this and will 208 * just not output anything. 209 * 210 * <h4 id="_context_java_types">Interpretation of Java-types and values</h4> When some 211 * value is null nothing is rendered if it is used as a section. If some value is null and 212 * it is used as a variable a null pointer exception will be thrown by default. This is 213 * configurable via {@link JStacheFormatterTypes} and custom {@link JStacheFormatter}. 214 * <p> 215 * Boxed and unboxed <code>boolean</code> can be used for mustache-sections. Section is 216 * only rendered if value is true. 217 * <p> 218 * {@link Optional} empty is treated like an empty list or a boolean false. Optional 219 * values are always assumed to be non null. 220 * <p> 221 * {@code Map<String,?>} follow different nesting rules than other types. If you are in a 222 * {@link Map} nested section the rest of the context is checked before the 223 * <code>Map</code>. Once that is done the Map is then checked using 224 * {@link Map#get(Object)}' where the key is the <em>last part of the dotted name</em>. 225 * <p> 226 * Data-binding contexts are nested. Names are looked up in innermost context first. If 227 * name is not found in current context, parent context is inspected. This process 228 * continues up to root context. 229 * 230 * In each rendering context name lookup is performed as follows: 231 * 232 * <ol> 233 * <li>Method with requested name is looked up. Method should have no arguments and should 234 * throw no checked exceptions. If there is such method it is used to fetch actual data to 235 * render. Compile-time error is raised if there is method with given name, but it is not 236 * accessible, has parameters or throws checked exceptions.</li> 237 * <li>Method with requested name and annotated correctly with {@link JStacheLambda} and 238 * the lookup is for a section than the method lambda method will be used.</li> 239 * <li>Method with getter-name for requested name is looked up. (For example, if 'age' is 240 * requested, 'getAge' method is looked up.) Method should have no arguments and should 241 * throw no checked exceptions. If there is such method it is used to fetch actual data to 242 * render. Compile-time error is raised if there is method with such name, but it is not 243 * accessible, has parameters or throws checked exceptions</li> 244 * 245 * <li>Field with requested name is looked up. Compile-time error is raised if there is 246 * field with such name but it's not accessible.</li> 247 * </ol> 248 * 249 * <h4 id="_enums">Enum matching Support Extension</h4> Basically enums have boolean keys 250 * that are the enums name (`Enum.name()`) that can be used as conditional sections. 251 * Assume `light` is an enum like: 252 * 253 * <pre> 254 * <code class="language-java"> 255 * public enum Light { 256 * RED, 257 * GREEN, 258 * YELLOW 259 * } 260 * </code> </pre> 261 * 262 * You can conditinally select on the enum like a pattern match: 263 * 264 * <pre> 265 * <code class="language-hbs"> 266 * {{#light.RED}} 267 * STOP 268 * {{/light.RED}} 269 * {{#light.GREEN}} 270 * GO 271 * {{/light.GREEN}} 272 * {{#light.YELLOW}} 273 * Proceeed with caution 274 * {{/light.YELLOW}} 275 * </code> </pre> 276 * 277 * <h4 id="_index_support">Index Support Extension</h4> 278 * 279 * JStachio is compatible with both handlebars and JMustache index keys for iterable 280 * sections. 281 * <ol> 282 * <li><code>-first</code> is boolean that is true when you are on the first item 283 * <li><code>-last</code> is a boolean that is true when you are on the last item in the 284 * iterable 285 * <li><code>-index</code> is a one based index. The first item would be `1` and not `0` 286 * </ol> 287 * 288 * <h3 id="_lambdas">Lambda Support</h3> 289 * 290 * <strong>@{@link JStacheLambda}</strong> 291 * <p> 292 * JStachio supports lambda section calls in a similar manner to 293 * <a href="https://github.com/samskivert/jmustache">JMustache</a>. Just tag your methods 294 * with {@link JStacheLambda} and the returned models will be used to render the contents 295 * of the lambda section. The top of the context stack can be passed to the lambda. 296 * 297 * 298 * <h2 id="_code_generation">Code Generation</h2> 299 * 300 * <strong>@{@link io.jstach.jstache.JStacheConfig#type()}</strong> 301 * <p> 302 * JStachio by default reads mustache syntax and generates code that needs the jstachio 303 * runtime (io.jstache.jstachio). However it is possible to generate code that does not 304 * need the runtime and possibly in the future other syntaxs like Handlebars might be 305 * supported. 306 * 307 * <h3 id="_methods_generated">Generated Renderer Classes</h3> JStachio generates a single 308 * class from a mustache template and model (class annotated with JStache) pair. The 309 * generated classes are generally called "Renderers" or sometimes "Templates". Depending 310 * on which JStache type is picked different methods are generated. The guaranteed 311 * generated methods <em>not to change on minor version or less</em> on the renderer 312 * classes are discussed in <strong>{@link JStacheType}</strong>. 313 * 314 * <h3 id="_zero_dep">Zero dependency code generation</h3> 315 * 316 * <strong>@{@link io.jstach.jstache.JStacheConfig#type()} == 317 * {@link JStacheType#STACHE}</strong> 318 * <p> 319 * Zero dependency code generation is useful if you want to avoid coupling your runtime 320 * and downstream dependencies with JStachio (including the annotations themselves) as 321 * well as minimize the overall footprint and or classes loaded. A common use case would 322 * be using jstachio for code generation in an annotation processing library where you 323 * want as minimal class path issues as possible. 324 * <p> 325 * If this configuration is selected generated code will <strong>ONLY have references to 326 * stock base JDK module ({@link java.base/}) classes</strong>. However one major caveat 327 * is that generated classes will not be reflectively accessible to the JStachio runtime 328 * and thus fallback and filtering will not work. Thus in a web framework environment this 329 * configuration choice is less desirable. 330 * <p> 331 * <em>n.b. as long as the jstachio annotations are not accessed reflectively you do not 332 * need the annotation jar in the classpath during runtime thus the annotations jar is 333 * effectively an optional compile time dependency.</em> 334 * 335 * 336 * <h2 id="_formatting">Formatting variables</h2> 337 * 338 * JStachio has strict control on what happens when you output a variable like 339 * <code>{{variable}}</code> or <code>{{{variable}}}</code>. 340 * 341 * <h3 id="_allowed_types">Allowed formatting types</h3> <strong> 342 * @{@link io.jstach.jstache.JStacheFormatterTypes}</strong> 343 * <p> 344 * Only a certain set of types are allowed to be formatted and if they are not a compiler 345 * error will happen (as in the annotation processor will fail). To understand more about 346 * that see {@link io.jstach.jstache.JStacheFormatterTypes}. 347 * 348 * <h3 id="_runtime_formatting">Runtime formatting</h3> 349 * <strong>@{@link io.jstach.jstache.JStacheFormatter} and 350 * @{@link JStacheConfig#formatter()}</strong> 351 * <p> 352 * Assuming the compiler allowed the variable to be formatted you can control the output 353 * via {@link io.jstach.jstache.JStacheFormatter} and setting 354 * {@link io.jstach.jstache.JStacheConfig#formatter()}. 355 * 356 * <h2 id="_escaping">Escaping and Content Type</h2> 357 * <strong>@{@link io.jstach.jstache.JStacheContentType}, and 358 * @{@link JStacheConfig#contentType()} </strong> 359 * <p> 360 * If you are using the JStachio runtime (io.jstach.jstachio) you will get out of the box 361 * escaping for HTML (see <code>io.jstach.jstachio.escapers.Html</code>) per the mustache 362 * spec. 363 * <p> 364 * <strong>To disable escaping</strong> set {@link JStacheConfig#contentType()} to 365 * <code>io.jstach.jstachio.escapers.PlainText</code> 366 * 367 * <h2 id="_config">Configuration</h2> <strong>@{@link JStacheConfig}</strong> 368 * <p> 369 * You can set global configuration on class, packages and module elements. See 370 * {@link JStacheConfig} for more details on config resolution. Some configuration is set 371 * through compiler flags and annotation processor options. However {@link JStacheConfig} 372 * unlike compiler flags and annotation processor options are available during runtime 373 * through reflective access. 374 * 375 * <h3 id="_config_flags">Compiler flags</h3> 376 * 377 * The compiler has some boolean flags that can be set statically via {@link JStacheFlags} 378 * as well as through annotation processor options. 379 * 380 * <h3 id="_config_compiler">Annotation processor options</h3> 381 * 382 * Some configuration is available as an annotation processor option. Current available 383 * options are: 384 * 385 * <ul> 386 * <li>{@link #RESOURCES_PATH_OPTION}</li> 387 * </ul> 388 * 389 * The previously mentioned {@link JStacheFlags compiler flags} are also available as 390 * annotation options. The flags are prefixed with "<code>jstache.</code>". For example 391 * {@link JStacheFlags.Flag#DEBUG} would be: 392 * <p> 393 * <code>jstache.debug=true/false</code>. 394 * 395 * <h4 id="_config_compiler_maven">Configuring options with Maven</h4> 396 * 397 * Example configuration with Maven: 398 * 399 * <pre class="language-xml">{@code 400 * <plugin> 401 * <groupId>org.apache.maven.plugins</groupId> 402 * <artifactId>maven-compiler-plugin</artifactId> 403 * <version>3.8.1</version> 404 * <configuration> 405 * <source>17</source> 406 * <target>17</target> 407 * <annotationProcessorPaths> 408 * <path> 409 * <groupId>io.jstach</groupId> 410 * <artifactId>jstachio-apt</artifactId> 411 * <version>${io.jstache.version}</version> 412 * </path> 413 * </annotationProcessorPaths> 414 * <compilerArgs> 415 * <arg> 416 * -Ajstache.resourcesPath=src/main/resources 417 * </arg> 418 * <arg> 419 * -Ajstache.debug=false 420 * </arg> 421 * </compilerArgs> 422 * </configuration> 423 * </plugin> 424 * }</pre> 425 * 426 * <h4 id="_config_compiler_gradle">Configuring options with Gradle</h4> 427 * 428 * Example configuration with Gradle: 429 * 430 * <pre><code class="language-kotlin"> 431 * compileJava { 432 * options.compilerArgs += [ 433 * '-Ajstache.resourcesPath=src/main/resources' 434 * ] 435 * } 436 * </code> </pre> 437 * 438 * 439 * </div> 440 * 441 * @author agentgt 442 * @see JStachePath 443 * @see JStacheFormatterTypes 444 * @see JStacheConfig 445 * @see JStacheFormatter 446 * @see JStacheContentType 447 * @see JStacheConfig 448 */ 449@Retention(RetentionPolicy.RUNTIME) 450@Target(ElementType.TYPE) 451@Documented 452public @interface JStache { 453 454 /** 455 * Resource path to template 456 * @return Path to mustache template 457 * @see JStachePath 458 */ 459 String path() default ""; 460 461 /** 462 * Inline the template as a Java string instead of a file. Use the new triple quote 463 * string literal for complex templates. 464 * @return An inline template 465 */ 466 String template() default ""; 467 468 /** 469 * Name of generated class. 470 * <p> 471 * name can be omitted. <code>model.getClass().getName()</code> + 472 * {@link JStacheName#DEFAULT_SUFFIX} name is used by default. 473 * @return Name of generated class 474 */ 475 String name() default ""; 476 477 /** 478 * An annotation processor compiler flag 479 * (<strong>{@value #RESOURCES_PATH_OPTION}</strong>) that says where the templates 480 * files are located. 481 * <p> 482 * When the annotation processor runs these files usually are in: 483 * <code>javax.tools.StandardLocation#CLASS_OUTPUT</code> and in a Maven or Gradle 484 * project they normally would reside in <code>src/main/resources</code> or 485 * <code>src/test/resources</code> which get copied on build to 486 * <code>target/classes</code> or similar. However due to incremental compiling 487 * template files are not always copied to <code>target/classes</code> and thus are 488 * not found by the annotation processor. To deal with this issue JStachio during 489 * compilation fallsback to direct filesystem access of the <em>source</em> directory 490 * instead of the output (<code>javax.tools.StandardLocation#CLASS_OUTPUT</code>) if 491 * the files cannot be found. 492 * <p> 493 * If the path does not start with a path separator then it will be appended to the 494 * the current working directory otherwise it is assumed to be a fully qualified path. 495 * <p> 496 * The default location is <code>CWD/src/main/resources</code> where CWD is the 497 * current working directory. 498 * 499 * <strong>If the option is blank or empty then NO fallback will happen and 500 * effectively disables the above behavior. </strong> 501 * 502 * You can change it by passing to the annotation processor a setting for 503 * <strong>{@value #RESOURCES_PATH_OPTION}</strong> like: 504 * <pre><code>jstache.resourcesPath=some/path</code></pre> 505 * 506 * For build annotation processor configuration examples see: 507 * <ol> 508 * <li><a href="#_config_compiler_maven">Configuring options with Maven</a></li> 509 * <li><a href="#_config_compiler_gradle">Configuring options with Gradle</a></li> 510 * </ol> 511 * 512 */ 513 public static final String RESOURCES_PATH_OPTION = "jstache.resourcesPath"; 514 515}