001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.commons.svl;
018
019import static org.apache.juneau.commons.utils.ThrowableUtils.*;
020
021import java.io.*;
022import java.util.*;
023import java.util.function.*;
024
025/**
026 * A pre-compiled SVL template.
027 *
028 * <p>
029 * A {@link VarTemplate} is the result of compiling a template string against a {@link VarResolver}.
030 * It separates the "parse" step from the "evaluate" step so that repeated resolutions of the same
031 * input string skip tokenization, var-registry lookup, and (eventually) function-dispatch metadata.
032 *
033 * <p>
034 * Templates are obtained via {@link VarResolver#compile(String)} or
035 * {@link VarResolverSession#compile(String)} — there is no public constructor.
036 *
037 * <h2 class='section'>Compile-binding contract:</h2>
038 * <p>
039 * A compiled template is bound to the {@link VarResolver} instance it was compiled against. Cached
040 * {@link Var} (and, in the future, {@link VarFunction}) references are resolved at compile time.
041 * Passing a {@link VarTemplate} produced by one resolver to a session belonging to a different
042 * resolver is undefined behavior. Rebuilding the resolver invalidates any compiled templates from
043 * the previous instance — caller's responsibility to re-compile.
044 *
045 * <h2 class='section'>Threadsafety:</h2>
046 * <p>
047 * {@link VarTemplate} instances are immutable and threadsafe — the same template can be safely
048 * shared across threads. Note that {@link VarResolverSession} is <b>not</b> threadsafe; the
049 * session passed to {@link #resolve(VarResolverSession)} or {@link #asSupplier(VarResolverSession)}
050 * inherits the standard session-threadsafety contract. The {@link #asSupplierWithFreshSessions(VarResolver)}
051 * variant opens a fresh session per call and is safe to share across threads.
052 *
053 * <h2 class='section'>Which Supplier do I want?</h2>
054 * <ul>
055 *    <li>{@link #asSupplierWithFreshSessions(VarResolver)} — opens a fresh session per
056 *       {@code .get()} call. Safe to share across threads. Use this for user-facing code,
057 *       hot-reload patterns, and any situation where the {@code Supplier} may be invoked
058 *       on threads other than the caller's. <b>Recommended default.</b>
059 *    <li>{@link #asSupplier(VarResolverSession)} — captures the existing session and reuses
060 *       it on every {@code .get()} call. <b>Inherits the session's threadsafety contract</b>
061 *       (i.e. not threadsafe). Use only in perf-sensitive paths where the caller owns the
062 *       session lifecycle.
063 * </ul>
064 *
065 * <h2 class='section'>See Also:</h2><ul>
066 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallSimpleVariableLanguage">Marshall Simple Variable Language</a>
067 * </ul>
068 */
069@SuppressWarnings({
070   "resource" // 'out' and 'session' are caller-owned; this method must not close them.
071})
072public final class VarTemplate {
073
074   /**
075    * The raw template string captured at compile time. Returned by {@link #getSource()}.
076    */
077   private final String input;
078
079   /**
080    * The resolver this template was compiled against. Used by
081    * {@link #asSupplierWithFreshSessions(VarResolver)} to open fresh sessions and by tests for
082    * resolver-binding diagnostics.
083    */
084   private final VarResolver resolver;
085
086   /**
087    * The compiled segments. Walked in order by {@link #resolve(VarResolverSession)} and
088    * {@link #resolveTo(VarResolverSession, Writer)}. Empty array for empty input; single
089    * {@link LiteralSegment} for inputs with no special chars; mixed sequence otherwise.
090    *
091    * <p>
092    * Compile-time stable-value folding may replace {@link VarRefSegment} entries with
093    * {@link LiteralSegment} entries when the wrapped {@link Var} opts in via
094    * {@link Var#isStable()}.
095    */
096   private final TemplateSegment[] segments;
097
098   /**
099    * Cached {@link #isLiteral()} result. Computed once at construction by inspecting
100    * {@link #segments}.
101    */
102   private final boolean literal;
103
104   /**
105    * Pre-computed result for literal-only templates. {@code null} when {@link #literal} is
106    * {@code false}.
107    *
108    * <p>
109    * <b>Why this is not just {@link #input}:</b> escape interpretation can produce a literal
110    * whose text differs from the source. For example {@code "\${literal}"} compiles to a single
111    * {@link LiteralSegment} carrying the string {@code "${literal}"} — the resolved output is
112    * <i>not</i> the raw input. Compile-time stable-value folding similarly produces
113    * literal-only templates whose resolved text is the folded value, not the source. Caching
114    * the joined literal text once at compile time avoids walking segments on every resolve.
115    */
116   private final String literalText;
117
118   /** References found at compile time, in source order. */
119   private final List<TemplateReference> references;
120
121   /** {@code true} if any segment is a folded value literal (see {@link LiteralSegment#value}). */
122   private final boolean hasValueLiteral;
123
124   /**
125    * Package-private constructor — instances are created exclusively via
126    * {@link VarTemplateCompiler#compile(VarResolver, String)} (which is invoked by
127    * {@link VarResolver#compile(String)} and {@link VarResolverSession#compile(String)}).
128    *
129    * @param resolver The resolver this template is bound to.
130    * @param input The raw template string.
131    * @param segments The compiled segments.
132    */
133   VarTemplate(VarResolver resolver, String input, TemplateSegment[] segments) {
134      this(resolver, input, segments, List.of());
135   }
136
137   /**
138    * Package-private constructor with the references collected by the compiler.
139    *
140    * @param resolver The resolver this template is bound to.
141    * @param input The raw template string.
142    * @param segments The compiled segments.
143    * @param references The references found while compiling.
144    */
145   VarTemplate(VarResolver resolver, String input, TemplateSegment[] segments, List<TemplateReference> references) {
146      this.references = references;
147      this.resolver = resolver;
148      this.input = input;
149      this.segments = segments;
150      this.literal = computeIsLiteral(segments);
151      var hv = false;
152      if (segments != null)
153         for (var seg : segments)
154            if (seg instanceof LiteralSegment ls && ls.value)
155               hv = true;
156      this.hasValueLiteral = hv;
157      // For literal-only templates, pre-compute the resolved text. For null source we keep
158      // literalText null so resolve() returns null (matching VarResolverSession.resolve(null)).
159      if (literal && input != null)
160         this.literalText = joinLiteralSegments(segments);
161      else
162         this.literalText = null;
163   }
164
165   /**
166    * Resolves this template against the given session.
167    *
168    * <p>
169    * Walks the cached segment array in order, accumulating the result in a {@link StringBuilder}.
170    * Literal-only templates fast-path to a single allocation skip and return the source string
171    * directly.
172    *
173    * @param session The session to resolve against. Must not be {@code null}. The session is
174    *    not required to belong to the same {@link VarResolver} this template was compiled
175    *    against, but cached {@link Var} references will only honor that resolver's registry —
176    *    see the "compile-binding contract" note in the class javadoc.
177    * @return The resolved string, or {@code null} if this template was compiled from a {@code null} source
178    *    (mirroring {@link VarResolverSession#resolve(String)} returning {@code null} for {@code null} input).
179    *    Otherwise never {@code null}.
180    */
181   public String resolve(VarResolverSession session) {
182      if (literal)
183         return literalText;
184      var sb = new StringBuilder(input.length() * 2);
185      for (var seg : segments)
186         seg.resolve(session, sb);
187      return sb.toString();
188   }
189
190   /**
191    * Resolves this template, passing each resolved <em>value</em> through {@code valueEncoder}.
192    *
193    * <p>
194    * Literal template text is appended unencoded.  Each top-level {@code ${...}} or {@code #{...}} segment is encoded
195    * once, on its final text and after any function inside it has run, so a nested {@code ${...}} is not encoded twice.
196    * A stable var folded at compile time is still encoded.  A {@link Structure} result of an expression is not encoded
197    * here; the session's value formatter renders it and owns the encoding of its items.
198    *
199    * @param session The session to resolve against.  Must not be {@code null}.
200    * @param valueEncoder The encoder applied to resolved values.  <jk>null</jk> behaves like {@link #resolve(VarResolverSession)}.
201    * @return The resolved string, or {@code null} if this template was compiled from a {@code null} source.
202    */
203   public String resolve(VarResolverSession session, UnaryOperator<String> valueEncoder) {
204      if (valueEncoder == null || (literal && ! hasValueLiteral))
205         return resolve(session);
206      var sb = new StringBuilder(input.length() * 2);
207      for (var seg : segments)
208         seg.resolve(session, sb, valueEncoder);
209      return sb.toString();
210   }
211
212   /**
213    * Resolves this template against the given session and writes the result directly to
214    * {@code out}.
215    *
216    * <p>
217    * Streamed-Var-bearing segments write through to {@code out} without materializing an
218    * intermediate {@code String}. Used by {@link VarResolver#resolveTo(String, Writer)} so
219    * downstream serializers can stream large content efficiently.
220    *
221    * @param session The session to resolve against.  Must not be {@code null}.
222    * @param out The writer to append to.  Must not be {@code null}.
223    * @return {@code out}, for fluent-API chaining.
224    * @throws IOException Thrown by the underlying stream.
225    */
226   public Writer resolveTo(VarResolverSession session, Writer out) throws IOException {
227      if (literal) {
228         out.write(literalText);
229         return out;
230      }
231      for (var seg : segments)
232         seg.resolveTo(session, out);
233      return out;
234   }
235
236   /**
237    * Returns a {@link Supplier} that resolves this template against the given session each time
238    * its {@link Supplier#get()} method is called.
239    *
240    * <p>
241    * The captured session is reused across {@code .get()} calls; this Supplier is <b>not</b>
242    * threadsafe (it inherits the session's threadsafety contract). For a threadsafe variant
243    * use {@link #asSupplierWithFreshSessions(VarResolver)}.
244    *
245    * @param session The session to capture. Must not be {@code null}.
246    * @return A {@code Supplier<String>} bound to {@code session}.
247    */
248   public Supplier<String> asSupplier(VarResolverSession session) {
249      return () -> resolve(session);
250   }
251
252   /**
253    * Returns a threadsafe {@link Supplier} that opens a fresh {@link VarResolverSession} on
254    * every {@link Supplier#get()} call.
255    *
256    * <p>
257    * Use this variant when the returned {@code Supplier} may be invoked from threads other
258    * than the caller's — e.g. when stashed on a long-lived bean field or shared across
259    * worker threads. The fresh-session-per-{@code .get()} pattern is the recommended default
260    * for user-facing code.
261    *
262    * @param vr The resolver to open sessions against. Must not be {@code null}. Typically
263    *    the same resolver this template was compiled against.
264    * @return A threadsafe {@code Supplier<String>}.
265    */
266   public Supplier<String> asSupplierWithFreshSessions(VarResolver vr) {
267      return () -> resolve(vr.createSession());
268   }
269
270   /**
271    * Returns {@code true} if this template contains no variable references and resolves to a
272    * fixed string.
273    *
274    * <p>
275    * Computed at compile time by inspecting the segment array: {@code true} iff the array is
276    * empty or contains only {@link LiteralSegment} entries. Stable-value folding may flip a
277    * template with stable {@link Var}s to literal by replacing the relevant {@link VarRefSegment}
278    * entries with {@link LiteralSegment} entries at compile time.
279    *
280    * <p>
281    * Callers can use this hint to fast-path purely-literal templates — for example, by skipping
282    * the {@code Supplier} wrapping overhead for a {@code @Value("plain string")} field:
283    *
284    * <p class='bjava'>
285    *    <jk>var</jk> <jv>tpl</jv> = <jv>vr</jv>.compile(<jv>raw</jv>);
286    *    <jk>if</jk> (<jv>tpl</jv>.isLiteral())
287    *       <jc>// No need to wrap in a Supplier; the value never changes.</jc>
288    *       <jk>return</jk> <jv>tpl</jv>.resolve(<jv>session</jv>);
289    * </p>
290    *
291    * @return {@code true} if the template resolves to a fixed string.
292    */
293   public boolean isLiteral() {
294      return literal;
295   }
296
297   /**
298    * Returns the vars, functions and identifiers this template reads, in source order.
299    *
300    * <p>
301    * Computed once at compile time; calling this does no work.  See {@link TemplateReference} for what is and is not
302    * listed.
303    *
304    * @return An unmodifiable list.  Never <jk>null</jk>.
305    */
306   public List<TemplateReference> references() {
307      return references;
308   }
309
310   /**
311    * Returns the raw input string this template was compiled from.
312    *
313    * <p>
314    * Useful for diagnostics, error messages, and debugging. The string is preserved verbatim
315    * including any escape sequences.
316    *
317    * @return The raw input string.
318    */
319   public String getSource() {
320      return input;
321   }
322
323   /**
324    * The resolver this template is bound to.
325    *
326    * <p>
327    * Package-private accessor for use by {@link VarResolver}/{@link VarResolverSession} and
328    * test code. Callers that need fresh-session resolution should use
329    * {@link #asSupplierWithFreshSessions(VarResolver)} instead.
330    *
331    * @return The bound resolver.
332    */
333   VarResolver getResolver() {
334      return resolver;
335   }
336
337   /**
338    * Package-private accessor for the compiled segments. Used by tests and by the
339    * stable-value folding pass.
340    *
341    * @return The compiled segments. The array is shared (not copied); callers must not mutate.
342    */
343   TemplateSegment[] segments() {
344      return segments;
345   }
346
347   /**
348    * Inspects the segment array to determine whether this template is purely literal.
349    *
350    * <p>
351    * Implementation detail: empty array → literal; all-{@link LiteralSegment} → literal;
352    * anything else → not literal.
353    */
354   private static boolean computeIsLiteral(TemplateSegment[] segments) {
355      if (segments == null || segments.length == 0)
356         return true;
357      for (var seg : segments)
358         if (!seg.isLiteral())
359            return false;
360      return true;
361   }
362
363   /**
364    * Concatenates all {@link LiteralSegment} text into a single string. Caller must have
365    * verified {@link #computeIsLiteral(TemplateSegment[])} is {@code true} before calling.
366    *
367    * <p>
368    * Used to pre-compute {@link #literalText} at construction time so the literal-only
369    * fast-path in {@link #resolve(VarResolverSession)} avoids walking segments per call.
370    */
371   private static String joinLiteralSegments(TemplateSegment[] segments) {
372      if (segments.length == 0)
373         return "";
374      if (segments.length == 1)
375         return ((LiteralSegment) segments[0]).text;
376      var sb = new StringBuilder();
377      for (var seg : segments)
378         sb.append(((LiteralSegment) seg).text);
379      return sb.toString();
380   }
381
382   /**
383    * Convenience helper for callers that need to {@link #resolveTo(VarResolverSession, Writer)}
384    * but don't want to handle {@link IOException}. Wraps any thrown {@link IOException} in a
385    * {@link RuntimeException} via the standard {@code ThrowableUtils.toRex} helper.
386    *
387    * @param session The session to resolve against.  Must not be {@code null}.
388    * @param out The writer to append to.  Must not be {@code null}.
389    * @return {@code out}.
390    */
391   public Writer resolveToUnchecked(VarResolverSession session, Writer out) {
392      try {
393         return resolveTo(session, out);
394      } catch (IOException e) {
395         throw toRex(e);
396      }
397   }
398
399   @Override /* Overridden from Object */
400   public String toString() {
401      return "VarTemplate[" + input + "]";
402   }
403}