mirror of
https://github.com/openjdk/jdk.git
synced 2025-08-27 14:54:52 +02:00
8285932: Implementation of JEP 430 String Templates (Preview)
Reviewed-by: mcimadamore, rriggs, darcy
This commit is contained in:
parent
da2c930262
commit
4aa65cbeef
74 changed files with 9309 additions and 99 deletions
|
@ -1823,6 +1823,42 @@ abstract sealed class AbstractStringBuilder implements Appendable, CharSequence
|
|||
count += end - off;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used by StringConcatHelper via JLA. Adds the current builder count to the
|
||||
* accumulation of items being concatenated. If the coder for the builder is
|
||||
* UTF16 then upgrade the whole concatenation to UTF16.
|
||||
*
|
||||
* @param lengthCoder running accumulation of length and coder
|
||||
*
|
||||
* @return updated accumulation of length and coder
|
||||
*/
|
||||
long mix(long lengthCoder) {
|
||||
return (lengthCoder + count) | ((long)coder << 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used by StringConcatHelper via JLA. Adds the characters in the builder value to the
|
||||
* concatenation buffer and then updates the running accumulation of length.
|
||||
*
|
||||
* @param lengthCoder running accumulation of length and coder
|
||||
* @param buffer concatenation buffer
|
||||
*
|
||||
* @return running accumulation of length and coder minus the number of characters added
|
||||
*/
|
||||
long prepend(long lengthCoder, byte[] buffer) {
|
||||
lengthCoder -= count;
|
||||
|
||||
if (lengthCoder < ((long)UTF16 << 32)) {
|
||||
System.arraycopy(value, 0, buffer, (int)lengthCoder, count);
|
||||
} else if (coder == LATIN1) {
|
||||
StringUTF16.inflate(value, 0, buffer, (int)lengthCoder, count);
|
||||
} else {
|
||||
System.arraycopy(value, 0, buffer, (int)lengthCoder << 1, count << 1);
|
||||
}
|
||||
|
||||
return lengthCoder;
|
||||
}
|
||||
|
||||
private AbstractStringBuilder repeat(char c, int count) {
|
||||
int limit = this.count + count;
|
||||
ensureCapacityInternal(limit);
|
||||
|
|
|
@ -26,6 +26,8 @@
|
|||
package java.lang;
|
||||
|
||||
import jdk.internal.misc.Unsafe;
|
||||
import jdk.internal.javac.PreviewFeature;
|
||||
import jdk.internal.util.FormatConcatItem;
|
||||
import jdk.internal.vm.annotation.ForceInline;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
|
@ -43,6 +45,15 @@ final class StringConcatHelper {
|
|||
// no instantiation
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the coder for the character.
|
||||
* @param value character
|
||||
* @return coder
|
||||
*/
|
||||
static long coder(char value) {
|
||||
return StringLatin1.canEncode(value) ? LATIN1 : UTF16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for overflow, throw exception on overflow.
|
||||
*
|
||||
|
@ -76,7 +87,7 @@ final class StringConcatHelper {
|
|||
* @return new length and coder
|
||||
*/
|
||||
static long mix(long lengthCoder, char value) {
|
||||
return checkOverflow(lengthCoder + 1) | (StringLatin1.canEncode(value) ? 0 : UTF16);
|
||||
return checkOverflow(lengthCoder + 1) | coder(value);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -116,6 +127,21 @@ final class StringConcatHelper {
|
|||
return checkOverflow(lengthCoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mix value length and coder into current length and coder.
|
||||
* @param lengthCoder String length with coder packed into higher bits
|
||||
* the upper word.
|
||||
* @param value value to mix in
|
||||
* @return new length and coder
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static long mix(long lengthCoder, FormatConcatItem value) {
|
||||
lengthCoder = value.mix(lengthCoder);
|
||||
|
||||
return checkOverflow(lengthCoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends the stringly representation of boolean value into buffer,
|
||||
* given the coder and final index. Index is measured in chars, not in bytes!
|
||||
|
@ -319,6 +345,49 @@ final class StringConcatHelper {
|
|||
return indexCoder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends the stringly representation of FormatConcatItem value into buffer,
|
||||
* given the coder and final index. Index is measured in chars, not in bytes!
|
||||
*
|
||||
* @param indexCoder final char index in the buffer, along with coder packed
|
||||
* into higher bits.
|
||||
* @param buf buffer to append to
|
||||
* @param value String value to encode
|
||||
* @return updated index (coder value retained)
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
private static long prepend(long indexCoder, byte[] buf,
|
||||
FormatConcatItem value) {
|
||||
try {
|
||||
return value.prepend(indexCoder, buf);
|
||||
} catch (Error ex) {
|
||||
throw ex;
|
||||
} catch (Throwable ex) {
|
||||
throw new AssertionError("FormatConcatItem prepend error", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends constant and the stringly representation of value into buffer,
|
||||
* given the coder and final index. Index is measured in chars, not in bytes!
|
||||
*
|
||||
* @param indexCoder final char index in the buffer, along with coder packed
|
||||
* into higher bits.
|
||||
* @param buf buffer to append to
|
||||
* @param value boolean value to encode
|
||||
* @param prefix a constant to prepend before value
|
||||
* @return updated index (coder value retained)
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static long prepend(long indexCoder, byte[] buf,
|
||||
FormatConcatItem value, String prefix) {
|
||||
indexCoder = prepend(indexCoder, buf, value);
|
||||
if (prefix != null) indexCoder = prepend(indexCoder, buf, prefix);
|
||||
return indexCoder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates the String with given buffer and coder
|
||||
* @param buf buffer to use
|
||||
|
@ -332,7 +401,8 @@ final class StringConcatHelper {
|
|||
} else if (indexCoder == UTF16) {
|
||||
return new String(buf, String.UTF16);
|
||||
} else {
|
||||
throw new InternalError("Storage is not completely initialized, " + (int)indexCoder + " bytes left");
|
||||
throw new InternalError("Storage is not completely initialized, " +
|
||||
(int)indexCoder + " bytes left");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -449,6 +519,71 @@ final class StringConcatHelper {
|
|||
return String.COMPACT_STRINGS ? LATIN1 : UTF16;
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize after phase1.
|
||||
*/
|
||||
private static class LateInit {
|
||||
static final MethodHandle GETCHAR_LATIN1_MH;
|
||||
|
||||
static final MethodHandle GETCHAR_UTF16_MH;
|
||||
|
||||
static final MethodHandle PUTCHAR_LATIN1_MH;
|
||||
|
||||
static final MethodHandle PUTCHAR_UTF16_MH;
|
||||
|
||||
static {
|
||||
MethodType getCharMT =
|
||||
MethodType.methodType(char.class,
|
||||
byte[].class, int.class);
|
||||
MethodType putCharMT =
|
||||
MethodType.methodType(void.class,
|
||||
byte[].class, int.class, int.class);
|
||||
GETCHAR_LATIN1_MH = lookupStatic("getCharLatin1", getCharMT);
|
||||
GETCHAR_UTF16_MH = lookupStatic("getCharUTF16", getCharMT);
|
||||
PUTCHAR_LATIN1_MH = lookupStatic("putCharLatin1", putCharMT);
|
||||
PUTCHAR_UTF16_MH = lookupStatic("putCharUTF16", putCharMT);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static char getCharLatin1(byte[] buffer, int index) {
|
||||
return (char)buffer[index];
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static char getCharUTF16(byte[] buffer, int index) {
|
||||
return StringUTF16.getChar(buffer, index);
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static void putCharLatin1(byte[] buffer, int index, int ch) {
|
||||
buffer[index] = (byte)ch;
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static void putCharUTF16(byte[] buffer, int index, int ch) {
|
||||
StringUTF16.putChar(buffer, index, ch);
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static MethodHandle selectGetChar(long indexCoder) {
|
||||
return indexCoder < UTF16 ? LateInit.GETCHAR_LATIN1_MH :
|
||||
LateInit.GETCHAR_UTF16_MH;
|
||||
}
|
||||
|
||||
@ForceInline
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
static MethodHandle selectPutChar(long indexCoder) {
|
||||
return indexCoder < UTF16 ? LateInit.PUTCHAR_LATIN1_MH :
|
||||
LateInit.PUTCHAR_UTF16_MH;
|
||||
}
|
||||
|
||||
static MethodHandle lookupStatic(String name, MethodType methodType) {
|
||||
try {
|
||||
return MethodHandles.lookup().findStatic(StringConcatHelper.class, name, methodType);
|
||||
|
|
621
src/java.base/share/classes/java/lang/StringTemplate.java
Normal file
621
src/java.base/share/classes/java/lang/StringTemplate.java
Normal file
|
@ -0,0 +1,621 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.util.FormatProcessor;
|
||||
import java.util.function.Function;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import jdk.internal.access.JavaTemplateAccess;
|
||||
import jdk.internal.access.SharedSecrets;
|
||||
import jdk.internal.javac.PreviewFeature;
|
||||
|
||||
/**
|
||||
* {@link StringTemplate} is the run-time representation of a string template or
|
||||
* text block template in a template expression.
|
||||
* <p>
|
||||
* In the source code of a Java program, a string template or text block template
|
||||
* contains an interleaved succession of <em>fragment literals</em> and <em>embedded
|
||||
* expressions</em>. The {@link StringTemplate#fragments()} method returns the
|
||||
* fragment literals, and the {@link StringTemplate#values()} method returns the
|
||||
* results of evaluating the embedded expressions. {@link StringTemplate} does not
|
||||
* provide access to the source code of the embedded expressions themselves; it is
|
||||
* not a compile-time representation of a string template or text block template.
|
||||
* <p>
|
||||
* {@link StringTemplate} is primarily used in conjunction with a template processor
|
||||
* to produce a string or other meaningful value. Evaluation of a template expression
|
||||
* first produces an instance of {@link StringTemplate}, representing the right hand side
|
||||
* of the template expression, and then passes the instance to the template processor
|
||||
* given by the template expression.
|
||||
* <p>
|
||||
* For example, the following code contains a template expression that uses the template
|
||||
* processor {@code RAW}, which simply yields the {@link StringTemplate} passed to it:
|
||||
* {@snippet :
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* StringTemplate st = RAW."\{x} + \{y} = \{x + y}";
|
||||
* List<String> fragments = st.fragments();
|
||||
* List<Object> values = st.values();
|
||||
* }
|
||||
* {@code fragments} will be equivalent to {@code List.of("", " + ", " = ", "")},
|
||||
* which includes the empty first and last fragments. {@code values} will be the
|
||||
* equivalent of {@code List.of(10, 20, 30)}.
|
||||
* <p>
|
||||
* The following code contains a template expression with the same template but with a
|
||||
* different template processor, {@code STR}:
|
||||
* {@snippet :
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* String s = STR."\{x} + \{y} = \{x + y}";
|
||||
* }
|
||||
* When the template expression is evaluated, an instance of {@link StringTemplate} is
|
||||
* produced that returns the same lists from {@link StringTemplate#fragments()} and
|
||||
* {@link StringTemplate#values()} as shown above. The {@link StringTemplate#STR} template
|
||||
* processor uses these lists to yield an interpolated string. The value of {@code s} will
|
||||
* be equivalent to {@code "10 + 20 = 30"}.
|
||||
* <p>
|
||||
* The {@code interpolate()} method provides a direct way to perform string interpolation
|
||||
* of a {@link StringTemplate}. Template processors can use the following code pattern:
|
||||
* {@snippet :
|
||||
* List<String> fragments = st.fragments();
|
||||
* List<Object> values = st.values();
|
||||
* ... check or manipulate the fragments and/or values ...
|
||||
* String result = StringTemplate.interpolate(fragments, values);
|
||||
* }
|
||||
* The {@link StringTemplate#process(Processor)} method, in conjunction with
|
||||
* the {@link StringTemplate#RAW} processor, may be used to defer processing of a
|
||||
* {@link StringTemplate}.
|
||||
* {@snippet :
|
||||
* StringTemplate st = RAW."\{x} + \{y} = \{x + y}";
|
||||
* ...other steps...
|
||||
* String result = st.process(STR);
|
||||
* }
|
||||
* The factory methods {@link StringTemplate#of(String)} and
|
||||
* {@link StringTemplate#of(List, List)} can be used to construct a {@link StringTemplate}.
|
||||
*
|
||||
* @see Processor
|
||||
* @see java.util.FormatProcessor
|
||||
*
|
||||
* @implNote Implementations of {@link StringTemplate} must minimally implement the
|
||||
* methods {@link StringTemplate#fragments()} and {@link StringTemplate#values()}.
|
||||
* Instances of {@link StringTemplate} are considered immutable. To preserve the
|
||||
* semantics of string templates and text block templates, the list returned by
|
||||
* {@link StringTemplate#fragments()} must be one element larger than the list returned
|
||||
* by {@link StringTemplate#values()}.
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* @jls 15.8.6 Process Template Expressions
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public interface StringTemplate {
|
||||
/**
|
||||
* Returns a list of fragment literals for this {@link StringTemplate}.
|
||||
* The fragment literals are the character sequences preceding each of the embedded
|
||||
* expressions in source code, plus the character sequence following the last
|
||||
* embedded expression. Such character sequences may be zero-length if an embedded
|
||||
* expression appears at the beginning or end of a template, or if two embedded
|
||||
* expressions are directly adjacent in a template.
|
||||
* In the example: {@snippet :
|
||||
* String student = "Mary";
|
||||
* String teacher = "Johnson";
|
||||
* StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";
|
||||
* List<String> fragments = st.fragments(); // @highlight substring="fragments()"
|
||||
* }
|
||||
* {@code fragments} will be equivalent to
|
||||
* {@code List.of("The student ", " is in ", "'s classroom.")}
|
||||
*
|
||||
* @return list of string fragments
|
||||
*
|
||||
* @implSpec the list returned is immutable
|
||||
*/
|
||||
List<String> fragments();
|
||||
|
||||
/**
|
||||
* Returns a list of embedded expression results for this {@link StringTemplate}.
|
||||
* In the example:
|
||||
* {@snippet :
|
||||
* String student = "Mary";
|
||||
* String teacher = "Johnson";
|
||||
* StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";
|
||||
* List<Object> values = st.values(); // @highlight substring="values()"
|
||||
* }
|
||||
* {@code values} will be equivalent to {@code List.of(student, teacher)}
|
||||
*
|
||||
* @return list of expression values
|
||||
*
|
||||
* @implSpec the list returned is immutable
|
||||
*/
|
||||
List<Object> values();
|
||||
|
||||
/**
|
||||
* Returns the string interpolation of the fragments and values for this
|
||||
* {@link StringTemplate}.
|
||||
* @apiNote For better visibility and when practical, it is recommended to use the
|
||||
* {@link StringTemplate#STR} processor instead of invoking the
|
||||
* {@link StringTemplate#interpolate()} method.
|
||||
* {@snippet :
|
||||
* String student = "Mary";
|
||||
* String teacher = "Johnson";
|
||||
* StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";
|
||||
* String result = st.interpolate(); // @highlight substring="interpolate()"
|
||||
* }
|
||||
* In the above example, the value of {@code result} will be
|
||||
* {@code "The student Mary is in Johnson's classroom."}. This is
|
||||
* produced by the interleaving concatenation of fragments and values from the supplied
|
||||
* {@link StringTemplate}. To accommodate concatenation, values are converted to strings
|
||||
* as if invoking {@link String#valueOf(Object)}.
|
||||
*
|
||||
* @return interpolation of this {@link StringTemplate}
|
||||
*
|
||||
* @implSpec The default implementation returns the result of invoking
|
||||
* {@code StringTemplate.interpolate(this.fragments(), this.values())}.
|
||||
*/
|
||||
default String interpolate() {
|
||||
return StringTemplate.interpolate(fragments(), values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the result of applying the specified processor to this {@link StringTemplate}.
|
||||
* This method can be used as an alternative to string template expressions. For example,
|
||||
* {@snippet :
|
||||
* String student = "Mary";
|
||||
* String teacher = "Johnson";
|
||||
* String result1 = STR."The student \{student} is in \{teacher}'s classroom.";
|
||||
* String result2 = RAW."The student \{student} is in \{teacher}'s classroom.".process(STR); // @highlight substring="process"
|
||||
* }
|
||||
* Produces an equivalent result for both {@code result1} and {@code result2}.
|
||||
*
|
||||
* @param processor the {@link Processor} instance to process
|
||||
*
|
||||
* @param <R> Processor's process result type.
|
||||
* @param <E> Exception thrown type.
|
||||
*
|
||||
* @return constructed object of type {@code R}
|
||||
*
|
||||
* @throws E exception thrown by the template processor when validation fails
|
||||
* @throws NullPointerException if processor is null
|
||||
*
|
||||
* @implSpec The default implementation returns the result of invoking
|
||||
* {@code processor.process(this)}. If the invocation throws an exception that
|
||||
* exception is forwarded to the caller.
|
||||
*/
|
||||
default <R, E extends Throwable> R
|
||||
process(Processor<? extends R, ? extends E> processor) throws E {
|
||||
Objects.requireNonNull(processor, "processor should not be null");
|
||||
|
||||
return processor.process(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a diagnostic string that describes the fragments and values of the supplied
|
||||
* {@link StringTemplate}.
|
||||
*
|
||||
* @param stringTemplate the {@link StringTemplate} to represent
|
||||
*
|
||||
* @return diagnostic string representing the supplied string template
|
||||
*
|
||||
* @throws NullPointerException if stringTemplate is null
|
||||
*/
|
||||
static String toString(StringTemplate stringTemplate) {
|
||||
Objects.requireNonNull(stringTemplate, "stringTemplate should not be null");
|
||||
return "StringTemplate{ fragments = [ \"" +
|
||||
String.join("\", \"", stringTemplate.fragments()) +
|
||||
"\" ], values = " +
|
||||
stringTemplate.values() +
|
||||
" }";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link StringTemplate} as if constructed by invoking
|
||||
* {@code StringTemplate.of(List.of(string), List.of())}. That is, a {@link StringTemplate}
|
||||
* with one fragment and no values.
|
||||
*
|
||||
* @param string single string fragment
|
||||
*
|
||||
* @return StringTemplate composed from string
|
||||
*
|
||||
* @throws NullPointerException if string is null
|
||||
*/
|
||||
static StringTemplate of(String string) {
|
||||
Objects.requireNonNull(string, "string must not be null");
|
||||
JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
return JTA.of(List.of(string), List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a StringTemplate with the given fragments and values.
|
||||
*
|
||||
* @implSpec The {@code fragments} list size must be one more that the
|
||||
* {@code values} list size.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param values list of expression values
|
||||
*
|
||||
* @return StringTemplate composed from string
|
||||
*
|
||||
* @throws IllegalArgumentException if fragments list size is not one more
|
||||
* than values list size
|
||||
* @throws NullPointerException if fragments is null or values is null or if any fragment is null.
|
||||
*
|
||||
* @implNote Contents of both lists are copied to construct immutable lists.
|
||||
*/
|
||||
static StringTemplate of(List<String> fragments, List<?> values) {
|
||||
Objects.requireNonNull(fragments, "fragments must not be null");
|
||||
Objects.requireNonNull(values, "values must not be null");
|
||||
if (values.size() + 1 != fragments.size()) {
|
||||
throw new IllegalArgumentException(
|
||||
"fragments list size is not one more than values list size");
|
||||
}
|
||||
JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
return JTA.of(fragments, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a string that interleaves the elements of values between the
|
||||
* elements of fragments. To accommodate interpolation, values are converted to strings
|
||||
* as if invoking {@link String#valueOf(Object)}.
|
||||
*
|
||||
* @param fragments list of String fragments
|
||||
* @param values list of expression values
|
||||
*
|
||||
* @return String interpolation of fragments and values
|
||||
*
|
||||
* @throws IllegalArgumentException if fragments list size is not one more
|
||||
* than values list size
|
||||
* @throws NullPointerException fragments or values is null or if any of the fragments is null
|
||||
*/
|
||||
static String interpolate(List<String> fragments, List<?> values) {
|
||||
Objects.requireNonNull(fragments, "fragments must not be null");
|
||||
Objects.requireNonNull(values, "values must not be null");
|
||||
int fragmentsSize = fragments.size();
|
||||
int valuesSize = values.size();
|
||||
if (fragmentsSize != valuesSize + 1) {
|
||||
throw new IllegalArgumentException("fragments must have one more element than values");
|
||||
}
|
||||
JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
return JTA.interpolate(fragments, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine zero or more {@link StringTemplate StringTemplates} into a single
|
||||
* {@link StringTemplate}.
|
||||
* {@snippet :
|
||||
* StringTemplate st = StringTemplate.combine(RAW."\{a}", RAW."\{b}", RAW."\{c}");
|
||||
* assert st.interpolate().equals(STR."\{a}\{b}\{c}");
|
||||
* }
|
||||
* Fragment lists from the {@link StringTemplate StringTemplates} are combined end to
|
||||
* end with the last fragment from each {@link StringTemplate} concatenated with the
|
||||
* first fragment of the next. To demonstrate, if we were to take two strings and we
|
||||
* combined them as follows: {@snippet lang = "java":
|
||||
* String s1 = "abc";
|
||||
* String s2 = "xyz";
|
||||
* String sc = s1 + s2;
|
||||
* assert Objects.equals(sc, "abcxyz");
|
||||
* }
|
||||
* the last character {@code "c"} from the first string is juxtaposed with the first
|
||||
* character {@code "x"} of the second string. The same would be true of combining
|
||||
* {@link StringTemplate StringTemplates}.
|
||||
* {@snippet lang ="java":
|
||||
* StringTemplate st1 = RAW."a\{}b\{}c";
|
||||
* StringTemplate st2 = RAW."x\{}y\{}z";
|
||||
* StringTemplate st3 = RAW."a\{}b\{}cx\{}y\{}z";
|
||||
* StringTemplate stc = StringTemplate.combine(st1, st2);
|
||||
*
|
||||
* assert Objects.equals(st1.fragments(), List.of("a", "b", "c"));
|
||||
* assert Objects.equals(st2.fragments(), List.of("x", "y", "z"));
|
||||
* assert Objects.equals(st3.fragments(), List.of("a", "b", "cx", "y", "z"));
|
||||
* assert Objects.equals(stc.fragments(), List.of("a", "b", "cx", "y", "z"));
|
||||
* }
|
||||
* Values lists are simply concatenated to produce a single values list.
|
||||
* The result is a well-formed {@link StringTemplate} with n+1 fragments and n values, where
|
||||
* n is the total of number of values across all the supplied
|
||||
* {@link StringTemplate StringTemplates}.
|
||||
*
|
||||
* @param stringTemplates zero or more {@link StringTemplate}
|
||||
*
|
||||
* @return combined {@link StringTemplate}
|
||||
*
|
||||
* @throws NullPointerException if stringTemplates is null or if any of the
|
||||
* {@code stringTemplates} are null
|
||||
*
|
||||
* @implNote If zero {@link StringTemplate} arguments are provided then a
|
||||
* {@link StringTemplate} with an empty fragment and no values is returned, as if invoking
|
||||
* <code>StringTemplate.of("")</code> . If only one {@link StringTemplate} argument is provided
|
||||
* then it is returned unchanged.
|
||||
*/
|
||||
static StringTemplate combine(StringTemplate... stringTemplates) {
|
||||
JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
return JTA.combine(stringTemplates);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine a list of {@link StringTemplate StringTemplates} into a single
|
||||
* {@link StringTemplate}.
|
||||
* {@snippet :
|
||||
* StringTemplate st = StringTemplate.combine(List.of(RAW."\{a}", RAW."\{b}", RAW."\{c}"));
|
||||
* assert st.interpolate().equals(STR."\{a}\{b}\{c}");
|
||||
* }
|
||||
* Fragment lists from the {@link StringTemplate StringTemplates} are combined end to
|
||||
* end with the last fragment from each {@link StringTemplate} concatenated with the
|
||||
* first fragment of the next. To demonstrate, if we were to take two strings and we
|
||||
* combined them as follows: {@snippet lang = "java":
|
||||
* String s1 = "abc";
|
||||
* String s2 = "xyz";
|
||||
* String sc = s1 + s2;
|
||||
* assert Objects.equals(sc, "abcxyz");
|
||||
* }
|
||||
* the last character {@code "c"} from the first string is juxtaposed with the first
|
||||
* character {@code "x"} of the second string. The same would be true of combining
|
||||
* {@link StringTemplate StringTemplates}.
|
||||
* {@snippet lang ="java":
|
||||
* StringTemplate st1 = RAW."a\{}b\{}c";
|
||||
* StringTemplate st2 = RAW."x\{}y\{}z";
|
||||
* StringTemplate st3 = RAW."a\{}b\{}cx\{}y\{}z";
|
||||
* StringTemplate stc = StringTemplate.combine(List.of(st1, st2));
|
||||
*
|
||||
* assert Objects.equals(st1.fragments(), List.of("a", "b", "c"));
|
||||
* assert Objects.equals(st2.fragments(), List.of("x", "y", "z"));
|
||||
* assert Objects.equals(st3.fragments(), List.of("a", "b", "cx", "y", "z"));
|
||||
* assert Objects.equals(stc.fragments(), List.of("a", "b", "cx", "y", "z"));
|
||||
* }
|
||||
* Values lists are simply concatenated to produce a single values list.
|
||||
* The result is a well-formed {@link StringTemplate} with n+1 fragments and n values, where
|
||||
* n is the total of number of values across all the supplied
|
||||
* {@link StringTemplate StringTemplates}.
|
||||
*
|
||||
* @param stringTemplates list of {@link StringTemplate}
|
||||
*
|
||||
* @return combined {@link StringTemplate}
|
||||
*
|
||||
* @throws NullPointerException if stringTemplates is null or if any of the
|
||||
* its elements are null
|
||||
*
|
||||
* @implNote If {@code stringTemplates.size() == 0} then a {@link StringTemplate} with
|
||||
* an empty fragment and no values is returned, as if invoking
|
||||
* <code>StringTemplate.of("")</code> . If {@code stringTemplates.size() == 1}
|
||||
* then the first element of the list is returned unchanged.
|
||||
*/
|
||||
static StringTemplate combine(List<StringTemplate> stringTemplates) {
|
||||
JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
return JTA.combine(stringTemplates.toArray(new StringTemplate[0]));
|
||||
}
|
||||
|
||||
/**
|
||||
* This {@link Processor} instance is conventionally used for the string interpolation
|
||||
* of a supplied {@link StringTemplate}.
|
||||
* <p>
|
||||
* For better visibility and when practical, it is recommended that users use the
|
||||
* {@link StringTemplate#STR} processor instead of invoking the
|
||||
* {@link StringTemplate#interpolate()} method.
|
||||
* Example: {@snippet :
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* String result = STR."\{x} + \{y} = \{x + y}"; // @highlight substring="STR"
|
||||
* }
|
||||
* In the above example, the value of {@code result} will be {@code "10 + 20 = 30"}. This is
|
||||
* produced by the interleaving concatenation of fragments and values from the supplied
|
||||
* {@link StringTemplate}. To accommodate concatenation, values are converted to strings
|
||||
* as if invoking {@link String#valueOf(Object)}.
|
||||
* @apiNote {@link StringTemplate#STR} is statically imported implicitly into every
|
||||
* Java compilation unit.
|
||||
*/
|
||||
Processor<String, RuntimeException> STR = StringTemplate::interpolate;
|
||||
|
||||
/**
|
||||
* This {@link Processor} instance is conventionally used to indicate that the
|
||||
* processing of the {@link StringTemplate} is to be deferred to a later time. Deferred
|
||||
* processing can be resumed by invoking the
|
||||
* {@link StringTemplate#process(Processor)} or
|
||||
* {@link Processor#process(StringTemplate)} methods.
|
||||
* {@snippet :
|
||||
* import static java.lang.StringTemplate.RAW;
|
||||
* ...
|
||||
* StringTemplate st = RAW."\{x} + \{y} = \{x + y}";
|
||||
* ...other steps...
|
||||
* String result = STR.process(st);
|
||||
* }
|
||||
* @implNote Unlike {@link StringTemplate#STR}, {@link StringTemplate#RAW} must be
|
||||
* statically imported explicitly.
|
||||
*/
|
||||
Processor<StringTemplate, RuntimeException> RAW = st -> st;
|
||||
|
||||
/**
|
||||
* This interface describes the methods provided by a generalized string template processor. The
|
||||
* primary method {@link Processor#process(StringTemplate)} is used to validate
|
||||
* and compose a result using a {@link StringTemplate StringTemplate's} fragments and values lists.
|
||||
* <p>
|
||||
* For example:
|
||||
* {@snippet :
|
||||
* class MyProcessor implements Processor<String, IllegalArgumentException> {
|
||||
* @Override
|
||||
* public String process(StringTemplate st) throws IllegalArgumentException {
|
||||
* StringBuilder sb = new StringBuilder();
|
||||
* Iterator<String> fragmentsIter = st.fragments().iterator();
|
||||
*
|
||||
* for (Object value : st.values()) {
|
||||
* sb.append(fragmentsIter.next());
|
||||
*
|
||||
* if (value instanceof Boolean) {
|
||||
* throw new IllegalArgumentException("I don't like Booleans");
|
||||
* }
|
||||
*
|
||||
* sb.append(value);
|
||||
* }
|
||||
*
|
||||
* sb.append(fragmentsIter.next());
|
||||
*
|
||||
* return sb.toString();
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* MyProcessor myProcessor = new MyProcessor();
|
||||
* try {
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* String result = myProcessor."\{x} + \{y} = \{x + y}";
|
||||
* ...
|
||||
* } catch (IllegalArgumentException ex) {
|
||||
* ...
|
||||
* }
|
||||
* }
|
||||
* Implementations of this interface may provide, but are not limited to, validating
|
||||
* inputs, composing inputs into a result, and transforming an intermediate string
|
||||
* result to a non-string value before delivering the final result.
|
||||
* <p>
|
||||
* The user has the option of validating inputs used in composition. For example an SQL
|
||||
* processor could prevent injection vulnerabilities by sanitizing inputs or throwing an
|
||||
* exception of type {@code E} if an SQL statement is a potential vulnerability.
|
||||
* <p>
|
||||
* Composing allows user control over how the result is assembled. Most often, a
|
||||
* user will construct a new string from the string template, with placeholders
|
||||
* replaced by string representations of value list elements. These string
|
||||
* representations are created as if invoking {@link String#valueOf}.
|
||||
* <p>
|
||||
* Transforming allows the processor to return something other than a string. For
|
||||
* instance, a JSON processor could return a JSON object, by parsing the string created
|
||||
* by composition, instead of the composed string.
|
||||
* <p>
|
||||
* {@link Processor} is a {@link FunctionalInterface}. This permits
|
||||
* declaration of a processor using lambda expressions;
|
||||
* {@snippet :
|
||||
* Processor<String, RuntimeException> processor = st -> {
|
||||
* List<String> fragments = st.fragments();
|
||||
* List<Object> values = st.values();
|
||||
* // check or manipulate the fragments and/or values
|
||||
* ...
|
||||
* return StringTemplate.interpolate(fragments, values);
|
||||
* };
|
||||
* }
|
||||
* The {@link StringTemplate#interpolate()} method is available for those processors
|
||||
* that just need to work with the string interpolation;
|
||||
* {@snippet :
|
||||
* Processor<String, RuntimeException> processor = StringTemplate::interpolate;
|
||||
* }
|
||||
* or simply transform the string interpolation into something other than
|
||||
* {@link String};
|
||||
* {@snippet :
|
||||
* Processor<JSONObject, RuntimeException> jsonProcessor = st -> new JSONObject(st.interpolate());
|
||||
* }
|
||||
* @implNote The Java compiler automatically imports {@link StringTemplate#STR}
|
||||
*
|
||||
* @param <R> Processor's process result type
|
||||
* @param <E> Exception thrown type
|
||||
*
|
||||
* @see StringTemplate
|
||||
* @see java.util.FormatProcessor
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* @jls 15.8.6 Process Template Expressions
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
@FunctionalInterface
|
||||
public interface Processor<R, E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Constructs a result based on the template fragments and values in the
|
||||
* supplied {@link StringTemplate stringTemplate} object.
|
||||
* @apiNote Processing of a {@link StringTemplate} may include validation according to the particular facts relating
|
||||
* to each situation. The {@code E} type parameter indicates the type of checked exception that is thrown by
|
||||
* {@link #process} if validation fails, ex. {@code java.sql.SQLException}. If no checked exception is expected
|
||||
* then {@link RuntimeException} may be used. Note that unchecked exceptions, such as {@link RuntimeException},
|
||||
* {@link NullPointerException} or {@link IllegalArgumentException} may be thrown as part of the normal
|
||||
* method arguments processing. Details of which exceptions are thrown will be found in the documentation
|
||||
* of the specific implementation.
|
||||
*
|
||||
* @param stringTemplate a {@link StringTemplate} instance
|
||||
*
|
||||
* @return constructed object of type R
|
||||
*
|
||||
* @throws E exception thrown by the template processor when validation fails
|
||||
*/
|
||||
R process(StringTemplate stringTemplate) throws E;
|
||||
|
||||
/**
|
||||
* This factory method can be used to create a {@link Processor} containing a
|
||||
* {@link Processor#process} method derived from a lambda expression. As an example;
|
||||
* {@snippet :
|
||||
* Processor<String, RuntimeException> mySTR = Processor.of(StringTemplate::interpolate);
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* String str = mySTR."\{x} + \{y} = \{x + y}";
|
||||
* }
|
||||
* The result type of the constructed {@link Processor} may be derived from
|
||||
* the lambda expression, thus this method may be used in a var
|
||||
* statement. For example, {@code mySTR} from above can also be declared using;
|
||||
* {@snippet :
|
||||
* var mySTR = Processor.of(StringTemplate::interpolate);
|
||||
* }
|
||||
* {@link RuntimeException} is the assumed exception thrown type.
|
||||
*
|
||||
* @param process a function that takes a {@link StringTemplate} as an argument
|
||||
* and returns the inferred result type
|
||||
*
|
||||
* @return a {@link Processor}
|
||||
*
|
||||
* @param <T> Processor's process result type
|
||||
*/
|
||||
static <T> Processor<T, RuntimeException> of(Function<? super StringTemplate, ? extends T> process) {
|
||||
return process::apply;
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in policies using this additional interface have the flexibility to
|
||||
* specialize the composition of the templated string by returning a customized
|
||||
* {@link MethodHandle} from {@link Linkage#linkage linkage}.
|
||||
* These specializations are typically implemented to improve performance;
|
||||
* specializing value types or avoiding boxing and vararg arrays.
|
||||
*
|
||||
* @implNote This interface is sealed to only allow standard processors.
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public sealed interface Linkage permits FormatProcessor {
|
||||
/**
|
||||
* This method creates a {@link MethodHandle} that when invoked with arguments of
|
||||
* those specified in {@code type} returns a result that equals that returned by
|
||||
* the template processor's process method. The difference being that this method
|
||||
* can preview the template's fragments and value types in advance of usage and
|
||||
* thereby has the opportunity to produce a specialized implementation.
|
||||
*
|
||||
* @param fragments string template fragments
|
||||
* @param type method type, includes the StringTemplate receiver as
|
||||
* well as the value types
|
||||
*
|
||||
* @return {@link MethodHandle} for the processor applied to template
|
||||
*
|
||||
* @throws NullPointerException if any of the arguments are null
|
||||
*/
|
||||
MethodHandle linkage(List<String> fragments, MethodType type);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -77,10 +77,11 @@ import jdk.internal.reflect.CallerSensitive;
|
|||
import jdk.internal.reflect.Reflection;
|
||||
import jdk.internal.access.JavaLangAccess;
|
||||
import jdk.internal.access.SharedSecrets;
|
||||
import jdk.internal.misc.VM;
|
||||
import jdk.internal.javac.PreviewFeature;
|
||||
import jdk.internal.logger.LoggerFinderLoader;
|
||||
import jdk.internal.logger.LazyLoggers;
|
||||
import jdk.internal.logger.LocalizedLoggerWrapper;
|
||||
import jdk.internal.misc.VM;
|
||||
import jdk.internal.util.SystemProps;
|
||||
import jdk.internal.vm.Continuation;
|
||||
import jdk.internal.vm.ContinuationScope;
|
||||
|
@ -2522,6 +2523,23 @@ public final class System {
|
|||
return StringConcatHelper.mix(lengthCoder, constant);
|
||||
}
|
||||
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public long stringConcatCoder(char value) {
|
||||
return StringConcatHelper.coder(value);
|
||||
}
|
||||
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public long stringBuilderConcatMix(long lengthCoder,
|
||||
StringBuilder sb) {
|
||||
return sb.mix(lengthCoder);
|
||||
}
|
||||
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public long stringBuilderConcatPrepend(long lengthCoder, byte[] buf,
|
||||
StringBuilder sb) {
|
||||
return sb.prepend(lengthCoder, buf);
|
||||
}
|
||||
|
||||
public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
|
||||
return String.join(prefix, suffix, delimiter, elements, size);
|
||||
}
|
||||
|
|
|
@ -27,10 +27,15 @@ package java.lang.invoke;
|
|||
|
||||
import jdk.internal.access.JavaLangAccess;
|
||||
import jdk.internal.access.SharedSecrets;
|
||||
import jdk.internal.javac.PreviewFeature;
|
||||
import jdk.internal.util.FormatConcatItem;
|
||||
import jdk.internal.vm.annotation.Stable;
|
||||
import sun.invoke.util.Wrapper;
|
||||
|
||||
import java.lang.invoke.MethodHandles.Lookup;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static java.lang.invoke.MethodType.methodType;
|
||||
|
@ -110,8 +115,14 @@ public final class StringConcatFactory {
|
|||
* While the maximum number of argument slots that indy call can handle is 253,
|
||||
* we do not use all those slots, to let the strategies with MethodHandle
|
||||
* combinators to use some arguments.
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
private static final int MAX_INDY_CONCAT_ARG_SLOTS = 200;
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public static final int MAX_INDY_CONCAT_ARG_SLOTS;
|
||||
// Use static initialize block to avoid MAX_INDY_CONCAT_ARG_SLOTS being treating
|
||||
// as a constant for constant folding.
|
||||
static { MAX_INDY_CONCAT_ARG_SLOTS = 200; }
|
||||
|
||||
private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
|
||||
|
||||
|
@ -321,6 +332,7 @@ public final class StringConcatFactory {
|
|||
{
|
||||
Objects.requireNonNull(lookup, "Lookup is null");
|
||||
Objects.requireNonNull(name, "Name is null");
|
||||
Objects.requireNonNull(recipe, "Recipe is null");
|
||||
Objects.requireNonNull(concatType, "Concat type is null");
|
||||
Objects.requireNonNull(constants, "Constants are null");
|
||||
|
||||
|
@ -488,14 +500,12 @@ public final class StringConcatFactory {
|
|||
// Use int as the logical type for subword integral types
|
||||
// (byte and short). char and boolean require special
|
||||
// handling so don't change the logical type of those
|
||||
if (cl == byte.class || cl == short.class) {
|
||||
ptypes[i] = int.class;
|
||||
}
|
||||
ptypes[i] = promoteToIntType(ptypes[i]);
|
||||
// Object, float and double will be eagerly transformed
|
||||
// into a (non-null) String as a first step after invocation.
|
||||
// Set up to use String as the logical type for such arguments
|
||||
// internally.
|
||||
else if (cl == Object.class) {
|
||||
if (cl == Object.class) {
|
||||
if (objFilters == null) {
|
||||
objFilters = new MethodHandle[ptypes.length];
|
||||
}
|
||||
|
@ -664,7 +674,6 @@ public final class StringConcatFactory {
|
|||
return argPositions;
|
||||
}
|
||||
|
||||
|
||||
private static MethodHandle foldInLastMixers(MethodHandle mh, long initialLengthCoder, int pos, Class<?>[] ptypes, int count) {
|
||||
MethodHandle mix = switch (count) {
|
||||
case 1 -> mixer(ptypes[pos]);
|
||||
|
@ -710,6 +719,9 @@ public final class StringConcatFactory {
|
|||
int idx = classIndex(cl);
|
||||
MethodHandle prepend = PREPENDERS[idx];
|
||||
if (prepend == null) {
|
||||
if (idx == STRING_CONCAT_ITEM) {
|
||||
cl = FormatConcatItem.class;
|
||||
}
|
||||
PREPENDERS[idx] = prepend = JLA.stringConcatHelper("prepend",
|
||||
methodType(long.class, long.class, byte[].class,
|
||||
Wrapper.asPrimitiveType(cl), String.class)).rebind();
|
||||
|
@ -722,13 +734,15 @@ public final class StringConcatFactory {
|
|||
LONG_IDX = 2,
|
||||
BOOLEAN_IDX = 3,
|
||||
STRING_IDX = 4,
|
||||
TYPE_COUNT = 5;
|
||||
STRING_CONCAT_ITEM = 5,
|
||||
TYPE_COUNT = 6;
|
||||
private static int classIndex(Class<?> cl) {
|
||||
if (cl == String.class) return STRING_IDX;
|
||||
if (cl == int.class) return INT_IDX;
|
||||
if (cl == boolean.class) return BOOLEAN_IDX;
|
||||
if (cl == char.class) return CHAR_IDX;
|
||||
if (cl == long.class) return LONG_IDX;
|
||||
if (cl == String.class) return STRING_IDX;
|
||||
if (cl == int.class) return INT_IDX;
|
||||
if (cl == boolean.class) return BOOLEAN_IDX;
|
||||
if (cl == char.class) return CHAR_IDX;
|
||||
if (cl == long.class) return LONG_IDX;
|
||||
if (FormatConcatItem.class.isAssignableFrom(cl)) return STRING_CONCAT_ITEM;
|
||||
throw new IllegalArgumentException("Unexpected class: " + cl);
|
||||
}
|
||||
|
||||
|
@ -986,6 +1000,33 @@ public final class StringConcatFactory {
|
|||
private static final @Stable MethodHandle[] MIXERS = new MethodHandle[TYPE_COUNT];
|
||||
private static final long INITIAL_CODER = JLA.stringConcatInitialCoder();
|
||||
|
||||
/**
|
||||
* Promote integral types to int.
|
||||
*/
|
||||
private static Class<?> promoteToIntType(Class<?> t) {
|
||||
// use int for subword integral types; still need special mixers
|
||||
// and prependers for char, boolean
|
||||
return t == byte.class || t == short.class ? int.class : t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a stringifier for references and floats/doubles only.
|
||||
* Always returns null for other primitives.
|
||||
*
|
||||
* @param t class to stringify
|
||||
* @return stringifier; null, if not available
|
||||
*/
|
||||
private static MethodHandle stringifierFor(Class<?> t) {
|
||||
if (t == Object.class) {
|
||||
return objectStringifier();
|
||||
} else if (t == float.class) {
|
||||
return floatStringifier();
|
||||
} else if (t == double.class) {
|
||||
return doubleStringifier();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static MethodHandle stringValueOf(Class<?> ptype) {
|
||||
try {
|
||||
return MethodHandles.publicLookup()
|
||||
|
@ -998,4 +1039,304 @@ public final class StringConcatFactory {
|
|||
private StringConcatFactory() {
|
||||
// no instantiation
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified concatenation method to facilitate {@link StringTemplate}
|
||||
* concatenation. This method returns a single concatenation method that
|
||||
* interleaves fragments and values. fragment|value|fragment|value|...|value|fragment.
|
||||
* The number of fragments must be one more that the number of ptypes.
|
||||
* The total number of slots used by the ptypes must be less than or equal
|
||||
* to {@link #MAX_INDY_CONCAT_ARG_SLOTS}.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param ptypes list of expression types
|
||||
*
|
||||
* @return the {@link MethodHandle} for concatenation
|
||||
*
|
||||
* @throws StringConcatException If any of the linkage invariants are violated.
|
||||
* @throws NullPointerException If any of the incoming arguments is null.
|
||||
* @throws IllegalArgumentException If the number of value slots exceed {@link #MAX_INDY_CONCAT_ARG_SLOTS}.
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public static MethodHandle makeConcatWithTemplate(
|
||||
List<String> fragments,
|
||||
List<Class<?>> ptypes)
|
||||
throws StringConcatException
|
||||
{
|
||||
Objects.requireNonNull(fragments, "fragments is null");
|
||||
Objects.requireNonNull(ptypes, "ptypes is null");
|
||||
ptypes = List.copyOf(ptypes);
|
||||
|
||||
if (fragments.size() != ptypes.size() + 1) {
|
||||
throw new IllegalArgumentException("fragments size not equal ptypes size plus one");
|
||||
}
|
||||
|
||||
if (ptypes.isEmpty()) {
|
||||
return MethodHandles.constant(String.class, fragments.get(0));
|
||||
}
|
||||
|
||||
Class<?>[] ttypes = new Class<?>[ptypes.size()];
|
||||
MethodHandle[] filters = new MethodHandle[ptypes.size()];
|
||||
int slots = 0;
|
||||
|
||||
int pos = 0;
|
||||
for (Class<?> ptype : ptypes) {
|
||||
slots += ptype == long.class || ptype == double.class ? 2 : 1;
|
||||
|
||||
if (MAX_INDY_CONCAT_ARG_SLOTS < slots) {
|
||||
throw new StringConcatException("Too many concat argument slots: " +
|
||||
slots + ", can only accept " + MAX_INDY_CONCAT_ARG_SLOTS);
|
||||
}
|
||||
|
||||
boolean isSpecialized = ptype.isPrimitive();
|
||||
boolean isFormatConcatItem = FormatConcatItem.class.isAssignableFrom(ptype);
|
||||
Class<?> ttype = isSpecialized ? promoteToIntType(ptype) :
|
||||
isFormatConcatItem ? FormatConcatItem.class : Object.class;
|
||||
MethodHandle filter = isFormatConcatItem ? null : stringifierFor(ttype);
|
||||
|
||||
if (filter != null) {
|
||||
filters[pos] = filter;
|
||||
ttype = String.class;
|
||||
}
|
||||
|
||||
ttypes[pos++] = ttype;
|
||||
}
|
||||
|
||||
MethodHandle mh = MethodHandles.dropArguments(newString(), 2, ttypes);
|
||||
|
||||
long initialLengthCoder = INITIAL_CODER;
|
||||
String lastFragment = "";
|
||||
pos = 0;
|
||||
for (String fragment : fragments) {
|
||||
lastFragment = fragment;
|
||||
|
||||
if (ttypes.length <= pos) {
|
||||
break;
|
||||
}
|
||||
|
||||
Class<?> ttype = ttypes[pos];
|
||||
// (long,byte[],ttype) -> long
|
||||
MethodHandle prepender = prepender(lastFragment.isEmpty() ? null : fragment, ttype);
|
||||
initialLengthCoder = JLA.stringConcatMix(initialLengthCoder, fragment);
|
||||
// (byte[],long,ttypes...) -> String (unchanged)
|
||||
mh = MethodHandles.filterArgumentsWithCombiner(mh, 1, prepender,1, 0, 2 + pos);
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
MethodHandle newArrayCombinator = lastFragment.isEmpty() ? newArray() :
|
||||
newArrayWithSuffix(lastFragment);
|
||||
// (long,ttypes...) -> String
|
||||
mh = MethodHandles.foldArgumentsWithCombiner(mh, 0, newArrayCombinator,
|
||||
1 // index
|
||||
);
|
||||
|
||||
pos = 0;
|
||||
for (Class<?> ttype : ttypes) {
|
||||
// (long,ttype) -> long
|
||||
MethodHandle mix = mixer(ttypes[pos]);
|
||||
boolean lastPType = pos == ttypes.length - 1;
|
||||
|
||||
if (lastPType) {
|
||||
// (ttype) -> long
|
||||
mix = MethodHandles.insertArguments(mix, 0, initialLengthCoder);
|
||||
// (ttypes...) -> String
|
||||
mh = MethodHandles.foldArgumentsWithCombiner(mh, 0, mix,
|
||||
1 + pos // selected argument
|
||||
);
|
||||
} else {
|
||||
// (long,ttypes...) -> String
|
||||
mh = MethodHandles.filterArgumentsWithCombiner(mh, 0, mix,
|
||||
0, // old-index
|
||||
1 + pos // selected argument
|
||||
);
|
||||
}
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
mh = MethodHandles.filterArguments(mh, 0, filters);
|
||||
MethodType mt = MethodType.methodType(String.class, ptypes);
|
||||
mh = mh.viewAsType(mt, true);
|
||||
|
||||
return mh;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method breaks up large concatenations into separate
|
||||
* {@link MethodHandle MethodHandles} based on the number of slots required
|
||||
* per {@link MethodHandle}. Each {@link MethodHandle} after the first will
|
||||
* have an extra {@link String} slot for the result from the previous
|
||||
* {@link MethodHandle}.
|
||||
* {@link #makeConcatWithTemplate}
|
||||
* is used to construct the {@link MethodHandle MethodHandles}. The total
|
||||
* number of slots used by the ptypes is open ended. However, care must
|
||||
* be given when combining the {@link MethodHandle MethodHandles} so that
|
||||
* the combine total does not exceed the 255 slot limit.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param ptypes list of expression types
|
||||
* @param maxSlots maximum number of slots per {@link MethodHandle}.
|
||||
*
|
||||
* @return List of {@link MethodHandle MethodHandles}
|
||||
*
|
||||
* @throws IllegalArgumentException If maxSlots is not between 1 and
|
||||
* MAX_INDY_CONCAT_ARG_SLOTS.
|
||||
* @throws StringConcatException If any of the linkage invariants are violated.
|
||||
* @throws NullPointerException If any of the incoming arguments is null.
|
||||
* @throws IllegalArgumentException If the number of value slots exceed {@link #MAX_INDY_CONCAT_ARG_SLOTS}.
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public static List<MethodHandle> makeConcatWithTemplateCluster(
|
||||
List<String> fragments,
|
||||
List<Class<?>> ptypes,
|
||||
int maxSlots)
|
||||
throws StringConcatException
|
||||
{
|
||||
Objects.requireNonNull(fragments, "fragments is null");
|
||||
Objects.requireNonNull(ptypes, "ptypes is null");
|
||||
|
||||
if (fragments.size() != ptypes.size() + 1) {
|
||||
throw new StringConcatException("fragments size not equal ptypes size plus one");
|
||||
}
|
||||
|
||||
if (maxSlots < 1 || MAX_INDY_CONCAT_ARG_SLOTS < maxSlots) {
|
||||
throw new IllegalArgumentException("maxSlots must be between 1 and " +
|
||||
MAX_INDY_CONCAT_ARG_SLOTS);
|
||||
|
||||
}
|
||||
|
||||
if (ptypes.isEmpty()) {
|
||||
return List.of(MethodHandles.constant(String.class, fragments.get(0)));
|
||||
}
|
||||
|
||||
List<MethodHandle> mhs = new ArrayList<>();
|
||||
List<String> fragmentsSection = new ArrayList<>();
|
||||
List<Class<?>> ptypeSection = new ArrayList<>();
|
||||
int slots = 0;
|
||||
|
||||
int pos = 0;
|
||||
for (Class<?> ptype : ptypes) {
|
||||
boolean lastPType = pos == ptypes.size() - 1;
|
||||
fragmentsSection.add(fragments.get(pos));
|
||||
ptypeSection.add(ptype);
|
||||
|
||||
slots += ptype == long.class || ptype == double.class ? 2 : 1;
|
||||
|
||||
if (maxSlots <= slots || lastPType) {
|
||||
fragmentsSection.add(lastPType ? fragments.get(pos + 1) : "");
|
||||
MethodHandle mh = makeConcatWithTemplate(fragmentsSection,
|
||||
ptypeSection);
|
||||
mhs.add(mh);
|
||||
fragmentsSection.clear();
|
||||
fragmentsSection.add("");
|
||||
ptypeSection.clear();
|
||||
ptypeSection.add(String.class);
|
||||
slots = 1;
|
||||
}
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
return mhs;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method creates a {@link MethodHandle} expecting one input, the
|
||||
* receiver of the supplied getters. This method uses
|
||||
* {@link #makeConcatWithTemplateCluster}
|
||||
* to create the intermediate {@link MethodHandle MethodHandles}.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param getters list of getter {@link MethodHandle MethodHandles}
|
||||
* @param maxSlots maximum number of slots per {@link MethodHandle} in
|
||||
* cluster.
|
||||
*
|
||||
* @return the {@link MethodHandle} for concatenation
|
||||
*
|
||||
* @throws IllegalArgumentException If maxSlots is not between 1 and
|
||||
* MAX_INDY_CONCAT_ARG_SLOTS or if the
|
||||
* getters don't use the same argument type
|
||||
* @throws StringConcatException If any of the linkage invariants are violated
|
||||
* @throws NullPointerException If any of the incoming arguments is null
|
||||
* @throws IllegalArgumentException If the number of value slots exceed {@link #MAX_INDY_CONCAT_ARG_SLOTS}.
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public static MethodHandle makeConcatWithTemplateGetters(
|
||||
List<String> fragments,
|
||||
List<MethodHandle> getters,
|
||||
int maxSlots)
|
||||
throws StringConcatException
|
||||
{
|
||||
Objects.requireNonNull(fragments, "fragments is null");
|
||||
Objects.requireNonNull(getters, "getters is null");
|
||||
|
||||
if (fragments.size() != getters.size() + 1) {
|
||||
throw new StringConcatException("fragments size not equal getters size plus one");
|
||||
}
|
||||
|
||||
if (maxSlots < 1 || MAX_INDY_CONCAT_ARG_SLOTS < maxSlots) {
|
||||
throw new IllegalArgumentException("maxSlots must be between 1 and " +
|
||||
MAX_INDY_CONCAT_ARG_SLOTS);
|
||||
|
||||
}
|
||||
|
||||
if (getters.size() == 0) {
|
||||
throw new StringConcatException("no getters supplied");
|
||||
}
|
||||
|
||||
Class<?> receiverType = null;
|
||||
List<Class<?>> ptypes = new ArrayList<>();
|
||||
|
||||
for (MethodHandle getter : getters) {
|
||||
MethodType mt = getter.type();
|
||||
Class<?> returnType = mt.returnType();
|
||||
|
||||
if (returnType == void.class || mt.parameterCount() != 1) {
|
||||
throw new StringConcatException("not a getter " + mt);
|
||||
}
|
||||
|
||||
if (receiverType == null) {
|
||||
receiverType = mt.parameterType(0);
|
||||
} else if (receiverType != mt.parameterType(0)) {
|
||||
throw new StringConcatException("not the same receiever type " +
|
||||
mt + " needs " + receiverType);
|
||||
}
|
||||
|
||||
ptypes.add(returnType);
|
||||
}
|
||||
|
||||
MethodType resultType = MethodType.methodType(String.class, receiverType);
|
||||
List<MethodHandle> clusters = makeConcatWithTemplateCluster(fragments, ptypes,
|
||||
maxSlots);
|
||||
|
||||
MethodHandle mh = null;
|
||||
Iterator<MethodHandle> getterIterator = getters.iterator();
|
||||
|
||||
for (MethodHandle cluster : clusters) {
|
||||
MethodType mt = cluster.type();
|
||||
MethodHandle[] filters = new MethodHandle[mt.parameterCount()];
|
||||
int pos = 0;
|
||||
|
||||
if (mh != null) {
|
||||
filters[pos++] = mh;
|
||||
}
|
||||
|
||||
while (pos < filters.length) {
|
||||
filters[pos++] = getterIterator.next();
|
||||
}
|
||||
|
||||
cluster = MethodHandles.filterArguments(cluster, 0, filters);
|
||||
mh = MethodHandles.permuteArguments(cluster, resultType,
|
||||
new int[filters.length]);
|
||||
}
|
||||
|
||||
return mh;
|
||||
}
|
||||
}
|
||||
|
|
1004
src/java.base/share/classes/java/lang/runtime/Carriers.java
Normal file
1004
src/java.base/share/classes/java/lang/runtime/Carriers.java
Normal file
File diff suppressed because it is too large
Load diff
230
src/java.base/share/classes/java/lang/runtime/ReferenceKey.java
Normal file
230
src/java.base/share/classes/java/lang/runtime/ReferenceKey.java
Normal file
|
@ -0,0 +1,230 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.lang.ref.Reference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* View/wrapper of keys used by the backing {@link ReferencedKeyMap}.
|
||||
* There are two style of keys; one for entries in the backing map and
|
||||
* one for queries to the backing map. This second style avoids the
|
||||
* overhead of a {@link Reference} object.
|
||||
*
|
||||
* @param <T> key type
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* Warning: This class is part of PreviewFeature.Feature.STRING_TEMPLATES.
|
||||
* Do not rely on its availability.
|
||||
*/
|
||||
interface ReferenceKey<T> {
|
||||
/**
|
||||
* {@return the value of the unwrapped key}
|
||||
*/
|
||||
T get();
|
||||
|
||||
/**
|
||||
* Cleanup unused key.
|
||||
*/
|
||||
void unused();
|
||||
|
||||
/**
|
||||
* {@link WeakReference} wrapper key for entries in the backing map.
|
||||
*
|
||||
* @param <T> key type
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
class WeakKey<T> extends WeakReference<T> implements ReferenceKey<T> {
|
||||
/**
|
||||
* Saved hashcode of the key. Used when {@link WeakReference} is
|
||||
* null.
|
||||
*/
|
||||
private final int hashcode;
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*
|
||||
* @param key unwrapped key value
|
||||
* @param queue reference queue
|
||||
*/
|
||||
WeakKey(T key, ReferenceQueue<T> queue) {
|
||||
super(key, queue);
|
||||
this.hashcode = Objects.hashCode(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup unused key. No need to enqueue since the key did not make it
|
||||
* into the map.
|
||||
*/
|
||||
@Override
|
||||
public void unused() {
|
||||
clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
// Necessary when removing a null reference
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
// Necessary when comparing an unwrapped key
|
||||
if (obj instanceof ReferenceKey<?> key) {
|
||||
obj = key.get();
|
||||
}
|
||||
return Objects.equals(get(), obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// Use saved hashcode
|
||||
return hashcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.getClass().getCanonicalName() + "#" + System.identityHashCode(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link SoftReference} wrapper key for entries in the backing map.
|
||||
*
|
||||
* @param <T> key type
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
class SoftKey<T> extends SoftReference<T> implements ReferenceKey<T> {
|
||||
/**
|
||||
* Saved hashcode of the key. Used when {@link SoftReference} is
|
||||
* null.
|
||||
*/
|
||||
private final int hashcode;
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*
|
||||
* @param key unwrapped key value
|
||||
* @param queue reference queue
|
||||
*/
|
||||
SoftKey(T key, ReferenceQueue<T> queue) {
|
||||
super(key, queue);
|
||||
this.hashcode = Objects.hashCode(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup unused key. No need to enqueue since the key did not make it
|
||||
* into the map.
|
||||
*/
|
||||
@Override
|
||||
public void unused() {
|
||||
clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
// Necessary when removing a null reference
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
// Necessary when comparing an unwrapped key
|
||||
if (obj instanceof ReferenceKey<?> key) {
|
||||
obj = key.get();
|
||||
}
|
||||
return Objects.equals(get(), obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// Use saved hashcode
|
||||
return hashcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.getClass().getCanonicalName() + "#" + System.identityHashCode(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for querying the backing map. Avoids the overhead of an
|
||||
* {@link Reference} object.
|
||||
*
|
||||
* @param <T> key type
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
class StrongKey<T> implements ReferenceKey<T> {
|
||||
T key;
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*
|
||||
* @param key unwrapped key value
|
||||
*/
|
||||
StrongKey(T key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the unwrapped key}
|
||||
*/
|
||||
@Override
|
||||
public T get() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unused() {
|
||||
key = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
// Necessary when comparing an unwrapped key
|
||||
if (obj instanceof ReferenceKey<?> key) {
|
||||
obj = key.get();
|
||||
}
|
||||
return Objects.equals(get(), obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// Use unwrapped key hash code
|
||||
return get().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.getClass().getCanonicalName() + "#" + System.identityHashCode(this);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,334 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.lang.ref.Reference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* This class provides management of {@link Map maps} where it is desirable to
|
||||
* remove entries automatically when the key is garbage collected. This is
|
||||
* accomplished by using a backing map where the keys are either a
|
||||
* {@link WeakReference} or a {@link SoftReference}.
|
||||
* <p>
|
||||
* To create a {@link ReferencedKeyMap} the user must provide a {@link Supplier}
|
||||
* of the backing map and whether {@link WeakReference} or
|
||||
* {@link SoftReference} is to be used.
|
||||
*
|
||||
* {@snippet :
|
||||
* // Use HashMap and WeakReference
|
||||
* Map<Long, String> map = ReferencedKeyMap.create(false, HashMap::new);
|
||||
* map.put(10_000_000L, "a");
|
||||
* map.put(10_000_001L, "b");
|
||||
* map.put(10_000_002L, "c");
|
||||
* map.put(10_000_003L, "d");
|
||||
* map.put(10_000_004L, "e");
|
||||
*
|
||||
* // Use ConcurrentHashMap and SoftReference
|
||||
* map = ReferencedKeyMap.create(true, ConcurrentHashMap::new);
|
||||
* map.put(20_000_000L, "v");
|
||||
* map.put(20_000_001L, "w");
|
||||
* map.put(20_000_002L, "x");
|
||||
* map.put(20_000_003L, "y");
|
||||
* map.put(20_000_004L, "z");
|
||||
* }
|
||||
*
|
||||
* @implNote Care must be given that the backing map does replacement by
|
||||
* replacing the value in the map entry instead of deleting the old entry and
|
||||
* adding a new entry, otherwise replaced entries may end up with a strongly
|
||||
* referenced key. {@link HashMap} and {@link ConcurrentHashMap} are known
|
||||
* to be safe.
|
||||
*
|
||||
* @param <K> the type of keys maintained by this map
|
||||
* @param <V> the type of mapped values
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* Warning: This class is part of PreviewFeature.Feature.STRING_TEMPLATES.
|
||||
* Do not rely on its availability.
|
||||
*/
|
||||
final class ReferencedKeyMap<K, V> implements Map<K, V> {
|
||||
/**
|
||||
* true if {@link SoftReference} keys are to be used,
|
||||
* {@link WeakReference} otherwise.
|
||||
*/
|
||||
private final boolean isSoft;
|
||||
|
||||
/**
|
||||
* Backing {@link Map}.
|
||||
*/
|
||||
private final Map<ReferenceKey<K>, V> map;
|
||||
|
||||
/**
|
||||
* {@link ReferenceQueue} for cleaning up {@link ReferenceKey.WeakKey EntryKeys}.
|
||||
*/
|
||||
private final ReferenceQueue<K> stale;
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*
|
||||
* @param isSoft true if {@link SoftReference} keys are to
|
||||
* be used, {@link WeakReference} otherwise.
|
||||
* @param map backing map
|
||||
*/
|
||||
private ReferencedKeyMap(boolean isSoft, Map<ReferenceKey<K>, V> map) {
|
||||
this.isSoft = isSoft;
|
||||
this.map = map;
|
||||
this.stale = new ReferenceQueue<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link ReferencedKeyMap} map.
|
||||
*
|
||||
* @param isSoft true if {@link SoftReference} keys are to
|
||||
* be used, {@link WeakReference} otherwise.
|
||||
* @param supplier {@link Supplier} of the backing map
|
||||
*
|
||||
* @return a new map with {@link Reference} keys
|
||||
*
|
||||
* @param <K> the type of keys maintained by the new map
|
||||
* @param <V> the type of mapped values
|
||||
*/
|
||||
static <K, V> ReferencedKeyMap<K, V>
|
||||
create(boolean isSoft, Supplier<Map<ReferenceKey<K>, V>> supplier) {
|
||||
return new ReferencedKeyMap<K, V>(isSoft, supplier.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link ReferencedKeyMap} map using
|
||||
* {@link WeakReference} keys.
|
||||
*
|
||||
* @param supplier {@link Supplier} of the backing map
|
||||
*
|
||||
* @return a new map with {@link Reference} keys
|
||||
*
|
||||
* @param <K> the type of keys maintained by the new map
|
||||
* @param <V> the type of mapped values
|
||||
*/
|
||||
static <K, V> ReferencedKeyMap<K, V>
|
||||
create(Supplier<Map<ReferenceKey<K>, V>> supplier) {
|
||||
return new ReferencedKeyMap<K, V>(false, supplier.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return a key suitable for a map entry}
|
||||
*
|
||||
* @param key unwrapped key
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private ReferenceKey<K> entryKey(Object key) {
|
||||
if (isSoft) {
|
||||
return new ReferenceKey.SoftKey<>((K)key, stale);
|
||||
} else {
|
||||
return new ReferenceKey.WeakKey<>((K)key, stale);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return a key suitable for lookup}
|
||||
*
|
||||
* @param key unwrapped key
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private ReferenceKey<K> lookupKey(Object key) {
|
||||
return new ReferenceKey.StrongKey<>((K)key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
removeStaleReferences();
|
||||
return map.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
removeStaleReferences();
|
||||
return map.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsKey(Object key) {
|
||||
Objects.requireNonNull(key, "key must not be null");
|
||||
removeStaleReferences();
|
||||
return map.containsKey(lookupKey(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsValue(Object value) {
|
||||
Objects.requireNonNull(value, "value must not be null");
|
||||
removeStaleReferences();
|
||||
return map.containsValue(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public V get(Object key) {
|
||||
Objects.requireNonNull(key, "key must not be null");
|
||||
removeStaleReferences();
|
||||
return map.get(lookupKey(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public V put(K key, V newValue) {
|
||||
Objects.requireNonNull(key, "key must not be null");
|
||||
Objects.requireNonNull(newValue, "value must not be null");
|
||||
removeStaleReferences();
|
||||
ReferenceKey<K> entryKey = entryKey(key);
|
||||
// If {@code put} returns non-null then was actually a {@code replace}
|
||||
// and older key was used. In that case the new key was not used and the
|
||||
// reference marked stale.
|
||||
V oldValue = map.put(entryKey, newValue);
|
||||
if (oldValue != null) {
|
||||
entryKey.unused();
|
||||
}
|
||||
return oldValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V remove(Object key) {
|
||||
// Rely on gc to clean up old key.
|
||||
return map.remove(lookupKey(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putAll(Map<? extends K, ? extends V> m) {
|
||||
removeStaleReferences();
|
||||
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
|
||||
K key = entry.getKey();
|
||||
V value = entry.getValue();
|
||||
put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
removeStaleReferences();
|
||||
// Rely on gc to clean up old keys.
|
||||
map.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Common routine for collecting the current set of keys.
|
||||
*
|
||||
* @return {@link Stream} of valid keys (unwrapped)
|
||||
*/
|
||||
private Stream<K> filterKeySet() {
|
||||
return map.keySet()
|
||||
.stream()
|
||||
.map(ReferenceKey::get)
|
||||
.filter(Objects::nonNull);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keySet() {
|
||||
removeStaleReferences();
|
||||
return filterKeySet().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<V> values() {
|
||||
removeStaleReferences();
|
||||
return map.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Entry<K, V>> entrySet() {
|
||||
removeStaleReferences();
|
||||
return filterKeySet()
|
||||
.map(k -> new AbstractMap.SimpleEntry<>(k, get(k)))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public V putIfAbsent(K key, V newValue) {
|
||||
removeStaleReferences();
|
||||
ReferenceKey<K> entryKey = entryKey(key);
|
||||
// If {@code putIfAbsent} returns non-null then was actually a
|
||||
// {@code replace} and older key was used. In that case the new key was
|
||||
// not used and the reference marked stale.
|
||||
V oldValue = map.putIfAbsent(entryKey, newValue);
|
||||
if (oldValue != null) {
|
||||
entryKey.unused();
|
||||
}
|
||||
return oldValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object key, Object value) {
|
||||
// Rely on gc to clean up old key.
|
||||
return map.remove(lookupKey(key), value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean replace(K key, V oldValue, V newValue) {
|
||||
removeStaleReferences();
|
||||
// If replace is successful then the older key will be used and the
|
||||
// lookup key will suffice.
|
||||
return map.replace(lookupKey(key), oldValue, newValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public V replace(K key, V value) {
|
||||
removeStaleReferences();
|
||||
// If replace is successful then the older key will be used and the
|
||||
// lookup key will suffice.
|
||||
return map.replace(lookupKey(key), value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
removeStaleReferences();
|
||||
return filterKeySet()
|
||||
.map(k -> k + "=" + get(k))
|
||||
.collect(Collectors.joining(", ", "{", "}"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes enqueued weak references from map.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void removeStaleReferences() {
|
||||
while (true) {
|
||||
ReferenceKey.WeakKey<K> key = (ReferenceKey.WeakKey<K>)stale.poll();
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
map.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* This class implements specialized {@link StringTemplate StringTemplates} produced by
|
||||
* string template bootstrap method callsites generated by the compiler. Instances of this
|
||||
* class are produced by {@link StringTemplateImplFactory}.
|
||||
* <p>
|
||||
* Values are stored by subclassing {@link Carriers.CarrierObject}. This allows specializations
|
||||
* and sharing of value shapes without creating a new class for each shape.
|
||||
* <p>
|
||||
* {@link StringTemplate} fragments are shared via binding to the
|
||||
* {@link java.lang.invoke.CallSite CallSite's} {@link MethodHandle}.
|
||||
* <p>
|
||||
* The {@link StringTemplateImpl} instance also carries
|
||||
* specialized {@link MethodHandle MethodHandles} for producing the values list and interpolation.
|
||||
* These {@link MethodHandle MethodHandles} are also shared by binding to the
|
||||
* {@link java.lang.invoke.CallSite CallSite}.
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* Warning: This class is part of PreviewFeature.Feature.STRING_TEMPLATES.
|
||||
* Do not rely on its availability.
|
||||
*/
|
||||
final class StringTemplateImpl extends Carriers.CarrierObject implements StringTemplate {
|
||||
/**
|
||||
* List of string fragments for the string template. This value of this list is shared by
|
||||
* all instances created at the {@link java.lang.invoke.CallSite CallSite}.
|
||||
*/
|
||||
private final List<String> fragments;
|
||||
|
||||
/**
|
||||
* Specialized {@link MethodHandle} used to implement the {@link StringTemplate StringTemplate's}
|
||||
* {@code values} method. This {@link MethodHandle} is shared by all instances created at the
|
||||
* {@link java.lang.invoke.CallSite CallSite}.
|
||||
*/
|
||||
private final MethodHandle valuesMH;
|
||||
|
||||
/**
|
||||
* Specialized {@link MethodHandle} used to implement the {@link StringTemplate StringTemplate's}
|
||||
* {@code interpolate} method. This {@link MethodHandle} is shared by all instances created at the
|
||||
* {@link java.lang.invoke.CallSite CallSite}.
|
||||
*/
|
||||
private final MethodHandle interpolateMH;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param primitiveCount number of primitive slots required (bound at callsite)
|
||||
* @param objectCount number of object slots required (bound at callsite)
|
||||
* @param fragments list of string fragments (bound in (bound at callsite)
|
||||
* @param valuesMH {@link MethodHandle} to produce list of values (bound at callsite)
|
||||
* @param interpolateMH {@link MethodHandle} to produce interpolation (bound at callsite)
|
||||
*/
|
||||
StringTemplateImpl(int primitiveCount, int objectCount,
|
||||
List<String> fragments, MethodHandle valuesMH, MethodHandle interpolateMH) {
|
||||
super(primitiveCount, objectCount);
|
||||
this.fragments = fragments;
|
||||
this.valuesMH = valuesMH;
|
||||
this.interpolateMH = interpolateMH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> fragments() {
|
||||
return fragments;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object> values() {
|
||||
try {
|
||||
return (List<Object>)valuesMH.invokeExact(this);
|
||||
} catch (RuntimeException | Error ex) {
|
||||
throw ex;
|
||||
} catch (Throwable ex) {
|
||||
throw new RuntimeException("string template values failure", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String interpolate() {
|
||||
try {
|
||||
return (String)interpolateMH.invokeExact(this);
|
||||
} catch (RuntimeException | Error ex) {
|
||||
throw ex;
|
||||
} catch (Throwable ex) {
|
||||
throw new RuntimeException("string template interpolate failure", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof StringTemplate st &&
|
||||
Objects.equals(fragments(), st.fragments()) &&
|
||||
Objects.equals(values(), st.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(fragments(), values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return StringTemplate.toString(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,204 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.lang.invoke.StringConcatException;
|
||||
import java.lang.invoke.StringConcatFactory;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This class synthesizes {@link StringTemplate StringTemplates} based on
|
||||
* fragments and bootstrap method type. Usage is primarily from
|
||||
* {@link java.lang.runtime.TemplateRuntime}.
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* Warning: This class is part of PreviewFeature.Feature.STRING_TEMPLATES.
|
||||
* Do not rely on its availability.
|
||||
*/
|
||||
final class StringTemplateImplFactory {
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*/
|
||||
StringTemplateImplFactory() {
|
||||
throw new AssertionError("private constructor");
|
||||
}
|
||||
|
||||
/*
|
||||
* {@link StringTemplateImpl} constructor MethodHandle.
|
||||
*/
|
||||
private static final MethodHandle CONSTRUCTOR;
|
||||
|
||||
|
||||
/*
|
||||
* Frequently used method types.
|
||||
*/
|
||||
private static final MethodType MT_STRING_STIMPL =
|
||||
MethodType.methodType(String.class, StringTemplateImpl.class);
|
||||
private static final MethodType MT_LIST_STIMPL =
|
||||
MethodType.methodType(List.class, StringTemplateImpl.class);
|
||||
|
||||
/**
|
||||
* List (for nullable) of MethodHandle;
|
||||
*/
|
||||
private static final MethodHandle TO_LIST;
|
||||
|
||||
static {
|
||||
try {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
MethodType mt = MethodType.methodType(void.class, int.class, int.class, List.class,
|
||||
MethodHandle.class, MethodHandle.class);
|
||||
CONSTRUCTOR = lookup.findConstructor(StringTemplateImpl.class, mt)
|
||||
.asType(mt.changeReturnType(Carriers.CarrierObject.class));
|
||||
|
||||
mt = MethodType.methodType(List.class, Object[].class);
|
||||
TO_LIST = lookup.findStatic(StringTemplateImplFactory.class, "toList", mt);
|
||||
} catch(ReflectiveOperationException ex) {
|
||||
throw new AssertionError("carrier static init fail", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link StringTemplateImpl} constructor.
|
||||
*
|
||||
* @param fragments string template fragments
|
||||
* @param type values types with StringTemplate return
|
||||
*
|
||||
* @return {@link MethodHandle} that can construct a {@link StringTemplateImpl} with arguments
|
||||
* used as values.
|
||||
*/
|
||||
static MethodHandle createStringTemplateImplMH(List<String> fragments, MethodType type) {
|
||||
Carriers.CarrierElements elements = Carriers.CarrierFactory.of(type);
|
||||
MethodHandle[] components = elements
|
||||
.components()
|
||||
.stream()
|
||||
.map(c -> c.asType(c.type().changeParameterType(0, StringTemplateImpl.class)))
|
||||
.toArray(MethodHandle[]::new);
|
||||
Class<?>[] ptypes = elements
|
||||
.components()
|
||||
.stream()
|
||||
.map(c -> c.type().returnType())
|
||||
.toArray(Class<?>[]::new);
|
||||
int[] permute = new int[ptypes.length];
|
||||
|
||||
MethodHandle interpolateMH;
|
||||
MethodType mt;
|
||||
try {
|
||||
interpolateMH = StringConcatFactory.makeConcatWithTemplate(fragments, List.of(ptypes));
|
||||
} catch (StringConcatException ex) {
|
||||
throw new RuntimeException("constructing internal string template", ex);
|
||||
}
|
||||
interpolateMH = MethodHandles.filterArguments(interpolateMH, 0, components);
|
||||
interpolateMH = MethodHandles.permuteArguments(interpolateMH, MT_STRING_STIMPL, permute);
|
||||
|
||||
mt = MethodType.methodType(List.class, ptypes);
|
||||
MethodHandle valuesMH = TO_LIST.asCollector(Object[].class, components.length).asType(mt);
|
||||
valuesMH = MethodHandles.filterArguments(valuesMH, 0, components);
|
||||
valuesMH = MethodHandles.permuteArguments(valuesMH, MT_LIST_STIMPL, permute);
|
||||
|
||||
MethodHandle constructor = MethodHandles.insertArguments(CONSTRUCTOR, 0,
|
||||
elements.primitiveCount(), elements.objectCount(),
|
||||
fragments, valuesMH, interpolateMH);
|
||||
constructor = MethodHandles.foldArguments(elements.initializer(), 0, constructor);
|
||||
|
||||
mt = MethodType.methodType(StringTemplate.class, ptypes);
|
||||
constructor = constructor.asType(mt);
|
||||
|
||||
return constructor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic {@link StringTemplate}.
|
||||
*
|
||||
* @param fragments immutable list of string fragments from string template
|
||||
* @param values immutable list of expression values
|
||||
*/
|
||||
private record SimpleStringTemplate(List<String> fragments, List<Object> values)
|
||||
implements StringTemplate {
|
||||
@Override
|
||||
public String toString() {
|
||||
return StringTemplate.toString(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new StringTemplate composed from fragments and values.
|
||||
*
|
||||
* @param fragments array of string fragments
|
||||
* @param values array of expression values
|
||||
*
|
||||
* @return StringTemplate composed from fragments and values
|
||||
*/
|
||||
static StringTemplate newTrustedStringTemplate(String[] fragments, Object[] values) {
|
||||
return new SimpleStringTemplate(List.of(fragments), toList(values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new StringTemplate composed from fragments and values.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param values array of expression values
|
||||
*
|
||||
* @return StringTemplate composed from fragments and values
|
||||
*/
|
||||
static StringTemplate newTrustedStringTemplate(List<String> fragments, Object[] values) {
|
||||
return new SimpleStringTemplate(List.copyOf(fragments), toList(values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new StringTemplate composed from fragments and values.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param values list of expression values
|
||||
*
|
||||
* @return StringTemplate composed from fragments and values
|
||||
*/
|
||||
|
||||
static StringTemplate newStringTemplate(List<String> fragments, List<?> values) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Object> copy = (List<Object>)values.stream().toList();
|
||||
return new SimpleStringTemplate(List.copyOf(fragments), copy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect nullable elements from an array into a unmodifiable list.
|
||||
* Elements are guaranteed to be safe.
|
||||
*
|
||||
* @param elements elements to place in list
|
||||
*
|
||||
* @return unmodifiable list.
|
||||
*/
|
||||
private static List<Object> toList(Object[] elements) {
|
||||
return Arrays.stream(elements).toList();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,269 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.lang.invoke.CallSite;
|
||||
import java.lang.invoke.ConstantCallSite;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.lang.StringTemplate.Processor;
|
||||
import java.lang.StringTemplate.Processor.Linkage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import jdk.internal.access.JavaTemplateAccess;
|
||||
import jdk.internal.access.SharedSecrets;
|
||||
import jdk.internal.javac.PreviewFeature;
|
||||
|
||||
/**
|
||||
* Manages string template bootstrap methods. These methods may be used, for example,
|
||||
* by Java compiler implementations to create {@link StringTemplate} instances. For example,
|
||||
* the java compiler will translate the following code;
|
||||
* {@snippet :
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* StringTemplate st = RAW."\{x} + \{y} = \{x + y}";
|
||||
* }
|
||||
* to byte code that invokes the {@link java.lang.runtime.TemplateRuntime#newStringTemplate}
|
||||
* bootstrap method to construct a {@link CallSite} that accepts two integers and produces a new
|
||||
* {@link StringTemplate} instance.
|
||||
* {@snippet :
|
||||
* MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
* MethodType mt = MethodType.methodType(StringTemplate.class, int.class, int.class);
|
||||
* CallSite cs = TemplateRuntime.newStringTemplate(lookup, "", mt, "", " + ", " = ", "");
|
||||
* ...
|
||||
* int x = 10;
|
||||
* int y = 20;
|
||||
* StringTemplate st = (StringTemplate)cs.getTarget().invokeExact(x, y);
|
||||
* }
|
||||
* If the string template requires more than
|
||||
* {@link java.lang.invoke.StringConcatFactory#MAX_INDY_CONCAT_ARG_SLOTS} value slots,
|
||||
* then the java compiler will use the
|
||||
* {@link java.lang.runtime.TemplateRuntime#newLargeStringTemplate} bootstrap method
|
||||
* instead. For example, the java compiler will translate the following code;
|
||||
* {@snippet :
|
||||
* int[] a = new int[1000], b = new int[1000];
|
||||
* ...
|
||||
* StringTemplate st = """
|
||||
* \{a[0]} - \{b[0]}
|
||||
* \{a[1]} - \{b[1]}
|
||||
* ...
|
||||
* \{a[999]} - \{b[999]}
|
||||
* """;
|
||||
* }
|
||||
* to byte code that invokes the {@link java.lang.runtime.TemplateRuntime#newLargeStringTemplate}
|
||||
* bootstrap method to construct a {@link CallSite} that accepts an array of integers and produces a new
|
||||
* {@link StringTemplate} instance.
|
||||
* {@snippet :
|
||||
* MethodType mt = MethodType.methodType(StringTemplate.class, String[].class, Object[].class);
|
||||
* CallSite cs = TemplateRuntime.newStringTemplate(lookup, "", mt);
|
||||
* ...
|
||||
* int[] a = new int[1000], b = new int[1000];
|
||||
* ...
|
||||
* StringTemplate st = (StringTemplate)cs.getTarget().invokeExact(
|
||||
* new String[] { "", " - ", "\n", " - ", "\n", ... " - ", "\n" },
|
||||
* new Object[] { a[0], b[0], a[1], b[1], ..., a[999], b[999]}
|
||||
* );
|
||||
* }
|
||||
*
|
||||
* @since 21
|
||||
*/
|
||||
@PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
|
||||
public final class TemplateRuntime {
|
||||
private static final JavaTemplateAccess JTA = SharedSecrets.getJavaTemplateAccess();
|
||||
|
||||
/**
|
||||
* {@link MethodHandle} to {@link TemplateRuntime#defaultProcess}.
|
||||
*/
|
||||
private static final MethodHandle DEFAULT_PROCESS_MH;
|
||||
|
||||
/**
|
||||
* {@link MethodHandle} to {@link TemplateRuntime#newTrustedStringTemplate}.
|
||||
*/
|
||||
private static final MethodHandle NEW_TRUSTED_STRING_TEMPLATE;
|
||||
|
||||
/**
|
||||
* Initialize {@link MethodHandle MethodHandles}.
|
||||
*/
|
||||
static {
|
||||
try {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
MethodType mt = MethodType.methodType(Object.class,
|
||||
List.class, Processor.class, Object[].class);
|
||||
DEFAULT_PROCESS_MH =
|
||||
lookup.findStatic(TemplateRuntime.class, "defaultProcess", mt);
|
||||
|
||||
mt = MethodType.methodType(StringTemplate.class, String[].class, Object[].class);
|
||||
NEW_TRUSTED_STRING_TEMPLATE =
|
||||
lookup.findStatic(StringTemplateImplFactory.class, "newTrustedStringTemplate", mt);
|
||||
} catch (ReflectiveOperationException ex) {
|
||||
throw new AssertionError("string bootstrap fail", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*/
|
||||
private TemplateRuntime() {
|
||||
throw new AssertionError("private constructor");
|
||||
}
|
||||
|
||||
/**
|
||||
* String template bootstrap method for creating string templates.
|
||||
* The static arguments include the fragments list.
|
||||
* The non-static arguments are the values.
|
||||
*
|
||||
* @param lookup method lookup from call site
|
||||
* @param name method name - not used
|
||||
* @param type method type
|
||||
* (ptypes...) -> StringTemplate
|
||||
* @param fragments fragment array for string template
|
||||
*
|
||||
* @return {@link CallSite} to handle create string template
|
||||
*
|
||||
* @throws NullPointerException if any of the arguments is null
|
||||
* @throws Throwable if linkage fails
|
||||
*/
|
||||
public static CallSite newStringTemplate(MethodHandles.Lookup lookup,
|
||||
String name,
|
||||
MethodType type,
|
||||
String... fragments) throws Throwable {
|
||||
Objects.requireNonNull(lookup, "lookup is null");
|
||||
Objects.requireNonNull(name, "name is null");
|
||||
Objects.requireNonNull(type, "type is null");
|
||||
Objects.requireNonNull(fragments, "fragments is null");
|
||||
|
||||
MethodHandle mh = StringTemplateImplFactory
|
||||
.createStringTemplateImplMH(List.of(fragments), type).asType(type);
|
||||
|
||||
return new ConstantCallSite(mh);
|
||||
}
|
||||
|
||||
/**
|
||||
* String template bootstrap method for creating large string templates,
|
||||
* i.e., when the number of value slots exceeds
|
||||
* {@link java.lang.invoke.StringConcatFactory#MAX_INDY_CONCAT_ARG_SLOTS}.
|
||||
* The non-static arguments are the fragments array and values array.
|
||||
*
|
||||
* @param lookup method lookup from call site
|
||||
* @param name method name - not used
|
||||
* @param type method type
|
||||
* (String[], Object[]) -> StringTemplate
|
||||
*
|
||||
* @return {@link CallSite} to handle create large string template
|
||||
*
|
||||
* @throws NullPointerException if any of the arguments is null
|
||||
* @throws Throwable if linkage fails
|
||||
*/
|
||||
public static CallSite newLargeStringTemplate(MethodHandles.Lookup lookup,
|
||||
String name,
|
||||
MethodType type) throws Throwable {
|
||||
Objects.requireNonNull(lookup, "lookup is null");
|
||||
Objects.requireNonNull(name, "name is null");
|
||||
Objects.requireNonNull(type, "type is null");
|
||||
|
||||
return new ConstantCallSite(NEW_TRUSTED_STRING_TEMPLATE.asType(type));
|
||||
}
|
||||
|
||||
/**
|
||||
* String template bootstrap method for static final processors.
|
||||
* The static arguments include the fragments array and a {@link MethodHandle}
|
||||
* to retrieve the value of the static final processor.
|
||||
* The non-static arguments are the values.
|
||||
*
|
||||
* @param lookup method lookup from call site
|
||||
* @param name method name - not used
|
||||
* @param type method type
|
||||
* (ptypes...) -> Object
|
||||
* @param processorGetter {@link MethodHandle} to get static final processor
|
||||
* @param fragments fragments from string template
|
||||
*
|
||||
* @return {@link CallSite} to handle string template processing
|
||||
*
|
||||
* @throws NullPointerException if any of the arguments is null
|
||||
* @throws Throwable if linkage fails
|
||||
*
|
||||
* @implNote this method is likely to be revamped before exiting preview.
|
||||
*/
|
||||
public static CallSite processStringTemplate(MethodHandles.Lookup lookup,
|
||||
String name,
|
||||
MethodType type,
|
||||
MethodHandle processorGetter,
|
||||
String... fragments) throws Throwable {
|
||||
Objects.requireNonNull(lookup, "lookup is null");
|
||||
Objects.requireNonNull(name, "name is null");
|
||||
Objects.requireNonNull(type, "type is null");
|
||||
Objects.requireNonNull(processorGetter, "processorGetter is null");
|
||||
Objects.requireNonNull(fragments, "fragments is null");
|
||||
|
||||
Processor<?, ?> processor = (Processor<?, ?>)processorGetter.invoke();
|
||||
MethodHandle mh = processor instanceof Linkage linkage
|
||||
? linkage.linkage(List.of(fragments), type)
|
||||
: defaultProcessMethodHandle(type, processor, List.of(fragments));
|
||||
|
||||
return new ConstantCallSite(mh);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a simple {@link StringTemplate} and then invokes the processor's process method.
|
||||
*
|
||||
* @param fragments fragments from string template
|
||||
* @param processor {@link Processor} to process
|
||||
* @param values array of expression values
|
||||
*
|
||||
* @return result of processing the string template
|
||||
*
|
||||
* @throws Throwable when {@link Processor#process(StringTemplate)} throws
|
||||
*/
|
||||
private static Object defaultProcess(
|
||||
List<String> fragments,
|
||||
Processor<?, ?> processor,
|
||||
Object[] values
|
||||
) throws Throwable {
|
||||
return processor.process(StringTemplate.of(fragments, Arrays.stream(values).toList()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a {@link MethodHandle} which is effectively invokes
|
||||
* {@code processor.process(new StringTemplate(fragments, values...)}.
|
||||
*
|
||||
* @return default process {@link MethodHandle}
|
||||
*/
|
||||
private static MethodHandle defaultProcessMethodHandle(
|
||||
MethodType type,
|
||||
Processor<?, ?> processor,
|
||||
List<String> fragments
|
||||
) {
|
||||
MethodHandle mh = MethodHandles.insertArguments(DEFAULT_PROCESS_MH, 0, fragments, processor);
|
||||
return mh.asCollector(Object[].class, type.parameterCount()).asType(type);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package java.lang.runtime;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import jdk.internal.access.JavaLangAccess;
|
||||
import jdk.internal.access.JavaTemplateAccess;
|
||||
import jdk.internal.access.SharedSecrets;
|
||||
|
||||
/**
|
||||
* This class provides runtime support for string templates. The methods within
|
||||
* are intended for internal use only.
|
||||
*
|
||||
* @since 21
|
||||
*
|
||||
* Warning: This class is part of PreviewFeature.Feature.STRING_TEMPLATES.
|
||||
* Do not rely on its availability.
|
||||
*/
|
||||
final class TemplateSupport implements JavaTemplateAccess {
|
||||
|
||||
/**
|
||||
* Private constructor.
|
||||
*/
|
||||
private TemplateSupport() {
|
||||
}
|
||||
|
||||
static {
|
||||
SharedSecrets.setJavaTemplateAccess(new TemplateSupport());
|
||||
}
|
||||
|
||||
private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
|
||||
|
||||
/**
|
||||
* Returns a StringTemplate composed from fragments and values.
|
||||
*
|
||||
* @implSpec The {@code fragments} list size must be one more that the
|
||||
* {@code values} list size.
|
||||
*
|
||||
* @param fragments list of string fragments
|
||||
* @param values list of expression values
|
||||
*
|
||||
* @return StringTemplate composed from fragments and values
|
||||
*
|
||||
* @throws IllegalArgumentException if fragments list size is not one more
|
||||
* than values list size
|
||||
* @throws NullPointerException if fragments is null or values is null or if any fragment is null.
|
||||
*
|
||||
* @implNote Contents of both lists are copied to construct immutable lists.
|
||||
*/
|
||||
@Override
|
||||
public StringTemplate of(List<String> fragments, List<?> values) {
|
||||
return StringTemplateImplFactory.newStringTemplate(fragments, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a string that interleaves the elements of values between the
|
||||
* elements of fragments.
|
||||
*
|
||||
* @param fragments list of String fragments
|
||||
* @param values list of expression values
|
||||
*
|
||||
* @return String interpolation of fragments and values
|
||||
*/
|
||||
@Override
|
||||
public String interpolate(List<String> fragments, List<?> values) {
|
||||
int fragmentsSize = fragments.size();
|
||||
int valuesSize = values.size();
|
||||
if (fragmentsSize == 1) {
|
||||
return fragments.get(0);
|
||||
}
|
||||
int size = fragmentsSize + valuesSize;
|
||||
String[] strings = new String[size];
|
||||
int i = 0, j = 0;
|
||||
for (; j < valuesSize; j++) {
|
||||
strings[i++] = fragments.get(j);
|
||||
strings[i++] = String.valueOf(values.get(j));
|
||||
}
|
||||
strings[i] = fragments.get(j);
|
||||
return JLA.join("", "", "", strings, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine one or more {@link StringTemplate StringTemplates} to produce a combined {@link StringTemplate}.
|
||||
* {@snippet :
|
||||
* StringTemplate st = StringTemplate.combine("\{a}", "\{b}", "\{c}");
|
||||
* assert st.interpolate().equals("\{a}\{b}\{c}");
|
||||
* }
|
||||
*
|
||||
* @param sts zero or more {@link StringTemplate}
|
||||
*
|
||||
* @return combined {@link StringTemplate}
|
||||
*
|
||||
* @throws NullPointerException if sts is null or if any element of sts is null
|
||||
*/
|
||||
@Override
|
||||
public StringTemplate combine(StringTemplate... sts) {
|
||||
Objects.requireNonNull(sts, "sts must not be null");
|
||||
if (sts.length == 0) {
|
||||
return StringTemplate.of("");
|
||||
} else if (sts.length == 1) {
|
||||
return Objects.requireNonNull(sts[0], "string templates should not be null");
|
||||
}
|
||||
int size = 0;
|
||||
for (StringTemplate st : sts) {
|
||||
Objects.requireNonNull(st, "string templates should not be null");
|
||||
size += st.values().size();
|
||||
}
|
||||
String[] combinedFragments = new String[size + 1];
|
||||
Object[] combinedValues = new Object[size];
|
||||
combinedFragments[0] = "";
|
||||
int fragmentIndex = 1;
|
||||
int valueIndex = 0;
|
||||
for (StringTemplate st : sts) {
|
||||
Iterator<String> iterator = st.fragments().iterator();
|
||||
combinedFragments[fragmentIndex - 1] += iterator.next();
|
||||
while (iterator.hasNext()) {
|
||||
combinedFragments[fragmentIndex++] = iterator.next();
|
||||
}
|
||||
for (Object value : st.values()) {
|
||||
combinedValues[valueIndex++] = value;
|
||||
}
|
||||
}
|
||||
return StringTemplateImplFactory.newTrustedStringTemplate(combinedFragments, combinedValues);
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue