diff --git a/htmlflow-core/src/main/java/htmlflow/HtmlFlow.java b/htmlflow-core/src/main/java/htmlflow/HtmlFlow.java index 57130729..7af0119d 100644 --- a/htmlflow-core/src/main/java/htmlflow/HtmlFlow.java +++ b/htmlflow-core/src/main/java/htmlflow/HtmlFlow.java @@ -24,6 +24,7 @@ */ package htmlflow; +import htmlflow.continuations.HtmlResolver; import htmlflow.visitor.HtmlDocVisitor; import htmlflow.visitor.HtmlViewVisitor; import htmlflow.visitor.HtmlViewVisitorAsync; @@ -49,8 +50,9 @@ private HtmlFlow() {} * @param template An HtmlTemplate function, which depends on an HtmlView used to create HTMl * elements. * @param isIndented Set indentation on or off. + * @return The compiled chain, or the linked chain when it does not compile. */ - private static PreprocessingVisitor preprocessing( + private static HtmlResolver preprocessing( HtmlTemplate template, boolean isIndented ) { @@ -69,7 +71,7 @@ private static PreprocessingVisitor preprocessing( * accumulated in the internal StringBuffer out. */ preView.getVisitor().resolve(null); - return pre; + return pre.compile(); } /** @@ -77,11 +79,9 @@ private static PreprocessingVisitor preprocessing( * MFE configurations and processes them to enable MFE support in the view. * * @param template An HtmlTemplate function that defines the HTML structure with MFE components - * @return A PreprocessingVisitorMfe containing the processed MFE components + * @return The compiled chain, or the linked chain when it does not compile. */ - private static PreprocessingVisitorMfe preprocessingMfe( - HtmlTemplate template - ) { + private static HtmlResolver preprocessingMfe(HtmlTemplate template) { PreprocessingVisitorMfe processView = new PreprocessingVisitorMfe( false ); @@ -94,7 +94,7 @@ private static PreprocessingVisitorMfe preprocessingMfe( template.resolve(preView); // second process preView.getVisitor().resolve(null); - return processView; + return processView.compile(); } /** @@ -186,22 +186,12 @@ static HtmlView view( boolean preEncoding, boolean mfeEnabled ) { - if (preEncoding && mfeEnabled) { - PreprocessingVisitorMfe processView = preprocessingMfe(template); - return new HtmlView<>( - () -> - new HtmlViewVisitor( - out, - isIndented, - processView.getFirst() - ), - template, - threadSafe - ); - } else if (preEncoding) { - PreprocessingVisitor pre = preprocessing(template, isIndented); + if (preEncoding) { + HtmlResolver resolver = mfeEnabled + ? preprocessingMfe(template) + : preprocessing(template, isIndented); return new HtmlView<>( - (() -> new HtmlViewVisitor(out, isIndented, pre.getFirst())), + () -> new HtmlViewVisitor(out, isIndented, resolver), template, threadSafe ); @@ -260,32 +250,20 @@ static HtmlView view( boolean preEncoding, boolean mfeEnabled ) { - if (preEncoding && mfeEnabled) { - PreprocessingVisitorMfe processView = preprocessingMfe(template); + if (preEncoding) { + HtmlResolver resolver = mfeEnabled + ? preprocessingMfe(template) + : preprocessing(template, isIndented); return new HtmlView<>( () -> new HtmlViewVisitor( new StringBuilder(), isIndented, - processView.getFirst() + resolver ), template, threadSafe ); - } else if (preEncoding) { - PreprocessingVisitor pre = preprocessing(template, isIndented); - return new HtmlView<>( - ( - () -> - new HtmlViewVisitor( - new StringBuilder(), - isIndented, - pre.getFirst() - ) - ), - template, - threadSafe - ); } else { return new HtmlViewHot<>( () -> new HtmlViewVisitorHot(new StringBuilder(), isIndented), diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuation.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuation.java index 799175fc..7d3e9116 100644 --- a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuation.java +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuation.java @@ -34,7 +34,7 @@ * Base class for a linked list of nodes, corresponding to HtmlContinuation objects. * HtmlContinuation is responsible for emitting an HTML block and call the next node. */ -public abstract class HtmlContinuation { +public abstract class HtmlContinuation implements HtmlResolver { /** A negative number means that should be ignored. */ final int currentDepth; @@ -74,17 +74,19 @@ public HtmlContinuation getNext() { } /** - * Executes this continuation and calls the next one if exist. + * Emits this block and calls the next continuation if it exists. * * @param model */ - public abstract void execute(Object model); + @Override + public abstract void resolve(Object model); /** * Creates a copy of this HtmlContinuation with a new visitor * * @param visitor */ + @Override public abstract HtmlContinuation copy(HtmlVisitor visitor); @SuppressWarnings("squid:S3011") diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsync.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsync.java index fdb6d02e..3a6b6521 100644 --- a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsync.java +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsync.java @@ -31,7 +31,7 @@ public HtmlContinuationAsync( } @Override - public final void execute(Object model) { + public final void resolve(Object model) { if (currentDepth >= 0) { this.visitor.setIsClosed(isClosed); this.visitor.setDepth(currentDepth); @@ -41,7 +41,7 @@ public final void execute(Object model) { (T) model, () -> { if (next != null) { - next.execute(model); + next.resolve(model); } } ); diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsyncTerminationNode.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsyncTerminationNode.java index 5500361e..b991c7a1 100644 --- a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsyncTerminationNode.java +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationAsyncTerminationNode.java @@ -15,7 +15,7 @@ public HtmlContinuationAsyncTerminationNode(CompletableFuture cf) { this.cf = cf; } - public void execute(Object model) { + public void resolve(Object model) { cf.complete(null); } diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSync.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSync.java index c2869b49..35e51d92 100644 --- a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSync.java +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSync.java @@ -25,14 +25,14 @@ protected HtmlContinuationSync( * @param model */ @Override - public final void execute(Object model) { + public final void resolve(Object model) { if (currentDepth >= 0) { this.visitor.setIsClosed(isClosed); this.visitor.setDepth(currentDepth); } emitHtml(model); if (next != null) { - next.execute(model); + next.resolve(model); } } diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncForEach.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncForEach.java new file mode 100644 index 00000000..1841136c --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncForEach.java @@ -0,0 +1,68 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package htmlflow.continuations; + +import htmlflow.visitor.HtmlVisitor; +import java.util.function.Function; + +/** + * HtmlContinuation for a loop body that runs once per item. The body carries its own leading + * indentation. + * + * @author Bernardo Pereira + */ +public class HtmlContinuationSyncForEach extends HtmlContinuationSync { + + private final Function> items; + + private final HtmlResolver item; + + public HtmlContinuationSyncForEach( + Function> items, + HtmlResolver item, + HtmlVisitor visitor, + HtmlContinuation next + ) { + super(-1, false, visitor, next); + this.items = items; + this.item = item; + } + + @SuppressWarnings("unchecked") + @Override + protected final void emitHtml(Object model) { + for (E e : items.apply((M) model)) item.resolve(e); + } + + @Override + public HtmlContinuation copy(HtmlVisitor v) { + return new HtmlContinuationSyncForEach<>( + items, + item.copy(v), + v, + next != null ? next.copy(v) : null + ); + } +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncValue.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncValue.java new file mode 100644 index 00000000..033d9609 --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncValue.java @@ -0,0 +1,216 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package htmlflow.continuations; + +import htmlflow.exceptions.HtmlFlowAppendException; +import htmlflow.visitor.HtmlVisitor; +import htmlflow.visitor.Tags; +import htmlflow.visitor.escape.HtmlEscapers; +import java.io.IOException; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; + +/** + * HtmlContinuation for a single value read from the model. The markup around the value lives in + * the preencoded static blocks on either side. + * + * @author Bernardo Pereira + */ +public class HtmlContinuationSyncValue extends HtmlContinuationSync { + + public enum Kind { + /** Written as is. */ + RAW, + /** HTML escaped. */ + TEXT, + INT, + LONG, + DOUBLE, + BOOLEAN, + /** An attribute we skip when the accessor returns null. */ + ATTR_NULLABLE, + } + + private final Kind kind; + private final Object accessor; + + /** Only set for ATTR_NULLABLE. */ + private final String attributeName; + + /** + * Sets indentation to -1 to inform that visitor should continue with previous indentation. + * A value slot changes neither the depth nor the isClosed of the visitor. + */ + public HtmlContinuationSyncValue( + Kind kind, + Object accessor, + String attributeName, + HtmlVisitor visitor, + HtmlContinuation next + ) { + super(-1, false, visitor, next); + this.kind = kind; + this.accessor = accessor; + this.attributeName = attributeName; + } + + public Kind kind() { + return kind; + } + + public Object accessor() { + return accessor; + } + + public String attributeName() { + return attributeName; + } + + /** + * @apiNote The generated bytecode calls this by name. Renaming it makes compiled chains fall + * back to the linked chain. + */ + public static String text(Object value) { + return HtmlEscapers.htmlEscaper().escape(String.valueOf(value)); + } + + /** + * Appends a value. A StringBuilder takes numbers without a String copy, which matters on + * pages with many numbers. + * + * @apiNote The generated bytecode calls the append methods by name, same as {@link #text}. + */ + public static void append(Appendable out, int value) throws IOException { + if (out instanceof StringBuilder) { + ((StringBuilder) out).append(value); + } else { + out.append(Integer.toString(value)); + } + } + + public static void append(Appendable out, long value) throws IOException { + if (out instanceof StringBuilder) { + ((StringBuilder) out).append(value); + } else { + out.append(Long.toString(value)); + } + } + + public static void append(Appendable out, double value) throws IOException { + if (out instanceof StringBuilder) { + ((StringBuilder) out).append(value); + } else { + out.append(Double.toString(value)); + } + } + + public static void append(Appendable out, boolean value) + throws IOException { + out.append(Boolean.toString(value)); + } + + /** Appends String.valueOf(value), so null prints as "null". */ + public static void append(Appendable out, Object value) throws IOException { + out.append(String.valueOf(value)); + } + + /** @apiNote The generated bytecode calls this by name, same as {@link #text}. */ + public static void attrNullable(Appendable out, String name, Object value) { + if (value != null) Tags.addAttribute(out, name, String.valueOf(value)); + } + + /** Reads a value slot and appends it. The hot reload visitor shares this with the chain. */ + @SuppressWarnings("unchecked") + public static void appendValue( + Appendable out, + Kind kind, + Object accessor, + Object model + ) { + try { + switch (kind) { + case INT: + append( + out, + ((ToIntFunction) accessor).applyAsInt(model) + ); + break; + case LONG: + append( + out, + ((ToLongFunction) accessor).applyAsLong(model) + ); + break; + case DOUBLE: + append( + out, + ((ToDoubleFunction) accessor).applyAsDouble( + model + ) + ); + break; + case BOOLEAN: + append(out, ((Predicate) accessor).test(model)); + break; + case TEXT: + out.append( + text(((Function) accessor).apply(model)) + ); + break; + default: + append(out, ((Function) accessor).apply(model)); + } + } catch (IOException e) { + throw new HtmlFlowAppendException(e); + } + } + + @SuppressWarnings("unchecked") + @Override + protected final void emitHtml(Object model) { + if (kind == Kind.ATTR_NULLABLE) { + attrNullable( + visitor.out(), + attributeName, + ((Function) accessor).apply(model) + ); + } else { + appendValue(visitor.out(), kind, accessor, model); + } + } + + @Override + public HtmlContinuation copy(HtmlVisitor v) { + return new HtmlContinuationSyncValue( + kind, + accessor, + attributeName, + v, + next != null ? next.copy(v) : null + ); + } +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncWhen.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncWhen.java new file mode 100644 index 00000000..50a75aaf --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlContinuationSyncWhen.java @@ -0,0 +1,77 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package htmlflow.continuations; + +import htmlflow.visitor.HtmlVisitor; +import java.util.function.Predicate; + +/** + * HtmlContinuation for a conditional that writes one of two preencoded blocks. orElse is null + * when the template has none. + * + * @author Bernardo Pereira + */ +public class HtmlContinuationSyncWhen extends HtmlContinuationSync { + + private final Predicate condition; + + private final HtmlResolver body; + + private final HtmlResolver orElse; + + public HtmlContinuationSyncWhen( + Predicate condition, + HtmlResolver body, + HtmlResolver orElse, + HtmlVisitor visitor, + HtmlContinuation next + ) { + super(-1, false, visitor, next); + this.condition = condition; + this.body = body; + this.orElse = orElse; + } + + @SuppressWarnings("unchecked") + @Override + protected final void emitHtml(Object model) { + if (condition.test((M) model)) { + body.resolve(model); + } else if (orElse != null) { + orElse.resolve(model); + } + } + + @Override + public HtmlContinuation copy(HtmlVisitor v) { + return new HtmlContinuationSyncWhen<>( + condition, + body.copy(v), + orElse == null ? null : orElse.copy(v), + v, + next != null ? next.copy(v) : null + ); + } +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolver.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolver.java new file mode 100644 index 00000000..0af6652c --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolver.java @@ -0,0 +1,38 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package htmlflow.continuations; + +import htmlflow.visitor.HtmlVisitor; + +/** + * Emits the HTML of a preprocessed template, either by walking a chain of continuations or + * through a compiled chain. + */ +public interface HtmlResolver { + /** Emits the HTML for the given model. */ + void resolve(Object model); + + /** Returns a resolver that writes through the given visitor. */ + HtmlResolver copy(HtmlVisitor visitor); +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolverCompiled.java b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolverCompiled.java new file mode 100644 index 00000000..44f905e2 --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/HtmlResolverCompiled.java @@ -0,0 +1,64 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package htmlflow.continuations; + +import htmlflow.exceptions.HtmlFlowAppendException; +import htmlflow.visitor.HtmlVisitor; +import java.io.IOException; + +/** + * Base class of the classes that {@link htmlflow.continuations.codegen.ChainCompiler} generates + * for a chain of static blocks and value slots. The generated class implements {@link #write}, + * and like a continuation it writes to the output of its visitor. + */ +public abstract class HtmlResolverCompiled implements HtmlResolver, Cloneable { + + private HtmlVisitor visitor; + + protected HtmlResolverCompiled() {} + + @Override + public final void resolve(Object model) { + try { + write(visitor.out(), model); + } catch (IOException e) { + throw new HtmlFlowAppendException(e); + } + } + + /** Shares the accessors with this resolver and writes through the given visitor. */ + @Override + public final HtmlResolver copy(HtmlVisitor visitor) { + try { + HtmlResolverCompiled copy = (HtmlResolverCompiled) clone(); + copy.visitor = visitor; + return copy; + } catch (CloneNotSupportedException e) { + throw new IllegalStateException(e); // unreachable, this class is Cloneable + } + } + + protected abstract void write(Appendable out, Object model) + throws IOException; +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ChainCompiler.java b/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ChainCompiler.java new file mode 100644 index 00000000..9fc89d0e --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ChainCompiler.java @@ -0,0 +1,432 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package htmlflow.continuations.codegen; + +import htmlflow.continuations.HtmlContinuation; +import htmlflow.continuations.HtmlContinuationSyncStatic; +import htmlflow.continuations.HtmlContinuationSyncValue; +import htmlflow.continuations.HtmlContinuationSyncValue.Kind; +import htmlflow.continuations.HtmlResolver; +import htmlflow.continuations.HtmlResolverCompiled; +import java.io.IOException; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; +import java.lang.invoke.MethodType; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; + +/** + * Generates one {@link HtmlResolverCompiled} class for each chain of static blocks and value slots. + * Every accessor gets its own field and its own call site. + * + *

The write method appends straight to the output Appendable. Numbers go through the + * HtmlContinuationSyncValue.append helpers, so a StringBuilder takes them without a String copy. + * Nothing is buffered. + * + *

The method never branches, so it needs no StackMapTable, and the stack and local counts are + * constant. We write the class file directly, so this needs no bytecode library. + * + *

When something goes wrong, {@link #compile} returns the linked chain itself. A mistake here + * costs performance, not correctness. + * + * @author Bernardo Pereira + */ +public final class ChainCompiler { + + private static final Lookup LOOKUP = MethodHandles.lookup(); + + /** Hidden classes land in the lookup's package, so the name must too. */ + private static final String GEN = + "htmlflow/continuations/codegen/ChainResolverGen"; + + private static final String RESOLVER_COMPILED = internal( + HtmlResolverCompiled.class + ); + private static final String VALUE_SLOT = internal( + HtmlContinuationSyncValue.class + ); + private static final String APPENDABLE = internal(Appendable.class); + private static final String STRING_DESC = String.class.descriptorString(); + private static final String CHAR_SEQUENCE_DESC = + CharSequence.class.descriptorString(); + private static final String OBJECT_DESC = Object.class.descriptorString(); + private static final String TAKES_OBJECT = method(OBJECT_DESC, ""); + + /** Called by name from the generated code. See {@link #helpersFound}. */ + private static final String TEXT = "text"; + private static final String ATTR_NULLABLE = "attrNullable"; + private static final String APPEND = "append"; + + /** False when a helper is missing, so every chain stays linked. */ + private static final boolean HELPERS_FOUND = helpersFound(); + + private static final int HUGE_METHOD_LIMIT = 8000; + + /* The local variables of the generated methods. */ + private static final int THIS = 0; + private static final int ACCESSORS_ARG = 1; + private static final int OUT_LOCAL = 1; + private static final int MODEL_LOCAL = 2; + + /* These are constant because the generated code has no branches. */ + private static final int INIT_MAX_STACK = 4; + private static final int INIT_MAX_LOCALS = 2; + private static final int WRITE_MAX_STACK = 6; + private static final int WRITE_MAX_LOCALS = 3; + + private ChainCompiler() {} + + /** + * @return A compiled resolver for the chain starting in first, or first itself when the chain + * holds other nodes than static blocks and value slots, when it is too large, or when the + * definition of the class failed. + */ + public static HtmlResolver compile(HtmlContinuation first) { + Slots slots = Slots.of(first); + if (slots == null || !HELPERS_FOUND) return first; + try { + byte[] classFile = classFile(slots); + if (classFile == null) return first; + Class gen = LOOKUP + .defineHiddenClass(classFile, true) + .lookupClass(); + MethodHandle constructor = LOOKUP.findConstructor( + gen, + MethodType.methodType(void.class, Object[].class) + ); + return (HtmlResolver) constructor.invoke(slots.accessors); + } catch (Throwable failed) { + return first; + } + } + + /** + * Looks up the helpers the generated code calls by name. The JVM links invokestatic lazily, + * so a wrong name would pass verification and only throw NoSuchMethodError on first render. + */ + private static boolean helpersFound() { + try { + HtmlContinuationSyncValue.class.getDeclaredMethod( + TEXT, + Object.class + ); + for (Class value : new Class[] { + int.class, + long.class, + double.class, + boolean.class, + Object.class, + }) { + HtmlContinuationSyncValue.class.getDeclaredMethod( + APPEND, + Appendable.class, + value + ); + } + HtmlContinuationSyncValue.class.getDeclaredMethod( + ATTR_NULLABLE, + Appendable.class, + String.class, + Object.class + ); + return true; + } catch (NoSuchMethodException missing) { + return false; + } + } + + private static byte[] classFile(Slots slots) throws IOException { + Kind[] kinds = slots.kinds; + ClassFile gen = new ClassFile(GEN, RESOLVER_COMPILED); + for (int i = 0; i < kinds.length; i++) { + gen.field("a" + i, desc(accessorFor(kinds[i]).type)); + } + ClassFile.ConstantPool pool = gen.pool(); + gen.method( + "", + method(Object[].class.descriptorString(), "V"), + INIT_MAX_STACK, + INIT_MAX_LOCALS, + constructorCode(pool, slots) + ); + ClassFile.Bytecode write = writeCode(pool, slots); + if (write.size() >= HUGE_METHOD_LIMIT) return null; + gen.method( + "write", + method(desc(APPENDABLE) + OBJECT_DESC, "V"), + WRITE_MAX_STACK, + WRITE_MAX_LOCALS, + write + ); + return gen.toBytes(); + } + + /** Generates the constructor, which casts each array element into its own field. */ + private static ClassFile.Bytecode constructorCode( + ClassFile.ConstantPool pool, + Slots slots + ) throws IOException { + Kind[] kinds = slots.kinds; + ClassFile.Bytecode code = new ClassFile.Bytecode(); + code.aload(THIS); + code.invokeSpecial(pool.method(RESOLVER_COMPILED, "", "()V")); + for (int i = 0; i < kinds.length; i++) { + String type = accessorFor(kinds[i]).type; + code.aload(THIS); + code.aload(ACCESSORS_ARG); + code.pushInt(i); + code.arrayLoad(); + code.checkCast(pool.clazz(type)); + code.putField(pool.field(GEN, "a" + i, desc(type))); + } + code.returnVoid(); + return code; + } + + private static ClassFile.Bytecode writeCode( + ClassFile.ConstantPool pool, + Slots slots + ) throws IOException { + String[] statics = slots.statics; + Kind[] kinds = slots.kinds; + String[] attrNames = slots.attrNames; + ClassFile.Bytecode code = new ClassFile.Bytecode(); + for (int i = 0; i < kinds.length; i++) { + emitStatic(code, pool, statics[i]); + emitSlot(code, pool, i, kinds[i], attrNames[i]); + } + emitStatic(code, pool, statics[kinds.length]); + code.returnVoid(); + return code; + } + + /** Generates the append of a constant String. */ + private static void emitStatic( + ClassFile.Bytecode code, + ClassFile.ConstantPool pool, + String text + ) throws IOException { + if (text.isEmpty()) return; + code.aload(OUT_LOCAL); + code.ldc(pool.string(text)); + appendAndPop(code, pool); + } + + private static void emitSlot( + ClassFile.Bytecode code, + ClassFile.ConstantPool pool, + int i, + Kind kind, + String attrName + ) throws IOException { + if (kind == Kind.ATTR_NULLABLE) { + emitNullableAttribute(code, pool, i, attrName); + return; + } + code.aload(OUT_LOCAL); + if (kind == Kind.TEXT) { + callAccessor(code, pool, i, Accessor.OBJECT); + code.invokeStatic( + pool.method(VALUE_SLOT, TEXT, TAKES_OBJECT + STRING_DESC) + ); + appendAndPop(code, pool); + } else { + Accessor accessor = accessorFor(kind); + callAccessor(code, pool, i, accessor); + code.invokeStatic( + pool.method( + VALUE_SLOT, + APPEND, + method(desc(APPENDABLE) + accessor.returns, "V") + ) + ); + } + } + + /** The interface, method and return descriptor for each accessor, kept together so they match. */ + private enum Accessor { + INT(ToIntFunction.class, "applyAsInt", "I"), + LONG(ToLongFunction.class, "applyAsLong", "J"), + DOUBLE(ToDoubleFunction.class, "applyAsDouble", "D"), + BOOLEAN(Predicate.class, "test", "Z"), + OBJECT(Function.class, "apply", OBJECT_DESC); + + private final String type; + private final String method; + private final String returns; + + Accessor(Class type, String method, String returns) { + this.type = internal(type); + this.method = method; + this.returns = returns; + } + } + + private static Accessor accessorFor(Kind kind) { + switch (kind) { + case INT: + return Accessor.INT; + case LONG: + return Accessor.LONG; + case DOUBLE: + return Accessor.DOUBLE; + case BOOLEAN: + return Accessor.BOOLEAN; + default: + return Accessor.OBJECT; + } + } + + /** Generates the call to attrNullable, which skips a null attribute. */ + private static void emitNullableAttribute( + ClassFile.Bytecode code, + ClassFile.ConstantPool pool, + int i, + String attrName + ) throws IOException { + code.aload(OUT_LOCAL); + code.ldc(pool.string(attrName)); + callAccessor(code, pool, i, Accessor.OBJECT); + code.invokeStatic( + pool.method( + VALUE_SLOT, + ATTR_NULLABLE, + method(desc(APPENDABLE) + STRING_DESC + OBJECT_DESC, "V") + ) + ); + } + + /** Generates the accessor call. Each slot gets its own call site. */ + private static void callAccessor( + ClassFile.Bytecode code, + ClassFile.ConstantPool pool, + int i, + Accessor accessor + ) throws IOException { + code.aload(THIS); + code.getField(pool.field(GEN, "a" + i, desc(accessor.type))); + code.aload(MODEL_LOCAL); + code.invokeInterface( + pool.interfaceMethod( + accessor.type, + accessor.method, + TAKES_OBJECT + accessor.returns + ) + ); + } + + /** Appends the String on the stack to the output and drops the returned Appendable. */ + private static void appendAndPop( + ClassFile.Bytecode code, + ClassFile.ConstantPool pool + ) throws IOException { + code.invokeInterface( + pool.interfaceMethod( + APPENDABLE, + "append", + method(CHAR_SEQUENCE_DESC, desc(APPENDABLE)) + ) + ); + code.pop(); + } + + private static String desc(String internalName) { + return 'L' + internalName + ';'; + } + + /** Converts a name such as java.lang.String into java/lang/String. */ + private static String internal(Class type) { + return type.getName().replace('.', '/'); + } + + private static String method(String params, String returns) { + return '(' + params + ')' + returns; + } + + /** The chain as parallel arrays. Runs of static nodes merge into one append. */ + private static final class Slots { + + /** The text before slot i. The last entry holds the text after the last slot. */ + final String[] statics; + + final Kind[] kinds; + final Object[] accessors; + final String[] attrNames; + + private Slots( + String[] statics, + Kind[] kinds, + Object[] accessors, + String[] attrNames + ) { + this.statics = statics; + this.kinds = kinds; + this.accessors = accessors; + this.attrNames = attrNames; + } + + /** @return null when the chain holds other nodes than static blocks and value slots. */ + static Slots of(HtmlContinuation first) { + int slots = 0; + for (HtmlContinuation c = first; c != null; c = c.getNext()) { + if (c instanceof HtmlContinuationSyncValue) { + slots++; + } else if (!(c instanceof HtmlContinuationSyncStatic)) { + return null; // a dynamic block, an await or a loop + } + } + if (slots == 0) return null; + + String[] statics = new String[slots + 1]; + Kind[] kinds = new Kind[slots]; + Object[] accessors = new Object[slots]; + String[] attrNames = new String[slots]; + + StringBuilder pending = new StringBuilder(); + int i = 0; + for (HtmlContinuation c = first; c != null; c = c.getNext()) { + if (c instanceof HtmlContinuationSyncStatic) { + pending.append( + ((HtmlContinuationSyncStatic) c).staticHtmlBlock + ); + continue; + } + HtmlContinuationSyncValue v = (HtmlContinuationSyncValue) c; + statics[i] = pending.toString(); + pending.setLength(0); + kinds[i] = v.kind(); + accessors[i] = v.accessor(); + attrNames[i] = v.attributeName(); + i++; + } + statics[slots] = pending.toString(); + return new Slots(statics, kinds, accessors, attrNames); + } + } +} diff --git a/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ClassFile.java b/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ClassFile.java new file mode 100644 index 00000000..8114bd49 --- /dev/null +++ b/htmlflow-core/src/main/java/htmlflow/continuations/codegen/ClassFile.java @@ -0,0 +1,358 @@ +/* + * MIT License + * + * Copyright (c) 2025, xmlet HtmlFlow + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package htmlflow.continuations.codegen; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Writes a class file in the order the JVM spec defines: constant pool, fields, methods. Nothing + * here depends on HtmlFlow. + * + * @author Bernardo Pereira + */ +final class ClassFile { + + private static final int MAGIC = 0xCAFEBABE; + private static final int MAJOR_JAVA_17 = 61; + + private static final int ACC_PUBLIC = 0x0001; + private static final int ACC_PRIVATE = 0x0002; + private static final int ACC_FINAL = 0x0010; + private static final int ACC_SUPER = 0x0020; + + private final ConstantPool pool = new ConstantPool(); + private final List fields = new ArrayList<>(); + private final List methods = new ArrayList<>(); + private final int thisClass; + private final int superClass; + private final int codeAttr; + + ClassFile(String name, String superName) throws IOException { + this.thisClass = pool.clazz(name); + this.superClass = pool.clazz(superName); + this.codeAttr = pool.utf8("Code"); + } + + ConstantPool pool() { + return pool; + } + + void field(String name, String desc) throws IOException { + fields.add(new int[] { pool.utf8(name), pool.utf8(desc) }); + } + + void method( + String name, + String desc, + int maxStack, + int maxLocals, + Bytecode code + ) throws IOException { + methods.add( + new Method( + pool.utf8(name), + pool.utf8(desc), + maxStack, + maxLocals, + code + ) + ); + } + + byte[] toBytes() throws IOException { + ByteArrayOutputStream raw = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(raw); + out.writeInt(MAGIC); + out.writeShort(0); // minor version + out.writeShort(MAJOR_JAVA_17); + pool.writeTo(out); + out.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER); + out.writeShort(thisClass); + out.writeShort(superClass); + out.writeShort(0); // interfaces + + out.writeShort(fields.size()); + for (int[] f : fields) { + out.writeShort(ACC_PRIVATE | ACC_FINAL); + out.writeShort(f[0]); + out.writeShort(f[1]); + out.writeShort(0); // field attributes + } + + out.writeShort(methods.size()); + for (Method m : methods) m.writeTo(out, codeAttr); + + out.writeShort(0); // class attributes + return raw.toByteArray(); + } + + /** + * A method_info and its Code attribute. + */ + private static final class Method { + + private final int name; + private final int desc; + private final int maxStack; + private final int maxLocals; + private final Bytecode code; + + Method(int name, int desc, int maxStack, int maxLocals, Bytecode code) { + this.name = name; + this.desc = desc; + this.maxStack = maxStack; + this.maxLocals = maxLocals; + this.code = code; + } + + void writeTo(DataOutputStream out, int codeAttr) throws IOException { + out.writeShort(ACC_PUBLIC); + out.writeShort(name); + out.writeShort(desc); + out.writeShort(1); // one attribute, Code + out.writeShort(codeAttr); + int length = code.size(); + out.writeInt(12 + length); // maxs, length, code, two empty tables + out.writeShort(maxStack); + out.writeShort(maxLocals); + out.writeInt(length); + code.writeTo(out); + out.writeShort(0); // exception table + out.writeShort(0); // no StackMapTable because nothing branches + } + } + + /** The constant pool. Repeated values share one entry. */ + static final class ConstantPool { + + private final Map seen = new HashMap<>(); + private final ByteArrayOutputStream raw = new ByteArrayOutputStream(); + private final DataOutputStream out = new DataOutputStream(raw); + private int next = 1; // index zero is not a valid entry + + int utf8(String value) throws IOException { + return intern( + "u" + value, + () -> { + out.writeByte(1); + out.writeUTF(value); + } + ); + } + + int string(String value) throws IOException { + return intern( + "s" + value, + () -> { + int text = utf8(value); + out.writeByte(8); + out.writeShort(text); + } + ); + } + + int clazz(String internalName) throws IOException { + return intern( + "c" + internalName, + () -> { + int name = utf8(internalName); + out.writeByte(7); + out.writeShort(name); + } + ); + } + + int field(String owner, String name, String desc) throws IOException { + return ref(9, owner, name, desc); + } + + int method(String owner, String name, String desc) throws IOException { + return ref(10, owner, name, desc); + } + + int interfaceMethod(String owner, String name, String desc) + throws IOException { + return ref(11, owner, name, desc); + } + + void writeTo(DataOutputStream target) throws IOException { + out.flush(); + target.writeShort(next); // the count is one past the last index + raw.writeTo(target); + } + + private int ref(int tag, String owner, String name, String desc) + throws IOException { + return intern( + tag + owner + '.' + name + desc, + () -> { + int type = clazz(owner); + int signature = nameAndType(name, desc); + out.writeByte(tag); + out.writeShort(type); + out.writeShort(signature); + } + ); + } + + /** + * Returns the key's index, writing the entry first if it is new. Writing first gives nested + * entries lower indexes, which the format requires. + */ + private int intern(String key, Entry entry) throws IOException { + Integer known = seen.get(key); + if (known != null) return known; + entry.write(); + seen.put(key, next); + return next++; + } + + private interface Entry { + void write() throws IOException; + } + + private int nameAndType(String name, String desc) throws IOException { + return intern( + "n" + name + desc, + () -> { + int n = utf8(name); + int d = utf8(desc); + out.writeByte(12); + out.writeShort(n); + out.writeShort(d); + } + ); + } + } + + /** The bytes of the body of one method. */ + static final class Bytecode { + + private static final int ALOAD_0 = 0x2a; + private static final int ICONST_0 = 0x03; + private static final int BIPUSH = 0x10; + private static final int SIPUSH = 0x11; + private static final int LDC = 0x12; + private static final int LDC_W = 0x13; + private static final int AALOAD = 0x32; + private static final int POP = 0x57; + private static final int RETURN = 0xb1; + private static final int GETFIELD = 0xb4; + private static final int PUTFIELD = 0xb5; + private static final int INVOKESPECIAL = 0xb7; + private static final int INVOKESTATIC = 0xb8; + private static final int INVOKEINTERFACE = 0xb9; + private static final int CHECKCAST = 0xc0; + + private final ByteArrayOutputStream raw = new ByteArrayOutputStream(); + + /** Loads local 0 to 3 with the one-byte aload_n form, enough for the generated code. */ + void aload(int local) { + raw.write(ALOAD_0 + local); + } + + void arrayLoad() { + raw.write(AALOAD); + } + + void pop() { + raw.write(POP); + } + + void returnVoid() { + raw.write(RETURN); + } + + void getField(int field) { + operand(GETFIELD, field); + } + + void putField(int field) { + operand(PUTFIELD, field); + } + + void checkCast(int type) { + operand(CHECKCAST, type); + } + + void invokeSpecial(int method) { + operand(INVOKESPECIAL, method); + } + + void invokeStatic(int method) { + operand(INVOKESTATIC, method); + } + + /** + * invokeinterface also takes a count of argument slots plus the receiver. Every interface + * call here, an accessor or Appendable.append, takes one reference, so the count is 2. + */ + void invokeInterface(int method) { + operand(INVOKEINTERFACE, method); + raw.write(2); + raw.write(0); + } + + void ldc(int constant) { + if (constant <= 0xFF) { + raw.write(LDC); + raw.write(constant); + } else { + operand(LDC_W, constant); + } + } + + void pushInt(int value) { + if (value <= 5) { + raw.write(ICONST_0 + value); + } else if (value <= Byte.MAX_VALUE) { + raw.write(BIPUSH); + raw.write(value); + } else { + operand(SIPUSH, value); + } + } + + int size() { + return raw.size(); + } + + void writeTo(DataOutputStream target) throws IOException { + raw.writeTo(target); + } + + private void operand(int opcode, int index) { + raw.write(opcode); + raw.write(index >>> 8); + raw.write(index); + } + } +} diff --git a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitor.java b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitor.java index 11ae5701..3b7c11bb 100644 --- a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitor.java +++ b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitor.java @@ -24,7 +24,7 @@ package htmlflow.visitor; -import htmlflow.continuations.HtmlContinuation; +import htmlflow.continuations.HtmlResolver; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.xmlet.htmlapifaster.Element; @@ -34,29 +34,29 @@ /** * This is the base implementation of the ElementVisitor (from HtmlApiFaster library). * - *

HtmlViewVisitor is also a head of HtmlContinuation objects chain, storing all needed - * information to emit HTML corresponding to Static HTML blocks and dynamic HTML. + *

HtmlViewVisitor also holds the resolver of the preprocessed template, which emits the static + * HTML blocks and the dynamic HTML. * * @author Miguel Gamboa, Luís Duare, Pedro Fialho created on 17-01-2018 */ public class HtmlViewVisitor extends HtmlVisitor { - /** The first node to be processed. */ - public final HtmlContinuation first; + /** The compiled chain, or the first node of the linked chain. */ + public final HtmlResolver first; public HtmlViewVisitor( Appendable out, boolean isIndented, - HtmlContinuation first + HtmlResolver first ) { super(out, isIndented); this.first = first.copy(this); } - /** Processing output through invocation of HtmlContinuation objects chain. */ + /** Emits the page through the compiled chain or the HtmlContinuation chain. */ @Override public final void resolve(Object model) { - first.execute(model); + first.resolve(model); } @Override diff --git a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsync.java b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsync.java index 494e9787..9e8c44ae 100644 --- a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsync.java +++ b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsync.java @@ -66,7 +66,7 @@ private HtmlViewVisitorAsync( @Override public void resolve(Object model) { - first.execute(model); + first.resolve(model); } @Override @@ -89,7 +89,7 @@ public CompletableFuture finishedAsync(Object model) { */ setNext(last, terminationNode); /** Initializes render on first node. */ - this.first.execute(model); + this.first.resolve(model); return cf; } diff --git a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsyncHot.java b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsyncHot.java index 100dd82c..0b83e55f 100644 --- a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsyncHot.java +++ b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorAsyncHot.java @@ -117,7 +117,7 @@ public CompletableFuture finishedAsync(Object model) { ); continuationProcessor.setAppendable(out); - continuationProcessor.getFirst().execute(model); + continuationProcessor.getFirst().resolve(model); return cf; } diff --git a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorHot.java b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorHot.java index 435eeb66..5be97db1 100644 --- a/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorHot.java +++ b/htmlflow-core/src/main/java/htmlflow/visitor/HtmlViewVisitorHot.java @@ -24,7 +24,15 @@ package htmlflow.visitor; +import htmlflow.continuations.HtmlContinuationSyncValue; +import htmlflow.continuations.HtmlContinuationSyncValue.Kind; import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; import org.xmlet.htmlapifaster.Element; import org.xmlet.htmlapifaster.async.AwaitConsumer; @@ -69,6 +77,88 @@ public void visitDynamic( biConsumer.accept(e, (U) model); } + /** No preencoded chain here, so each slot writes its value straight away. */ + private void writeValue(Kind kind, Object accessor) { + newlineAndIndent(); + HtmlContinuationSyncValue.appendValue(out, kind, accessor, model); + } + + @Override + public void visitValueRaw(Function accessor) { + writeValue(Kind.RAW, accessor); + } + + @Override + public void visitValueText(Function accessor) { + writeValue(Kind.TEXT, accessor); + } + + @Override + public void visitValueInt(ToIntFunction accessor) { + writeValue(Kind.INT, accessor); + } + + @Override + public void visitValueLong(ToLongFunction accessor) { + writeValue(Kind.LONG, accessor); + } + + @Override + public void visitValueDouble(ToDoubleFunction accessor) { + writeValue(Kind.DOUBLE, accessor); + } + + @Override + public void visitValueBoolean(Predicate accessor) { + writeValue(Kind.BOOLEAN, accessor); + } + + @SuppressWarnings("unchecked") + @Override + public void visitValueAttribute(String name, Function accessor) { + visitAttribute(name, String.valueOf(accessor.apply((M) model))); + } + + @SuppressWarnings("unchecked") + @Override + public void visitValueAttributeNullable( + String name, + Function accessor + ) { + Object value = accessor.apply((M) model); + if (value != null) visitAttribute(name, String.valueOf(value)); + } + + @SuppressWarnings("unchecked") + @Override + public void visitForEach( + Function> items, + T element, + Consumer itemTemplate + ) { + Object outer = model; + for (E item : items.apply((M) outer)) { + model = item; + itemTemplate.accept(element); + } + model = outer; + } + + @SuppressWarnings("unchecked") + @Override + public void visitWhen( + Predicate condition, + T element, + Consumer body, + Consumer orElse + ) { + if (condition.test((M) model)) { + body.accept(element); + } else if (orElse != null) { + orElse.accept(element); + } + } + @Override public void visitAwait( E e, diff --git a/htmlflow-core/src/main/java/htmlflow/visitor/PreprocessingVisitor.java b/htmlflow-core/src/main/java/htmlflow/visitor/PreprocessingVisitor.java index 66462308..31f55204 100644 --- a/htmlflow-core/src/main/java/htmlflow/visitor/PreprocessingVisitor.java +++ b/htmlflow-core/src/main/java/htmlflow/visitor/PreprocessingVisitor.java @@ -26,13 +26,28 @@ package htmlflow.visitor; import static htmlflow.visitor.PreprocessingVisitor.HtmlContinuationSetter.setNext; +import static htmlflow.visitor.Tags.ATTRIBUTE_MID; +import static htmlflow.visitor.Tags.QUOTATION; +import static htmlflow.visitor.Tags.SPACE; import htmlflow.continuations.HtmlContinuation; import htmlflow.continuations.HtmlContinuationSyncCloseAndIndent; import htmlflow.continuations.HtmlContinuationSyncDynamic; +import htmlflow.continuations.HtmlContinuationSyncForEach; import htmlflow.continuations.HtmlContinuationSyncStatic; +import htmlflow.continuations.HtmlContinuationSyncValue; +import htmlflow.continuations.HtmlContinuationSyncValue.Kind; +import htmlflow.continuations.HtmlContinuationSyncWhen; +import htmlflow.continuations.HtmlResolver; +import htmlflow.continuations.codegen.ChainCompiler; import java.lang.reflect.Field; import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; import org.xmlet.htmlapifaster.Element; import org.xmlet.htmlapifaster.async.AwaitConsumer; @@ -56,6 +71,13 @@ public class PreprocessingVisitor extends HtmlVisitor { /** The internal String builder beginning index of a static HTML block. */ protected int staticBlockIndex = 0; + /** + * Whether the next static block keeps its leading whitespace. A dynamic block writes its own + * indentation on each render, so the block after it gets trimmed. A value slot writes none, so + * trimming after it would eat real whitespace. + */ + private boolean keepLeadingSpace = false; + /** The first node to be processed. */ protected HtmlContinuation first; @@ -75,6 +97,15 @@ public HtmlContinuation getFirst() { return first; } + /** + * Compiles the chain recorded by {@link #resolve}. Call it once, after the chain is final. + * + * @return The compiled chain, or the linked chain when it does not compile. + */ + public final HtmlResolver compile() { + return ChainCompiler.compile(first); + } + /** * Here we are creating 2 HtmlContinuation objects: one for previous static HTML and a next one * corresponding to the consumer passed to dynamic(). We will first create the dynamic @@ -130,16 +161,212 @@ public void visitAwait( protected final void chainContinuationStatic( HtmlContinuation nextContinuation ) { - String staticHtml = sb().substring(staticBlockIndex); - String staticHtmlTrimmed = staticHtml.trim(); // trim to remove the indentation from static block HtmlContinuation staticCont = new HtmlContinuationSyncStatic( - staticHtmlTrimmed, + takeStaticBlock(true), this, nextContinuation ); - if (first == null) first = staticCont; // on first visit initializes the first pointer - else setNext(last, staticCont); // else append the staticCont to existing chain + appendNode(staticCont); last = nextContinuation.next; // advance last to point to the new HtmlContinuationCloseAndIndent + keepLeadingSpace = false; + } + + /** + * Returns the static HTML written since the last node of the chain. + * + * @param trimEnd True before a dynamic block, which writes the trailing indentation again. + * False before a value slot, where the HTML is already final. + */ + private String takeStaticBlock(boolean trimEnd) { + String block = sb().substring(staticBlockIndex); + int from = 0; + int to = block.length(); + if (!keepLeadingSpace) { + while (from < to && block.charAt(from) <= ' ') from++; + } + if (trimEnd) { + while (to > from && block.charAt(to - 1) <= ' ') to--; + } + return block.substring(from, to); + } + + private void requireOpenTag() { + if (isClosed) throw new IllegalStateException( + "Cannot add attributes after!!!" + ); + } + + /** Chains a value slot, leaving the HTML around it untouched. */ + private void chainValueSlot(Kind kind, Object accessor, String attrName) { + chainStaticThen( + takeStaticBlock(false), + new HtmlContinuationSyncValue(kind, accessor, attrName, this, null) + ); + } + + /** Chains a value slot whose indentation goes in the static block before it. */ + private void chainIndentedValueSlot(Kind kind, Object accessor) { + newlineAndIndent(); + chainValueSlot(kind, accessor, null); + } + + @Override + public void visitValueRaw(Function accessor) { + chainIndentedValueSlot(Kind.RAW, accessor); + } + + @Override + public void visitValueText(Function accessor) { + chainIndentedValueSlot(Kind.TEXT, accessor); + } + + @Override + public void visitValueInt(ToIntFunction accessor) { + chainIndentedValueSlot(Kind.INT, accessor); + } + + @Override + public void visitValueLong(ToLongFunction accessor) { + chainIndentedValueSlot(Kind.LONG, accessor); + } + + @Override + public void visitValueBoolean(Predicate accessor) { + chainIndentedValueSlot(Kind.BOOLEAN, accessor); + } + + @Override + public void visitValueDouble(ToDoubleFunction accessor) { + chainIndentedValueSlot(Kind.DOUBLE, accessor); + } + + @Override + public void visitValueAttribute(String name, Function accessor) { + requireOpenTag(); + // Name and quotes are constant, so they go in the static blocks around the slot. + write(SPACE); + write(name); + write(ATTRIBUTE_MID); + chainValueSlot(Kind.RAW, accessor, null); + write(QUOTATION); + } + + @Override + public void visitValueAttributeNullable( + String name, + Function accessor + ) { + requireOpenTag(); + // The attribute may be absent, so all of it waits for render time. + chainValueSlot(Kind.ATTR_NULLABLE, accessor, name); + } + + @Override + public void visitForEach( + Function> items, + T element, + Consumer itemTemplate + ) { + String outerStatic = openControlFlow(); + chainStaticThen( + outerStatic, + new HtmlContinuationSyncForEach( + items, + recordBlock(element, itemTemplate), + this, + null + ) + ); + } + + @Override + public void visitWhen( + Predicate condition, + T element, + Consumer body, + Consumer orElse + ) { + String outerStatic = openControlFlow(); + HtmlResolver bodyChain = recordBlock(element, body); + HtmlResolver elseChain = recordBlock(element, orElse); + chainStaticThen( + outerStatic, + new HtmlContinuationSyncWhen( + condition, + bodyChain, + elseChain, + this, + null + ) + ); + } + + /** + * Closes the parent begin tag if it is still open, and takes the static HTML before the block. + * The block records its own leading indentation, so this writes none. + */ + private String openControlFlow() { + if (!isClosed) { + depth++; + visitParentOnVoidElements(); + } + return takeStaticBlock(false); + } + + /** + * Preencodes the body of a loop or conditional into its own chain. Saves and restores all the + * recording state, so blocks can nest. + */ + private HtmlResolver recordBlock( + T element, + Consumer body + ) { + if (body == null) return null; + HtmlContinuation outerFirst = first; + HtmlContinuation outerLast = last; + boolean outerKeepLeadingSpace = keepLeadingSpace; + boolean outerIsClosed = isClosed; + int outerDepth = depth; + int mark = sb().length(); + + first = null; + last = null; + // The body owns its leading indentation, so every iteration writes it. + keepLeadingSpace = true; + staticBlockIndex = mark; + + body.accept(element); + + appendNode( + new HtmlContinuationSyncStatic(takeStaticBlock(false), this, null) + ); + HtmlContinuation chain = first; + + first = outerFirst; + last = outerLast; + keepLeadingSpace = outerKeepLeadingSpace; + isClosed = outerIsClosed; + depth = outerDepth; + sb().setLength(mark); // the body lives in its own chain, not the page + staticBlockIndex = mark; + // Bound to this visitor, since a hot async view runs the chain without copying it. + return ChainCompiler.compile(chain).copy(this); + } + + /** Appends the static HTML, skipped when empty, and then the node. */ + private void chainStaticThen(String staticHtml, HtmlContinuation node) { + appendNode( + staticHtml.isEmpty() + ? node + : new HtmlContinuationSyncStatic(staticHtml, this, node) + ); + last = node; + keepLeadingSpace = true; + staticBlockIndex = sb().length(); + } + + private void appendNode(HtmlContinuation node) { + if (first == null) first = node; else setNext(last, node); } protected final void indentAndAdvanceStaticBlockIndex() { @@ -151,9 +378,9 @@ protected final void indentAndAdvanceStaticBlockIndex() { /** Creates the last static HTML block. */ @Override public void resolve(Object model) { - String staticHtml = sb().substring(staticBlockIndex); + String staticHtml = takeStaticBlock(true); HtmlContinuation staticCont = new HtmlContinuationSyncStatic( - staticHtml.trim(), + staticHtml, this, null ); diff --git a/htmlflow-core/src/test/java/htmlflow/test/TestChainCodegen.java b/htmlflow-core/src/test/java/htmlflow/test/TestChainCodegen.java new file mode 100644 index 00000000..322fc03e --- /dev/null +++ b/htmlflow-core/src/test/java/htmlflow/test/TestChainCodegen.java @@ -0,0 +1,269 @@ +package htmlflow.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import htmlflow.HtmlFlow; +import htmlflow.HtmlPage; +import htmlflow.HtmlView; +import htmlflow.continuations.HtmlContinuation; +import htmlflow.continuations.HtmlResolverCompiled; +import htmlflow.exceptions.HtmlFlowAppendException; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Test; + +/** + * The generated write method must produce the HTML of the equivalent dynamic() template, into a + * StringBuilder and into any other Appendable. The template uses every kind of slot, so every + * branch of the generator runs. + */ +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +class TestChainCodegen { + + @Test + void slots_render_as_generated_bytecode() throws Exception { + assertTrue( + isCompiled(), + "no chain compiled, so the tests below would prove nothing" + ); + } + + @Test + void render_into_a_StringBuilder_matches_the_dynamic_block() { + assertEquals(dynamicReference(), render()); + } + + @Test + void write_into_another_Appendable_matches_the_dynamic_block() { + assertEquals( + dynamicReference(), + Utils.renderToAppendable(TestChainCodegen::template, rows()) + ); + } + + /** + * Only the loop body compiles, so the writer fails on the first row. A writer that failed on + * the first append would throw from the linked chain and miss the generated write method. + */ + @Test + void an_IOException_from_write_surfaces_as_HtmlFlowAppendException() { + HtmlView> view = view(); + view.setOut(new FailsOnRow()); + assertThrows(HtmlFlowAppendException.class, () -> view.write(rows())); + } + + private static final class FailsOnRow implements Appendable { + + private final StringBuilder sb = new StringBuilder(); + + @Override + public Appendable append(CharSequence csq) throws IOException { + if (csq.toString().contains("> view = view().threadSafe(); + List outputs = Collections.synchronizedList(new ArrayList<>()); + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + for (int i = 0; i < 64; i++) { + pool.execute(() -> outputs.add(view.render(rows()))); + } + } finally { + pool.shutdown(); + assertTrue( + pool.awaitTermination(30, TimeUnit.SECONDS), + "renders did not finish" + ); + } + assertEquals(64, outputs.size()); + for (String out : outputs) assertEquals(expected, out); + } + /** One property per kind of slot, used inside a loop. */ + private static final class Row { + + final int i; + final long l; + final double d; + final boolean b; + final String text; + final String raw; + final String cls; + final String note; + + Row(int i, String text, String note) { + this.i = i; + this.l = i * 1_000_000_000L; + this.d = i + 0.5; + this.b = i % 2 == 0; + this.text = text; + this.raw = "" + i + ""; + this.cls = i % 2 == 0 ? "even" : "odd"; + this.note = note; + } + } + + private static List rows() { + List rows = new ArrayList<>(); + rows.add(new Row(1, "a & b", "first")); + rows.add(new Row(2, "