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 class="language-java"> 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>Delimiters</td> 180 * <td style="color:blue;">YES</td> 181 * <td>Set Delimiter tags are used to change the tag delimiters for all content following 182 * the tag in the current compilation unit. The tag's content MUST be any two 183 * non-whitespace sequences (separated by whitespace) EXCEPT an equals sign ('=') followed 184 * by the current closing delimiter. Set Delimiter tags SHOULD be treated as standalone 185 * when appropriate. <em>(this feature is non-optional in current mustache but some 186 * mustaches implemenations treat it as optional)</em></td> 187 * </tr> 188 * <tr> 189 * <td>Dynamic Names</td> 190 * <td style="color:red;">NO</td> 191 * <td>Partials can be loaded dynamically at runtime using Dynamic Names; an optional part 192 * of the Mustache specification which allows to dynamically determine a tag's content at 193 * runtime.</td> 194 * </tr> 195 * <tr> 196 * <td>Blocks</td> 197 * <td style="color:blue;">YES</td> 198 * <td>A block begins with a dollar and ends with a slash. That is, {{$title}} begins a 199 * "title" block and {{/title}} ends it.</td> 200 * </tr> 201 * <tr> 202 * <td>Parents</td> 203 * <td style="color:blue;">YES</td> 204 * <td>A parent begins with a less than sign and ends with a slash. That is, 205 * {{<article}} begins an "article" parent and {{/article}} ends it.</td> 206 * </tr> 207 * </table> 208 * 209 * <h3 id="_context_lookup">Context Lookup</h3> 210 * 211 * JStachio unlike almost all other Mustache implementations does its context lookup 212 * statically during compile time. Consequently JStachio pedantically is early bound where 213 * as Mustache is traditionally late bound. Most of the time this difference will not 214 * manifest itself so long as you avoid using {@link Map} in your models. 215 * <p> 216 * The other notable difference is JStachio does not like missing variables (a compiler 217 * error will happen) where as many Mustache implementations sometimes allow this and will 218 * just not output anything. 219 * 220 * <em> n.b. This doc and various other docs often appears to use the term "variable" and 221 * "binding" interchangeable. "variable" however is generally a subset of "binding" and is 222 * the leaf nodes of the model tree that are to be outputted like String 223 * interpolation.</em> In mustache spec parlance it is the last key (all the way to the 224 * right) of a dotted name. Also in some cases this doc calls dotted names "path". 225 * 226 * 227 * <h4 id="_context_java_types">Interpretation of Java-types and values</h4> When some 228 * value is null nothing is rendered if it is used as a section. If some value is null and 229 * it is used as a variable a null pointer exception will be thrown by default. This is 230 * configurable via {@link JStacheFormatterTypes} and custom {@link JStacheFormatter}. 231 * <p> 232 * Boxed and unboxed <code>boolean</code> can be used for mustache-sections. Section is 233 * only rendered if value is true. 234 * <p> 235 * {@link Optional} empty is treated like an empty list or a boolean false. Optional 236 * values are always assumed to be non null. 237 * <p> 238 * {@code Map<String,?>} follow different nesting rules than other types. If you are in a 239 * {@link Map} nested section the rest of the context is checked before the 240 * <code>Map</code>. Once that is done the Map is then checked using 241 * {@link Map#get(Object)}' where the key is the <em>last part of the dotted name</em>. 242 * <p> 243 * Data-binding contexts are nested. Names are looked up in innermost context first. If 244 * name is not found in current context, parent context is inspected. This process 245 * continues up to root context. 246 * 247 * In each rendering context name lookup is performed as follows: 248 * 249 * <ol> 250 * <li>Method with requested name is looked up. Method should have no arguments and should 251 * throw no checked exceptions. If there is such method it is used to fetch actual data to 252 * render. Compile-time error is raised if there is method with given name, but it is not 253 * accessible, has parameters or throws checked exceptions.</li> 254 * <li>Method with requested name and annotated correctly with {@link JStacheLambda} and 255 * the lookup is for a section than the method lambda method will be used.</li> 256 * <li>Method with getter-name for requested name is looked up. (For example, if 'age' is 257 * requested, 'getAge' method is looked up.) Method should have no arguments and should 258 * throw no checked exceptions. If there is such method it is used to fetch actual data to 259 * render. Compile-time error is raised if there is method with such name, but it is not 260 * accessible, has parameters or throws checked exceptions</li> 261 * 262 * <li>Field with requested name is looked up. Compile-time error is raised if there is 263 * field with such name but it's not accessible.</li> 264 * </ol> 265 * 266 * <h4 id="_enums">Enum Matching Extension</h4> Basically enums have boolean keys that are 267 * the enums name ({@code Enum.name()}) that can be used as conditional sections. Assume 268 * {@code light} is an enum like: 269 * 270 * <pre> 271 * <code class="language-java"> 272 * public enum Light { 273 * RED, 274 * GREEN, 275 * YELLOW 276 * } 277 * </code> </pre> 278 * 279 * You can conditinally select on the enum like a pattern match: 280 * 281 * <pre> 282 * <code class="language-hbs"> 283 * {{#light.RED}} 284 * STOP 285 * {{/light.RED}} 286 * {{#light.GREEN}} 287 * GO 288 * {{/light.GREEN}} 289 * {{#light.YELLOW}} 290 * Proceeed with caution 291 * {{/light.YELLOW}} 292 * </code> </pre> 293 * 294 * <h4 id="_index_support">Index Extension</h4> 295 * 296 * JStachio is compatible with both handlebars.js (handlebars.java as well) and JMustache 297 * index keys for iterable sections. 298 * <ol> 299 * <li><code>-first</code> and <code>@first</code> is boolean that is true when you 300 * are on the first item 301 * <li><code>-last</code> and <code>@last</code> is a boolean that is true when you 302 * are on the last item in the iterable 303 * <li><code>-index</code> is a one based index. The first item would be {@code 1} and not 304 * {@code 0} 305 * <li><code>@index</code> is zero based index (handlebars). The first item would be 306 * {@code 0}. 307 * </ol> 308 * 309 * <h3 id="_lambdas">Lambda Support</h3> 310 * 311 * <strong>@{@link JStacheLambda}</strong> 312 * <p> 313 * JStachio supports lambda section calls in a similar manner to 314 * <a href="https://github.com/samskivert/jmustache">JMustache</a>. Just tag your methods 315 * with {@link JStacheLambda} and the returned models will be used to render the contents 316 * of the lambda section. The top of the context stack can be passed to the lambda. 317 * 318 * 319 * <h2 id="_code_generation">Code Generation</h2> 320 * 321 * <strong>@{@link io.jstach.jstache.JStacheConfig#type()}</strong> 322 * <p> 323 * JStachio by default reads mustache syntax and generates code that needs the jstachio 324 * runtime (io.jstache.jstachio). However it is possible to generate code that does not 325 * need the runtime and possibly in the future other syntaxs like Handlebars might be 326 * supported. 327 * 328 * <h3 id="_methods_generated">Generated Renderer Classes</h3> JStachio generates a single 329 * class from a mustache template and model (class annotated with JStache) pair. The 330 * generated classes are generally called "Renderers" or sometimes "Templates". Depending 331 * on which JStache type is picked different methods are generated. The guaranteed 332 * generated methods <em>not to change on minor version or less</em> on the renderer 333 * classes are discussed in <strong>{@link JStacheType}</strong>. 334 * 335 * <h3 id="_zero_dep">Zero dependency code generation</h3> 336 * 337 * <strong>@{@link io.jstach.jstache.JStacheConfig#type()} == 338 * {@link JStacheType#STACHE}</strong> 339 * <p> 340 * Zero dependency code generation is useful if you want to avoid coupling your runtime 341 * and downstream dependencies with JStachio (including the annotations themselves) as 342 * well as minimize the overall footprint and or classes loaded. A common use case would 343 * be using jstachio for code generation in an annotation processing library where you 344 * want as minimal class path issues as possible. 345 * <p> 346 * If this configuration is selected generated code will <strong>ONLY have references to 347 * stock base JDK module ({@link java.base/}) classes</strong>. However one major caveat 348 * is that generated classes will not be reflectively accessible to the JStachio runtime 349 * and thus fallback and filtering will not work. Thus in a web framework environment this 350 * configuration choice is less desirable. 351 * <p> 352 * <em>n.b. as long as the jstachio annotations are not accessed reflectively you do not 353 * need the annotation jar in the classpath during runtime thus the annotations jar is 354 * effectively an optional compile time dependency.</em> 355 * 356 * 357 * <h2 id="_formatting">Formatting variables</h2> 358 * 359 * JStachio has strict control on what happens when you output a variable (a binding that 360 * is not an iterable) like <code>{{variable}}</code> or <code>{{{variable}}}</code>. 361 * 362 * <h3 id="_allowed_types">Allowed formatting types</h3> <strong> 363 * @{@link io.jstach.jstache.JStacheFormatterTypes}</strong> 364 * <p> 365 * Only a certain set of types are allowed to be formatted and if they are not a compiler 366 * error will happen (as in the annotation processor will fail). To understand more about 367 * that see {@link io.jstach.jstache.JStacheFormatterTypes}. 368 * 369 * <h3 id="_runtime_formatting">Runtime formatting</h3> 370 * <strong>@{@link io.jstach.jstache.JStacheFormatter} and 371 * @{@link JStacheConfig#formatter()}</strong> 372 * <p> 373 * Assuming the compiler allowed the variable to be formatted you can control the output 374 * via {@link io.jstach.jstache.JStacheFormatter} and setting 375 * {@link io.jstach.jstache.JStacheConfig#formatter()}. 376 * <p> 377 * If you are using the JStachio runtime (io.jstach.jstachio) and have 378 * {@link JStacheConfig#type()} set to {@link JStacheType#JSTACHIO} (or UNSPECIFIED aka 379 * default) the default formatter will be used (see <code class= 380 * "externalLink">io.jstach.jstachio.formatters.DefaultFormatter</code>). The default 381 * formatter is slightly different than the mustache spec in that it does not allow 382 * formatting nulls. If you would like to follow the spec rules where <code>null</code> 383 * should be an empty string use <code class= 384 * "externalLink">io.jstach.jstachio.formatters.SpecFormatter</code>. 385 * 386 * <h2 id="_escaping">Escaping and Content Type</h2> 387 * <strong>@{@link io.jstach.jstache.JStacheContentType}, and 388 * @{@link JStacheConfig#contentType()} </strong> 389 * <p> 390 * If you are using the JStachio runtime (io.jstach.jstachio) and have 391 * {@link JStacheConfig#type()} set to {@link JStacheType#JSTACHIO} (or UNSPECIFIED aka 392 * default) you will get out of the box escaping for HTML (see 393 * <code class="externalLink">io.jstach.jstachio.escapers.Html</code>) per the mustache 394 * spec. 395 * <p> 396 * <strong>To disable escaping</strong> set {@link JStacheConfig#contentType()} to 397 * <code class="externalLink">io.jstach.jstachio.escapers.PlainText</code>. 398 * 399 * <h2 id="_config">Configuration</h2> <strong>@{@link JStacheConfig}</strong> 400 * <p> 401 * You can set global configuration on class, packages and module elements. See 402 * {@link JStacheConfig} for more details on config resolution. Some configuration is set 403 * through compiler flags and annotation processor options. However {@link JStacheConfig} 404 * unlike compiler flags and annotation processor options are available during runtime 405 * through reflective access. 406 * 407 * <h3 id="_config_flags">Compiler flags</h3> 408 * 409 * The compiler has some boolean flags that can be set statically via {@link JStacheFlags} 410 * as well as through annotation processor options. 411 * 412 * <h3 id="_config_compiler">Annotation processor options</h3> 413 * 414 * Some configuration is available as an annotation processor option. Current available 415 * options are: 416 * 417 * <ul> 418 * <li>{@link #RESOURCES_PATH_OPTION}</li> 419 * </ul> 420 * 421 * The previously mentioned {@linkplain JStacheFlags compiler flags} are also available as 422 * annotation options. The flags are prefixed with "<code>jstache.</code>". For example 423 * {@link JStacheFlags.Flag#DEBUG} would be: 424 * <p> 425 * <code>jstache.debug=true/false</code>. 426 * 427 * <h4 id="_config_compiler_maven">Configuring options with Maven</h4> 428 * 429 * Example configuration with Maven: 430 * 431 * <pre class="language-xml">{@code 432 * <plugin> 433 * <groupId>org.apache.maven.plugins</groupId> 434 * <artifactId>maven-compiler-plugin</artifactId> 435 * <version>3.8.1</version> 436 * <configuration> 437 * <source>17</source> 438 * <target>17</target> 439 * <annotationProcessorPaths> 440 * <path> 441 * <groupId>io.jstach</groupId> 442 * <artifactId>jstachio-apt</artifactId> 443 * <version>${io.jstache.version}</version> 444 * </path> 445 * </annotationProcessorPaths> 446 * <compilerArgs> 447 * <arg> 448 * -Ajstache.resourcesPath=src/main/resources 449 * </arg> 450 * <arg> 451 * -Ajstache.debug=false 452 * </arg> 453 * </compilerArgs> 454 * </configuration> 455 * </plugin> 456 * }</pre> 457 * 458 * <h4 id="_config_compiler_gradle">Configuring options with Gradle</h4> 459 * 460 * Example configuration with Gradle: 461 * 462 * <pre> 463 * <code class="language-kotlin"> 464 * compileJava { 465 * options.compilerArgs += [ 466 * '-Ajstache.resourcesPath=src/main/resources' 467 * ] 468 * } 469 * </code> </pre> 470 * 471 * 472 * </div> 473 * 474 * @author agentgt 475 * @see JStachePath 476 * @see JStacheFormatterTypes 477 * @see JStacheConfig 478 * @see JStacheFormatter 479 * @see JStacheContentType 480 * @see JStacheConfig 481 * 482 * @jstachioVersion 483 */ 484@Retention(RetentionPolicy.RUNTIME) 485@Target(ElementType.TYPE) 486@Documented 487public @interface JStache { 488 489 /** 490 * Resource path to template 491 * @return Path to mustache template 492 * @see JStachePath 493 */ 494 String path() default ""; 495 496 /** 497 * Inline the template as a Java string instead of a file. Use the new triple quote 498 * string literal for complex templates. 499 * @return An inline template 500 */ 501 String template() default ""; 502 503 /** 504 * Name of generated class. 505 * <p> 506 * name can be omitted. <code>model.getClass().getName()</code> + 507 * {@link JStacheName#DEFAULT_SUFFIX} name is used by default. 508 * @return Name of generated class 509 */ 510 String name() default ""; 511 512 /** 513 * An annotation processor compiler flag 514 * (<strong>{@value #RESOURCES_PATH_OPTION}</strong>) that says where the templates 515 * files are located. 516 * <p> 517 * When the annotation processor runs these files usually are in: 518 * <code>javax.tools.StandardLocation#CLASS_OUTPUT</code> and in a Maven or Gradle 519 * project they normally would reside in <code>src/main/resources</code> or 520 * <code>src/test/resources</code> which get copied on build to 521 * <code>target/classes</code> or similar. However due to incremental compiling 522 * template files are not always copied to <code>target/classes</code> and thus are 523 * not found by the annotation processor. To deal with this issue JStachio during 524 * compilation fallsback to direct filesystem access of the <em>source</em> directory 525 * instead of the output (<code>javax.tools.StandardLocation#CLASS_OUTPUT</code>) if 526 * the files cannot be found. 527 * <p> 528 * If the path does not start with a path separator then it will be appended to the 529 * the current working directory otherwise it is assumed to be a fully qualified path. 530 * <p> 531 * The default location is <code>CWD/src/main/resources</code> where CWD is the 532 * current working directory. 533 * 534 * <strong>If the option is blank or empty then NO fallback will happen and 535 * effectively disables the above behavior. </strong> 536 * 537 * You can change it by passing to the annotation processor a setting for 538 * <strong>{@value #RESOURCES_PATH_OPTION}</strong> like: 539 * <pre><code>jstache.resourcesPath=some/path</code></pre> 540 * 541 * For build annotation processor configuration examples see: 542 * <ol> 543 * <li><a href="#_config_compiler_maven">Configuring options with Maven</a></li> 544 * <li><a href="#_config_compiler_gradle">Configuring options with Gradle</a></li> 545 * </ol> 546 * 547 */ 548 public static final String RESOURCES_PATH_OPTION = "jstache.resourcesPath"; 549 550}