File: StringTemplateTest.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (308 lines) | stat: -rw-r--r-- 13,553 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
 * 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.
 *
 * 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.
 */

/*
 * @test
 * @bug 0000000
 * @summary Exercise runtime handing of templated strings.
 * @enablePreview true
 */

import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.*;
import java.util.function.Supplier;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
import javax.tools.ToolProvider;

public class StringTemplateTest {
    enum Category{GENERAL, CHARACTER, INTEGRAL, BIG_INT, FLOATING, BIG_FLOAT, DATE};

    static final String[] GENERAL = {"true", "false", "(Object)null", "STR", "BO", "BOOL", "(Boolean)null"};
    static final String[] CHARS = {"C", "CHAR", "(Character)null"};
    static final String[] INTS = {"L", "LONG", "I", "INT", "S", "SHORT", "BY", "BYTE", "Long.MAX_VALUE", "Long.MIN_VALUE", "(Long)null", "(Integer)null", "(Short)null", "(Byte)null"};
    static final String[] BIGINTS = {};
    static final String[] FLOATS = {"F", "FLOAT", "D", "DOUBLE", "Double.NEGATIVE_INFINITY", "Double.NaN", "Double.MAX_VALUE", "(Double)null", "(Float)null"};
    static final String[] BIGFLOATS = {};
    static final String[] DATES = {};

    final Random r = new Random(1);

    String randomValue(Category category) {
        return switch (category) {
            case GENERAL -> randomChoice(
                    GENERAL,
                    () -> randomValue(Category.CHARACTER),
                    () -> randomValue(Category.INTEGRAL),
                    () -> randomValue(Category.BIG_INT),
                    () -> randomValue(Category.FLOATING),
                    () -> randomValue(Category.BIG_FLOAT),
                    () -> randomValue(Category.DATE),
                    () -> "\"" + randomString(r.nextInt(10)) + "\"");
            case CHARACTER -> randomChoice(
                    CHARS,
                    () -> "\'" + randomString(1) + "\'");
            case INTEGRAL -> randomChoice(
                    INTS,
                    () -> "(byte)" + String.valueOf(r.nextInt(Byte.MIN_VALUE, Byte.MAX_VALUE)),
                    () -> "(short)" + String.valueOf(r.nextInt(Short.MIN_VALUE, Short.MAX_VALUE)),
                    () -> String.valueOf(r.nextInt()),
                    () -> r.nextLong() + "l");
            case BIG_INT -> randomChoice(
                    BIGINTS,
                    () -> "new java.math.BigInteger(\"" + r.nextLong() + "\")");
            case FLOATING -> randomChoice(
                    FLOATS,
                    () -> String.valueOf(r.nextDouble()),
                    () -> r.nextFloat() + "f");
            case BIG_FLOAT -> randomChoice(
                    BIGFLOATS,
                    () -> "new java.math.BigDecimal(" + r.nextDouble() + ")");
            case DATE -> randomChoice(
                    DATES,
                    () -> "new java.util.Date(" + r.nextLong() + "l)",
                    () -> r.nextLong() + "l");
        };
    }

    String randomChoice(Supplier<String>... suppl) {
        return suppl[r.nextInt(suppl.length)].get();
    }

    String randomChoice(String... values) {
        return values[r.nextInt(values.length)];
    }

    String randomChoice(String[] values, Supplier<String>... suppl) {
        int i = r.nextInt(values.length + suppl.length);
        return i < values.length ? values[i] : suppl[i - values.length].get();
    }

    String randomString(int length) {
        var sb = new StringBuilder(length << 2);
        while (length-- > 0) {
            char ch = (char)r.nextInt(9, 128);
            var s = switch (ch) {
                case '\t' -> "\\t";
                case '\'' -> "\\\'";
                case '"' -> "\\\"";
                case '\r' -> "\\r";
                case '\\' -> "\\\\";
                case '\n' -> "\\n";
                case '\f' -> "\\f";
                case '\b' -> "\\b";
                default -> ch + "";
            };
            sb.append(s);
        }
        return sb.toString();
    }

    String randomFormat(Category category) {
        char c;
        return "%" + switch (category) {
            case GENERAL -> randomWidth("-") + randomPrecision() + randomChar("bBhHsS");
            case CHARACTER -> randomWidth("-") + randomChar("cC");
            case INTEGRAL -> switch (c = randomChar("doxX")) {
                case 'd' -> randomFlags("+ ,(");
                default -> randomFlags("");
            } + randomWidth("-0") + c;
            case BIG_INT -> switch (c = randomChar("doxX")) {
                case 'd' -> randomFlags("+ ,(");
                default -> randomFlags("+ (");
            } + randomWidth("-0") + c;
            case FLOATING -> switch (c = randomChar("eEfaAgG")) {
                case 'a', 'A' -> randomFlags("+ ") + randomWidth("-0");
                case 'e', 'E' -> randomFlags("+ (") + randomWidth("-0") + randomPrecision();
                default -> randomFlags("+ ,(") + randomWidth("-0") + randomPrecision();
            } + c;
            case BIG_FLOAT -> switch (c = randomChar("eEfgG")) {
                case 'e', 'E' -> randomFlags("+ (") + randomWidth("-0") + randomPrecision();
                default -> randomFlags("+ ,(") + randomWidth("-0") + randomPrecision();
            } + c;
            case DATE ->  randomWidth("-") + randomChar("tT") + randomChar("BbhAaCYyjmdeRTrDFc");
        };
    }

    String randomFlags(String flags) {
        var sb = new StringBuilder(flags.length());
        for (var f : flags.toCharArray()) {
            if (r.nextBoolean() && (f != ' ' || sb.length() == 0 || sb.charAt(sb.length() - 1) != '+')) sb.append(f);
        }
        return sb.toString();
    }

    char randomChar(String chars) {
        return chars.charAt(r.nextInt(chars.length()));
    }

    String randomWidth(String flags) {
        var f = r.nextInt(flags.length() + 1);
        return r.nextBoolean() ? (r.nextBoolean() ? flags.charAt(r.nextInt(flags.length())) : "") + String.valueOf(r.nextInt(10) + 1) : "";
    }

    String randomPrecision() {
        return r.nextBoolean() ? '.' + String.valueOf(r.nextInt(10) + 1) : "";
    }

    public Class<?> compile() throws Exception {
        var classes = new HashMap<String, byte[]>();
        var fileManager = new ForwardingJavaFileManager(ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null)) {
            @Override
            public ClassLoader getClassLoader(JavaFileManager.Location location) {
                return new ClassLoader() {
                    @Override
                    public Class<?> loadClass(String name) throws ClassNotFoundException {
                        try {
                            return super.loadClass(name);
                        } catch (ClassNotFoundException e) {
                            byte[] classData = classes.get(name);
                            return defineClass(name, classData, 0, classData.length);
                        }
                    }
                };
            }
            @Override
            public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String name, JavaFileObject.Kind kind, FileObject originatingSource) throws UnsupportedOperationException {
                return new SimpleJavaFileObject(URI.create(name + ".class"), JavaFileObject.Kind.CLASS) {
                    @Override
                    public OutputStream openOutputStream() {
                        return new FilterOutputStream(new ByteArrayOutputStream()) {
                            @Override
                            public void close() throws IOException {
                                classes.put(name, ((ByteArrayOutputStream)out).toByteArray());
                            }
                        };
                    }
                };
            }
        };
        var source = genSource();
//        System.out.println(source);
        if (ToolProvider.getSystemJavaCompiler().getTask(null, fileManager, null,
                List.of("--enable-preview", "-source", String.valueOf(Runtime.version().feature())), null,
                List.of(new SimpleJavaFileObject(URI.create("StringTemplateTest$.java"), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return source;
            }
        })).call()) {
            return fileManager.getClassLoader(CLASS_OUTPUT).loadClass("StringTemplateTest$");
        } else {
            throw new AssertionError("compilation failed");
        }
    }

    String genFragments(Category c) {
        var fragments = new LinkedList<String>();
        for (int i = 0; i < 1500; i++) {
            var format = randomFormat(c);
            var value = randomValue(c);
            var qValue = value.replace("\\", "\\\\").replace("\"", "\\\"");
            fragments.add(STR."test(FMT.\"\{format}\\{\{value}}\", \"\{format}\", \"\{qValue}\", \{value}, log);");
        }
        return String.join("\n        ", fragments);
    }

    String genSource() {
        return STR."""
            import java.util.FormatProcessor;
            import java.util.Locale;

            public class StringTemplateTest$ {
                static final FormatProcessor FMT = FormatProcessor.create(Locale.US);
                static String STR = "this is static String";
                static char C = 'c';
                static Character CHAR = 'C';
                static long L = -12345678910l;
                static Long LONG = 9876543210l;
                static int I = 42;
                static Integer INT = -49;
                static boolean BO = true;
                static Boolean BOOL = false;
                static short S = 13;
                static Short SHORT = -17;
                static byte BY = -3;
                static Byte BYTE = 12;
                static float F = 4.789f;
                static Float FLOAT = -0.000006f;
                static double D = 6545745.6734654563;
                static Double DOUBLE = -4323.7645676574;

                public static void run(java.util.List<String> log) {
                    runGeneral(log);
                    runCharacter(log);
                    runIntegral(log);
                    runBigInt(log);
                    runFloating(log);
                    runBigFloat(log);
                    runDate(log);
                }
                public static void runGeneral(java.util.List<String> log) {
                    \{genFragments(Category.GENERAL)}
                }
                public static void runCharacter(java.util.List<String> log) {
                    \{genFragments(Category.CHARACTER)}
                }
                public static void runIntegral(java.util.List<String> log) {
                    \{genFragments(Category.INTEGRAL)}
                }
                public static void runBigInt(java.util.List<String> log) {
                    \{genFragments(Category.BIG_INT)}
                }
                public static void runFloating(java.util.List<String> log) {
                    \{genFragments(Category.FLOATING)}
                }
                public static void runBigFloat(java.util.List<String> log) {
                    \{genFragments(Category.BIG_FLOAT)}
                }
                public static void runDate(java.util.List<String> log) {
                    \{genFragments(Category.DATE)}
                }
                static void test(String fmt, String format, String expression, Object value, java.util.List<String> log) {
                    var formatted = String.format(java.util.Locale.US, format, value);
                    if (!fmt.equals(formatted)) {
                        log.add("  format: '%s' expression: '%s' value: '%s' expected: '%s' found: '%s'".formatted(format, expression, value, formatted, fmt));
                    }
                }
            }
            """;
    }

    public static void main(String... args) throws Exception {
        var log = new LinkedList<String>();
        new StringTemplateTest().compile().getMethod("run", List.class).invoke(null, log);
        if (!log.isEmpty()) {
            log.forEach(System.out::println);
            throw new AssertionError(STR."failed \{log.size()} tests");
        }
    }
}