View Javadoc
1   package io.jawk.jrt;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * Jawk
6    * ჻჻჻჻჻჻
7    * Copyright (C) 2006 - 2026 MetricsHub
8    * ჻჻჻჻჻჻
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   *
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   *
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23   */
24  
25  import java.math.BigDecimal;
26  import java.math.BigInteger;
27  import java.math.MathContext;
28  import java.math.RoundingMode;
29  import java.text.DecimalFormatSymbols;
30  import java.util.ArrayList;
31  import java.util.Arrays;
32  import java.util.IllegalFormatException;
33  import java.util.List;
34  import java.util.Locale;
35  import java.util.concurrent.ConcurrentHashMap;
36  
37  /**
38   * AWK's {@code printf}/{@code sprintf} formatting engine.
39   * <p>
40   * This class implements the POSIX AWK formatting semantics (as implemented by
41   * gawk), which differ from both C's {@code printf()} and
42   * {@link java.lang.String#format(String, Object...)} in several ways:
43   * </p>
44   * <ul>
45   * <li>{@code %s} converts numeric values to strings with AWK's number-to-string
46   * rules: integral values are printed without a fractional part, and other
47   * values are formatted with {@code CONVFMT};</li>
48   * <li>{@code %c} prints the character for a numeric code point, or the first
49   * character of a string value;</li>
50   * <li>{@code %i} is an alias for {@code %d}, and {@code %u} prints the value
51   * as an unsigned 64-bit integer;</li>
52   * <li>dynamic field width and precision ({@code *}) consume arguments, and
53   * gawk-style positional specifiers ({@code %n$}) are honored;</li>
54   * <li>integer conversions of values that exceed the 64-bit range fall back to
55   * the full decimal expansion ({@code %d}/{@code %i}) or {@code %g} notation
56   * ({@code %u}/{@code %o}/{@code %x}/{@code %X}), like gawk;</li>
57   * <li>NaN and infinities print as {@code nan}, {@code inf}, and {@code -inf};</li>
58   * <li>{@code %e}, {@code %f}, and {@code %g} round halfway cases to even, like
59   * the C library used by gawk;</li>
60   * <li>unknown conversion specifiers are printed verbatim without consuming an
61   * argument, and a fatal {@link AwkRuntimeException} is raised when there are
62   * not enough arguments to satisfy the format string.</li>
63   * </ul>
64   * <p>
65   * This formatting logic was originally externalized in the
66   * <a href="https://github.com/metricshub/printf4j">Printf4J</a> project, which
67   * emulated glibc's {@code printf()}. It has been reincorporated into Jawk and
68   * adapted to AWK's semantics.
69   * </p>
70   */
71  public final class AwkPrintf {
72  
73  	/** Default AWK number-to-string conversion format ({@code CONVFMT}). */
74  	public static final String DEFAULT_CONVFMT = "%.6g";
75  
76  	/** Conversion characters recognized as AWK format specifiers. */
77  	private static final String CONVERSION_CHARS = "diouxXeEfFgGaAcs";
78  
79  	/** Length modifier characters accepted (and ignored) like gawk. */
80  	private static final String LENGTH_MODIFIERS = "hjlLtz";
81  
82  	/** A one-character string holding the NUL character, printed by {@code %c} for empty values. */
83  	private static final String NUL_STRING = Character.toString((char) 0);
84  
85  	/** 2^63 as a double, the first value beyond the signed 64-bit range. */
86  	private static final double TWO_POW_63 = 9.223372036854775808e18;
87  
88  	/** 2^64 as a {@link BigInteger}, used for unsigned wrapping checks. */
89  	private static final BigInteger TWO_POW_64 = BigInteger.ONE.shiftLeft(64);
90  
91  	/** No width or precision operand in the specifier. */
92  	private static final int OPERAND_NONE = 0;
93  
94  	/** Width or precision given as literal digits in the format string. */
95  	private static final int OPERAND_FIXED = 1;
96  
97  	/** Width or precision given as {@code *}, consuming a sequential argument. */
98  	private static final int OPERAND_STAR = 2;
99  
100 	/** Width or precision given as {@code *n$}, referencing a positional argument. */
101 	private static final int OPERAND_STAR_POSITIONAL = 3;
102 
103 	/** Shared flag set with every flag cleared, for segments that ignore flags. */
104 	private static final Flags NO_FLAGS = new Flags(false, false, false, false, false, false);
105 
106 	/** Maximum number of parsed format strings kept in {@link #FORMAT_CACHE}. */
107 	private static final int FORMAT_CACHE_LIMIT = 256;
108 
109 	/**
110 	 * Cache of parsed format strings. Parsing depends only on the format text,
111 	 * not on the locale or the arguments, and AWK programs typically reuse a
112 	 * handful of format strings (including {@code CONVFMT}) for every record.
113 	 */
114 	private static final ConcurrentHashMap<String, Segment[]> FORMAT_CACHE = new ConcurrentHashMap<String, Segment[]>();
115 
116 	/** Maximum number of locales kept in {@link #LOCALE_SYMBOLS_CACHE}. */
117 	private static final int LOCALE_SYMBOLS_CACHE_LIMIT = 64;
118 
119 	/**
120 	 * Per-locale decimal and grouping separator characters.
121 	 * {@link DecimalFormatSymbols#getInstance(Locale)} clones the symbols on
122 	 * every call, which is far too expensive to repeat for every conversion.
123 	 */
124 	private static final ConcurrentHashMap<Locale, LocaleSymbols> LOCALE_SYMBOLS_CACHE = new ConcurrentHashMap<Locale, LocaleSymbols>();
125 
126 	private AwkPrintf() {
127 		throw new UnsupportedOperationException();
128 	}
129 
130 	/**
131 	 * Formats the given arguments with AWK's {@code sprintf()} semantics, using
132 	 * {@link Locale#US} and the default {@code CONVFMT} ({@code "%.6g"}).
133 	 *
134 	 * @param format AWK format string
135 	 * @param args arguments supplied after the format string
136 	 * @return the formatted text
137 	 * @throws AwkRuntimeException when there are not enough arguments to
138 	 *         satisfy the format string
139 	 */
140 	public static String sprintf(final String format, final Object... args) {
141 		return sprintf(Locale.US, DEFAULT_CONVFMT, format, args);
142 	}
143 
144 	/**
145 	 * Formats the given arguments with AWK's {@code sprintf()} semantics.
146 	 *
147 	 * @param locale locale used for numeric formatting (decimal separator,
148 	 *        grouping separator for the {@code '} flag)
149 	 * @param convfmt number-to-string conversion format ({@code CONVFMT}) used
150 	 *        by {@code %s} for non-integral numeric values
151 	 * @param format AWK format string
152 	 * @param args arguments supplied after the format string
153 	 * @return the formatted text
154 	 * @throws AwkRuntimeException when there are not enough arguments to
155 	 *         satisfy the format string
156 	 */
157 	public static String sprintf(final Locale locale, final String convfmt, final String format, final Object... args) {
158 		Locale actualLocale = locale == null ? Locale.US : locale;
159 		// An explicitly empty CONVFMT stays empty, like gawk; only a null
160 		// (absent) format selects the default.
161 		String actualConvfmt = convfmt == null ? DEFAULT_CONVFMT : convfmt;
162 		Object[] actualArgs = args == null ? new Object[0] : args;
163 		return new AwkPrintfFormatter(actualLocale, actualConvfmt, format, actualArgs).format();
164 	}
165 
166 	/**
167 	 * Converts a value to a string using AWK's number-to-string rules.
168 	 * <p>
169 	 * Non-numeric values are converted with {@code toString()}. Numeric values
170 	 * holding an integral value are printed without a fractional part (using
171 	 * the full decimal expansion when the value exceeds the 64-bit range), NaN
172 	 * and infinities print as {@code nan}, {@code inf}, and {@code -inf}, and
173 	 * all other numeric values are formatted with the supplied conversion
174 	 * format ({@code CONVFMT} or {@code OFMT}).
175 	 * </p>
176 	 *
177 	 * @param value value to convert
178 	 * @param conversionFormat number-to-string conversion format
179 	 * @param locale locale used for numeric formatting
180 	 * @return the AWK string value of {@code value}
181 	 */
182 	public static String toAwkString(final Object value, final String conversionFormat, final Locale locale) {
183 		if (value == null) {
184 			return "";
185 		}
186 		if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) {
187 			// Preserve exact 64-bit values that a double round-trip would corrupt.
188 			return Long.toString(((Number) value).longValue());
189 		}
190 		if (!(value instanceof Number)) {
191 			return value.toString();
192 		}
193 		return numberToAwkString(((Number) value).doubleValue(), conversionFormat, locale);
194 	}
195 
196 	private static String numberToAwkString(final double number, final String conversionFormat, final Locale locale) {
197 		if (Double.isNaN(number)) {
198 			return "nan";
199 		}
200 		if (Double.isInfinite(number)) {
201 			return number > 0 ? "inf" : "-inf";
202 		}
203 		if (JRT.isActuallyLong(number)) {
204 			double rounded = Math.rint(number);
205 			if (rounded >= -TWO_POW_63 && rounded < TWO_POW_63) {
206 				return Long.toString((long) rounded);
207 			}
208 			// The exact binary value of the double is intended: it makes rounding match gawk's C library.
209 			return new BigDecimal(rounded).toBigInteger().toString(); // NOPMD
210 		}
211 		// An explicitly empty CONVFMT/OFMT stays empty, like gawk; only a
212 		// null (absent) format selects the default.
213 		String fmt = conversionFormat == null ? DEFAULT_CONVFMT : conversionFormat;
214 		return sprintf(locale, DEFAULT_CONVFMT, fmt, Double.valueOf(number));
215 	}
216 
217 	/**
218 	 * Immutable set of conversion flags parsed from one format specifier.
219 	 */
220 	private static final class Flags {
221 
222 		private final boolean leftJustify;
223 		private final boolean plusSign;
224 		private final boolean spaceSign;
225 		private final boolean zeroPad;
226 		private final boolean alternate;
227 		private final boolean grouping;
228 
229 		Flags(boolean leftJustify, boolean plusSign, boolean spaceSign, boolean zeroPad, boolean alternate,
230 				boolean grouping) {
231 			this.leftJustify = leftJustify;
232 			this.plusSign = plusSign;
233 			this.spaceSign = spaceSign;
234 			this.zeroPad = zeroPad;
235 			this.alternate = alternate;
236 			this.grouping = grouping;
237 		}
238 
239 		/**
240 		 * Returns these flags with the {@code '} grouping flag cleared, for
241 		 * conversions that gawk never groups (octal and hexadecimal).
242 		 *
243 		 * @return an equivalent flag set without grouping
244 		 */
245 		Flags withoutGrouping() {
246 			return grouping ? new Flags(leftJustify, plusSign, spaceSign, zeroPad, alternate, false) : this;
247 		}
248 
249 		/**
250 		 * Returns these flags with the {@code -} flag set, as a negative
251 		 * dynamic field width requires.
252 		 *
253 		 * @return an equivalent flag set with left justification
254 		 */
255 		Flags withLeftJustify() {
256 			return leftJustify ? this : new Flags(true, plusSign, spaceSign, zeroPad, alternate, grouping);
257 		}
258 	}
259 
260 	/**
261 	 * Decimal and grouping separator characters of one locale.
262 	 */
263 	private static final class LocaleSymbols {
264 
265 		private final char decimalSeparator;
266 		private final char groupingSeparator;
267 
268 		LocaleSymbols(char decimalSeparator, char groupingSeparator) {
269 			this.decimalSeparator = decimalSeparator;
270 			this.groupingSeparator = groupingSeparator;
271 		}
272 	}
273 
274 	/**
275 	 * One parsed piece of a format string: either verbatim text or one
276 	 * conversion specifier. Segments are immutable and shared between all
277 	 * calls using the same format string, so rendering replays argument
278 	 * consumption, argument-mode tracking, and fatal parse errors in exactly
279 	 * the order the previous single-pass implementation produced them.
280 	 */
281 	private static final class Segment {
282 
283 		/** Verbatim text to append, or {@code null} for a conversion. */
284 		private final String literal;
285 
286 		/** Positional ({@code n$}) argument index, or 0 for sequential. */
287 		private final int argPosition;
288 
289 		private final Flags flags;
290 
291 		/** Width operand kind, one of the {@code OPERAND_*} constants. */
292 		private final int widthKind;
293 
294 		/** Fixed width value, or the {@code *n$} width argument position. */
295 		private final int width;
296 
297 		/** Precision operand kind, one of the {@code OPERAND_*} constants. */
298 		private final int precisionKind;
299 
300 		/** Fixed precision value, or the {@code *n$} precision argument position. */
301 		private final int precision;
302 
303 		/** Conversion character, or {@code '\0'} for literal segments. */
304 		private final char conversion;
305 
306 		/**
307 		 * Fatal parse error raised when rendering reaches this segment (after
308 		 * the width operand has consumed its argument), or {@code null}.
309 		 */
310 		private final String parseError;
311 
312 		Segment(String literal, int argPosition, Flags flags, int widthKind, int width, int precisionKind, int precision,
313 				char conversion, String parseError) {
314 			this.literal = literal;
315 			this.argPosition = argPosition;
316 			this.flags = flags;
317 			this.widthKind = widthKind;
318 			this.width = width;
319 			this.precisionKind = precisionKind;
320 			this.precision = precision;
321 			this.conversion = conversion;
322 			this.parseError = parseError;
323 		}
324 	}
325 
326 	/**
327 	 * Returns the decimal and grouping separators of the given locale, from a
328 	 * bounded cache.
329 	 */
330 	private static LocaleSymbols localeSymbolsFor(Locale locale) {
331 		LocaleSymbols symbols = LOCALE_SYMBOLS_CACHE.get(locale);
332 		if (symbols == null) {
333 			DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
334 			symbols = new LocaleSymbols(dfs.getDecimalSeparator(), dfs.getGroupingSeparator());
335 			if (LOCALE_SYMBOLS_CACHE.size() >= LOCALE_SYMBOLS_CACHE_LIMIT) {
336 				LOCALE_SYMBOLS_CACHE.clear();
337 			}
338 			LOCALE_SYMBOLS_CACHE.putIfAbsent(locale, symbols);
339 		}
340 		return symbols;
341 	}
342 
343 	/**
344 	 * Returns the parsed form of the given format string, from a bounded
345 	 * cache.
346 	 */
347 	private static Segment[] compiledFormat(String format) {
348 		Segment[] segments = FORMAT_CACHE.get(format);
349 		if (segments == null) {
350 			segments = compileFormat(format);
351 			if (FORMAT_CACHE.size() >= FORMAT_CACHE_LIMIT) {
352 				// Rare: a program cycling through many generated format
353 				// strings. Dropping the whole cache keeps the bound simple
354 				// and the hit path lock-free.
355 				FORMAT_CACHE.clear();
356 			}
357 			Segment[] winner = FORMAT_CACHE.putIfAbsent(format, segments);
358 			if (winner != null) {
359 				return winner;
360 			}
361 		}
362 		return segments;
363 	}
364 
365 	/**
366 	 * Parses a format string into segments. This method never throws: fatal
367 	 * parse errors are recorded as error segments so that rendering raises
368 	 * them only once every preceding conversion has consumed its arguments,
369 	 * preserving the error precedence of single-pass processing.
370 	 */
371 	private static Segment[] compileFormat(String format) {
372 		List<Segment> segments = new ArrayList<Segment>();
373 		StringBuilder literal = new StringBuilder();
374 		int length = format.length();
375 		int i = 0;
376 		while (i < length) {
377 			char c = format.charAt(i);
378 			if (c != '%') {
379 				literal.append(c);
380 				i++;
381 				continue;
382 			}
383 			if (i + 1 >= length) {
384 				// Dangling '%' at the end of the format: print it verbatim.
385 				literal.append('%');
386 				break;
387 			}
388 			if (format.charAt(i + 1) == '%') {
389 				literal.append('%');
390 				i += 2;
391 				continue;
392 			}
393 			i = compileSpecifier(format, i, segments, literal);
394 			if (i < 0) {
395 				// A fatal parse error segment was emitted; the rest of the
396 				// format string is unreachable.
397 				break;
398 			}
399 		}
400 		flushLiteral(segments, literal);
401 		return segments.toArray(new Segment[0]);
402 	}
403 
404 	/**
405 	 * Parses one format specifier starting at {@code start} (which points at
406 	 * the {@code '%'}), emitting segments, and returns the index of the first
407 	 * character after the specifier, or a negative value when a fatal parse
408 	 * error segment was emitted.
409 	 */
410 	private static int compileSpecifier(String format, int start, List<Segment> segments, StringBuilder literal) {
411 		int length = format.length();
412 		int i = start + 1;
413 
414 		// gawk-style positional specifier: %n$...
415 		int argPosition = 0;
416 		int digitsEnd = i;
417 		while (digitsEnd < length && isAsciiDigit(format.charAt(digitsEnd))) {
418 			digitsEnd++;
419 		}
420 		if (digitsEnd > i && digitsEnd < length && format.charAt(digitsEnd) == '$') {
421 			argPosition = parseInt(format, i, digitsEnd);
422 			if (argPosition <= 0) {
423 				emitError(segments, literal, OPERAND_NONE, 0, "argument index with `$' must be > 0 in `" + format + "'");
424 				return -1;
425 			}
426 			i = digitsEnd + 1;
427 		}
428 
429 		// Flags, in any order and possibly repeated.
430 		boolean leftJustify = false;
431 		boolean plusSign = false;
432 		boolean spaceSign = false;
433 		boolean zeroPad = false;
434 		boolean alternate = false;
435 		boolean grouping = false;
436 		flagLoop: while (i < length) {
437 			switch (format.charAt(i)) {
438 			case '-':
439 				leftJustify = true;
440 				break;
441 			case '+':
442 				plusSign = true;
443 				break;
444 			case ' ':
445 				spaceSign = true;
446 				break;
447 			case '0':
448 				zeroPad = true;
449 				break;
450 			case '#':
451 				alternate = true;
452 				break;
453 			case '\'':
454 				grouping = true;
455 				break;
456 			default:
457 				break flagLoop;
458 			}
459 			i++;
460 		}
461 
462 		// Field width: digits, or '*' (optionally '*n$').
463 		int widthKind = OPERAND_NONE;
464 		int width = -1;
465 		if (i < length && format.charAt(i) == '*') {
466 			i++;
467 			int starArgEnd = starPositionEnd(format, i);
468 			if (starArgEnd == i && i < length && isAsciiDigit(format.charAt(i))) {
469 				// Digits after a star operand not terminated by '$' are
470 				// fatal rather than literal, like gawk: "%*2d".
471 				emitError(
472 						segments,
473 						literal,
474 						OPERAND_NONE,
475 						0,
476 						"no `$' supplied for positional field width or precision in `" + format + "'");
477 				return -1;
478 			}
479 			if (starArgEnd > i) {
480 				widthKind = OPERAND_STAR_POSITIONAL;
481 				width = parseInt(format, i, starArgEnd - 1);
482 				i = starArgEnd;
483 			} else {
484 				widthKind = OPERAND_STAR;
485 			}
486 		} else {
487 			int widthEnd = i;
488 			while (widthEnd < length && isAsciiDigit(format.charAt(widthEnd))) {
489 				widthEnd++;
490 			}
491 			if (widthEnd > i) {
492 				widthKind = OPERAND_FIXED;
493 				width = parseInt(format, i, widthEnd);
494 				i = widthEnd;
495 			}
496 		}
497 
498 		// Precision: '.' followed by digits (empty means 0), or '.*'.
499 		int precisionKind = OPERAND_NONE;
500 		int precision = -1;
501 		if (i < length && format.charAt(i) == '.') {
502 			i++;
503 			if (i < length && format.charAt(i) == '*') {
504 				i++;
505 				int starArgEnd = starPositionEnd(format, i);
506 				if (starArgEnd == i && i < length && isAsciiDigit(format.charAt(i))) {
507 					// The width operand (if any) still consumes its argument
508 					// before this error is raised, like gawk: "%*.*2d".
509 					emitError(
510 							segments,
511 							literal,
512 							widthKind,
513 							width,
514 							"no `$' supplied for positional field width or precision in `" + format + "'");
515 					return -1;
516 				}
517 				if (starArgEnd > i) {
518 					precisionKind = OPERAND_STAR_POSITIONAL;
519 					precision = parseInt(format, i, starArgEnd - 1);
520 					i = starArgEnd;
521 				} else {
522 					precisionKind = OPERAND_STAR;
523 				}
524 			} else {
525 				int precisionEnd = i;
526 				while (precisionEnd < length && isAsciiDigit(format.charAt(precisionEnd))) {
527 					precisionEnd++;
528 				}
529 				precisionKind = OPERAND_FIXED;
530 				precision = precisionEnd == i ? 0 : parseInt(format, i, precisionEnd);
531 				i = precisionEnd;
532 			}
533 		}
534 
535 		// Length modifiers (h, j, l, L, t, z) are each accepted at most
536 		// once and ignored, like gawk. A repeated modifier such as "ll"
537 		// or "hh" makes the whole specifier invalid, also like gawk.
538 		int modifierMask = 0;
539 		while (i < length) {
540 			int modifierIndex = LENGTH_MODIFIERS.indexOf(format.charAt(i));
541 			if (modifierIndex < 0 || (modifierMask & 1 << modifierIndex) != 0) {
542 				break;
543 			}
544 			modifierMask |= 1 << modifierIndex;
545 			i++;
546 		}
547 
548 		if (i < length && format.charAt(i) == '%') {
549 			// A percent conversion reached through flags, width, or
550 			// precision prints a plain '%' and ignores them all, like
551 			// gawk ("%5%" prints "%"). Star operands still consume their
552 			// arguments, and an explicit position still pins the format to
553 			// positional mode, also like gawk.
554 			emitVerbatim(
555 					segments,
556 					literal,
557 					new Segment("%", argPosition, NO_FLAGS, widthKind, width, precisionKind, precision, (char) 0, null));
558 			return i + 1;
559 		}
560 
561 		if (i >= length || CONVERSION_CHARS.indexOf(format.charAt(i)) < 0) {
562 			// Unknown or unterminated conversion: print the specifier
563 			// verbatim (including the offending character) without
564 			// consuming a value argument, like gawk. Star operands still
565 			// consume their arguments, and an explicit position still pins
566 			// the format to positional mode, also like gawk.
567 			int end = i < length ? i + 1 : length;
568 			emitVerbatim(
569 					segments,
570 					literal,
571 					new Segment(
572 							format.substring(start, end),
573 							argPosition,
574 							NO_FLAGS,
575 							widthKind,
576 							width,
577 							precisionKind,
578 							precision,
579 							(char) 0,
580 							null));
581 			return end;
582 		}
583 
584 		char conversion = format.charAt(i);
585 		i++;
586 
587 		flushLiteral(segments, literal);
588 		segments.add(
589 				new Segment(
590 						null,
591 						argPosition,
592 						new Flags(leftJustify, plusSign, spaceSign, zeroPad, alternate, grouping),
593 						widthKind,
594 						width,
595 						precisionKind,
596 						precision,
597 						conversion,
598 						null));
599 		return i;
600 	}
601 
602 	/**
603 	 * Emits verbatim specifier text (a {@code %} conversion or an unknown
604 	 * conversion). When the specifier has no side effects (no star operand to
605 	 * consume, no positional index to validate), the text is merged into the
606 	 * pending literal run; otherwise a standalone segment replays those side
607 	 * effects before appending the text.
608 	 */
609 	private static void emitVerbatim(List<Segment> segments, StringBuilder literal, Segment segment) {
610 		boolean sideEffectFree = segment.argPosition == 0
611 				&& segment.widthKind != OPERAND_STAR
612 				&& segment.widthKind != OPERAND_STAR_POSITIONAL
613 				&& segment.precisionKind != OPERAND_STAR
614 				&& segment.precisionKind != OPERAND_STAR_POSITIONAL;
615 		if (sideEffectFree) {
616 			literal.append(segment.literal);
617 			return;
618 		}
619 		flushLiteral(segments, literal);
620 		segments.add(segment);
621 	}
622 
623 	/**
624 	 * Emits a fatal parse error segment, preceded by any width operand whose
625 	 * argument consumption must be replayed before the error is raised.
626 	 */
627 	private static void emitError(
628 			List<Segment> segments,
629 			StringBuilder literal,
630 			int widthKind,
631 			int width,
632 			String message) {
633 		flushLiteral(segments, literal);
634 		segments.add(new Segment(null, 0, NO_FLAGS, widthKind, width, OPERAND_NONE, -1, (char) 0, message));
635 	}
636 
637 	/** Emits the pending literal text run as a segment, if any. */
638 	private static void flushLiteral(List<Segment> segments, StringBuilder literal) {
639 		if (literal.length() > 0) {
640 			segments.add(new Segment(literal.toString(), 0, NO_FLAGS, OPERAND_NONE, -1, OPERAND_NONE, -1, (char) 0, null));
641 			literal.setLength(0);
642 		}
643 	}
644 
645 	/**
646 	 * Returns the index right after a {@code n$} sequence starting at
647 	 * {@code i}, or {@code i} when there is no such sequence.
648 	 */
649 	private static int starPositionEnd(String format, int i) {
650 		int length = format.length();
651 		int digitsEnd = i;
652 		while (digitsEnd < length && isAsciiDigit(format.charAt(digitsEnd))) {
653 			digitsEnd++;
654 		}
655 		if (digitsEnd > i && digitsEnd < length && format.charAt(digitsEnd) == '$') {
656 			return digitsEnd + 1;
657 		}
658 		return i;
659 	}
660 
661 	/**
662 	 * Stateful renderer for one {@code sprintf()} call, walking the parsed
663 	 * segments of the format string.
664 	 */
665 	private static final class AwkPrintfFormatter {
666 
667 		private final Locale locale;
668 		private final String convfmt;
669 		private final String format;
670 		private final Object[] args;
671 		private final StringBuilder out;
672 		private final char decimalSeparator;
673 		private final char groupingSeparator;
674 
675 		/** Index of the next sequential argument to consume. */
676 		private int argIndex;
677 
678 		/** Whether a positional ({@code n$}) argument reference was seen. */
679 		private boolean sawPositional;
680 
681 		/** Whether a sequential argument reference was seen. */
682 		private boolean sawSequential;
683 
684 		AwkPrintfFormatter(Locale locale, String convfmt, String format, Object[] args) {
685 			this.locale = locale;
686 			this.convfmt = convfmt;
687 			this.format = format;
688 			this.args = args;
689 			this.out = new StringBuilder(format.length() + 16);
690 			LocaleSymbols symbols = localeSymbolsFor(locale);
691 			this.decimalSeparator = symbols.decimalSeparator;
692 			this.groupingSeparator = symbols.groupingSeparator;
693 		}
694 
695 		String format() {
696 			for (Segment segment : compiledFormat(format)) {
697 				renderSegment(segment);
698 			}
699 			return out.toString();
700 		}
701 
702 		/**
703 		 * Renders one segment: evaluates the width and precision operands
704 		 * (consuming their arguments), raises any recorded parse error, and
705 		 * appends the literal text or the converted value.
706 		 */
707 		private void renderSegment(Segment segment) {
708 			Flags flags = segment.flags;
709 			int width = -1;
710 			if (segment.widthKind != OPERAND_NONE) {
711 				if (segment.widthKind == OPERAND_FIXED) {
712 					width = segment.width;
713 				} else {
714 					long dynamicWidth;
715 					if (segment.widthKind == OPERAND_STAR) {
716 						// A sequential star operand pins the format to
717 						// sequential mode; an explicitly positioned one is
718 						// neutral.
719 						recordArgumentMode(false);
720 						dynamicWidth = (long) JRT.toDouble(nextArg());
721 					} else {
722 						// gawk treats a zero-indexed star operand ("%*0$d")
723 						// as the value zero, without consuming an argument.
724 						dynamicWidth = segment.width == 0 ? 0 : (long) JRT.toDouble(argAt(segment.width));
725 					}
726 					if (dynamicWidth < 0) {
727 						flags = flags.withLeftJustify();
728 						dynamicWidth = -dynamicWidth;
729 					}
730 					width = (int) Math.min(dynamicWidth, Integer.MAX_VALUE);
731 				}
732 			}
733 			if (segment.parseError != null) {
734 				throw new AwkRuntimeException(segment.parseError);
735 			}
736 			int precision = -1;
737 			if (segment.precisionKind != OPERAND_NONE) {
738 				if (segment.precisionKind == OPERAND_FIXED) {
739 					precision = segment.precision;
740 				} else {
741 					long dynamicPrecision;
742 					if (segment.precisionKind == OPERAND_STAR) {
743 						// Same sequential-mode tracking as the width operand.
744 						recordArgumentMode(false);
745 						dynamicPrecision = (long) JRT.toDouble(nextArg());
746 					} else {
747 						// Same zero-index rule as the width operand.
748 						dynamicPrecision = segment.precision == 0 ? 0 : (long) JRT.toDouble(argAt(segment.precision));
749 					}
750 					// A negative dynamic precision means "no precision" in C.
751 					if (dynamicPrecision >= 0) {
752 						precision = (int) Math.min(dynamicPrecision, Integer.MAX_VALUE);
753 					}
754 				}
755 			}
756 			if (segment.literal != null) {
757 				// Verbatim text; a positional specifier still pins the format
758 				// to positional mode and validates its index, like gawk.
759 				if (segment.argPosition > 0) {
760 					recordArgumentMode(true);
761 					requireArgumentIndex(segment.argPosition);
762 				}
763 				out.append(segment.literal);
764 				return;
765 			}
766 			recordArgumentMode(segment.argPosition > 0);
767 			Object arg = segment.argPosition > 0 ? argAt(segment.argPosition) : nextArg();
768 			render(segment.conversion, flags, width, precision, arg);
769 		}
770 
771 		private Object nextArg() {
772 			if (argIndex >= args.length) {
773 				throw new AwkRuntimeException("not enough arguments to satisfy format string `" + format + "'");
774 			}
775 			return args[argIndex++];
776 		}
777 
778 		private Object argAt(int position) {
779 			requireArgumentIndex(position);
780 			return args[position - 1];
781 		}
782 
783 		/**
784 		 * Validates a positional ({@code n$}) argument index against the
785 		 * supplied arguments, like gawk, which checks the index even for
786 		 * conversions that do not consume the referenced value.
787 		 */
788 		private void requireArgumentIndex(int position) {
789 			if (position <= 0) {
790 				throw new AwkRuntimeException("argument index with `$' must be > 0 in `" + format + "'");
791 			}
792 			if (position > args.length) {
793 				throw new AwkRuntimeException(
794 						"argument index " + position + " greater than total number of supplied arguments in `" + format + "'");
795 			}
796 		}
797 
798 		/**
799 		 * Records how one conversion selects its value argument and rejects
800 		 * format strings that mix positional ({@code n$}) and sequential
801 		 * conversions, like gawk. Star width and precision operands are not
802 		 * tracked: gawk allows an explicitly positioned star operand
803 		 * ({@code %*2$s}) alongside sequential conversions.
804 		 *
805 		 * @param positional whether the conversion used an {@code n$} index
806 		 */
807 		private void recordArgumentMode(boolean positional) {
808 			if (positional) {
809 				sawPositional = true;
810 			} else {
811 				sawSequential = true;
812 			}
813 			if (sawPositional && sawSequential) {
814 				throw new AwkRuntimeException("must use `count$' on all formats or none in `" + format + "'");
815 			}
816 		}
817 
818 		private void render(char conversion, Flags flags, int width, int precision, Object arg) {
819 			switch (conversion) {
820 			case 'c':
821 				appendPadded(characterOf(arg), flags.leftJustify, false, width);
822 				break;
823 			case 's':
824 				String s = toAwkString(arg, convfmt, locale);
825 				if (precision >= 0 && s.codePointCount(0, s.length()) > precision) {
826 					// The precision counts characters (code points), so it
827 					// can never split a surrogate pair.
828 					s = s.substring(0, s.offsetByCodePoints(0, precision));
829 				}
830 				appendPadded(s, flags.leftJustify, false, width);
831 				break;
832 			case 'd':
833 			case 'i':
834 				renderSignedInteger(flags, width, precision, arg);
835 				break;
836 			case 'u':
837 			case 'o':
838 			case 'x':
839 			case 'X':
840 				renderUnsignedInteger(conversion, flags, width, precision, arg);
841 				break;
842 			case 'e':
843 			case 'E':
844 			case 'f':
845 			case 'F':
846 			case 'g':
847 			case 'G':
848 			case 'a':
849 			case 'A':
850 				renderFloat(conversion, flags, width, precision, arg);
851 				break;
852 			default:
853 				// Unreachable: the caller only passes known conversions.
854 				break;
855 			}
856 		}
857 
858 		/** Renders the {@code %c} character for the given argument. */
859 		private String characterOf(Object arg) {
860 			if (arg == null) {
861 				return NUL_STRING;
862 			}
863 			boolean numeric = arg instanceof Number || (arg instanceof StrNum && ((StrNum) arg).isNumber());
864 			if (numeric) {
865 				long code = (long) JRT.toDouble(arg);
866 				StringBuilder sb = new StringBuilder(2);
867 				if (code >= 0 && code <= Character.MAX_CODE_POINT) {
868 					sb.appendCodePoint((int) code);
869 				} else {
870 					sb.append((char) code);
871 				}
872 				return sb.toString();
873 			}
874 			String s = arg.toString();
875 			if (s.isEmpty()) {
876 				return NUL_STRING;
877 			}
878 			StringBuilder sb = new StringBuilder(2);
879 			sb.appendCodePoint(s.codePointAt(0));
880 			return sb.toString();
881 		}
882 
883 		private void renderSignedInteger(Flags flags, int width, int precision, Object arg) {
884 			double d = JRT.toDouble(arg);
885 			if (renderNonFinite('d', flags, width, d)) {
886 				return;
887 			}
888 
889 			boolean negative;
890 			String magnitude;
891 			if (arg instanceof Long || arg instanceof Integer || arg instanceof Short || arg instanceof Byte) {
892 				long v = ((Number) arg).longValue();
893 				negative = v < 0;
894 				magnitude = negative ? Long.toUnsignedString(-v) : Long.toString(v);
895 			} else if (d >= -TWO_POW_63 && d < TWO_POW_63) {
896 				long v = (long) d;
897 				negative = v < 0;
898 				magnitude = negative ? Long.toUnsignedString(-v) : Long.toString(v);
899 			} else {
900 				// Out of 64-bit range: print the full decimal expansion of the
901 				// (integral) double, like gawk.
902 				// The exact binary value of the double is intended: it makes rounding match gawk's C library.
903 				BigInteger bi = new BigDecimal(d).toBigInteger(); // NOPMD
904 				negative = bi.signum() < 0;
905 				magnitude = bi.abs().toString();
906 			}
907 
908 			String sign = negative ? "-" : flags.plusSign ? "+" : flags.spaceSign ? " " : "";
909 			appendInteger(sign, "", magnitude, flags, width, precision, isZeroMagnitude(magnitude));
910 		}
911 
912 		private void renderUnsignedInteger(char conversion, Flags flags, int width, int precision, Object arg) {
913 			double d = JRT.toDouble(arg);
914 			if (renderNonFinite(conversion, flags, width, d)) {
915 				return;
916 			}
917 
918 			int radix = conversion == 'o' ? 8 : conversion == 'u' ? 10 : 16;
919 			String magnitude;
920 			if (arg instanceof Long || arg instanceof Integer || arg instanceof Short || arg instanceof Byte) {
921 				magnitude = Long.toUnsignedString(((Number) arg).longValue(), radix);
922 			} else if (d >= -TWO_POW_63 && d < TWO_POW_63) {
923 				magnitude = Long.toUnsignedString((long) d, radix);
924 			} else {
925 				// The exact binary value of the double is intended: it makes rounding match gawk's C library.
926 				BigInteger bi = new BigDecimal(d).toBigInteger(); // NOPMD
927 				if (bi.signum() >= 0 && bi.compareTo(TWO_POW_64) < 0) {
928 					magnitude = bi.toString(radix);
929 				} else {
930 					// Out of the unsigned 64-bit range: fall back to %g
931 					// notation with the original sign, flags, precision, and
932 					// width, like gawk.
933 					renderFloat('g', flags, width, precision, Double.valueOf(d));
934 					return;
935 				}
936 			}
937 			if (conversion == 'X') {
938 				magnitude = magnitude.toUpperCase(Locale.ROOT);
939 			}
940 
941 			boolean zeroValue = d == 0;
942 			boolean zeroMagnitude = isZeroMagnitude(magnitude);
943 			int actualPrecision = precision;
944 			if (zeroMagnitude && precision == 0 && (flags.alternate || !zeroValue)) {
945 				// gawk prints "0" rather than nothing for a zero magnitude
946 				// with an explicit zero precision when the '#' flag is given,
947 				// or when the original value is nonzero and merely truncates
948 				// to zero.
949 				actualPrecision = 1;
950 			}
951 			// The '#' prefix depends on the original value, not the truncated
952 			// magnitude: gawk prints "0x0" for %#.0x with 0.1. For %o, gawk
953 			// always adds the alternate leading zero in addition to any
954 			// precision padding: %#.5o of 1 prints "000001".
955 			String prefix = "";
956 			if (flags.alternate && !zeroValue) {
957 				if (conversion == 'x') {
958 					prefix = "0x";
959 				} else if (conversion == 'X') {
960 					prefix = "0X";
961 				} else if (conversion == 'o') {
962 					prefix = "0";
963 				}
964 			}
965 			// gawk's ' flag groups decimal output only, never octal or
966 			// hexadecimal.
967 			Flags integerFlags = conversion == 'u' ? flags : flags.withoutGrouping();
968 			appendInteger("", prefix, magnitude, integerFlags, width, actualPrecision, zeroMagnitude);
969 		}
970 
971 		/**
972 		 * Applies precision, grouping, and width to an integer body and
973 		 * appends it to the output.
974 		 */
975 		private void appendInteger(
976 				String sign,
977 				String prefix,
978 				String magnitude,
979 				Flags flags,
980 				int width,
981 				int precision,
982 				boolean zeroMagnitude) {
983 			String digits = magnitude;
984 			if (precision == 0 && zeroMagnitude) {
985 				// C: a zero value with an explicit zero precision prints no
986 				// characters. gawk drops the sign flags as well.
987 				appendPadded("", flags.leftJustify, false, width);
988 				return;
989 			}
990 			if (precision > digits.length()) {
991 				digits = zeros(precision - digits.length()) + digits;
992 			}
993 			if (flags.grouping) {
994 				digits = groupDigits(digits);
995 			}
996 			String body = sign + prefix + digits;
997 			if (width > body.length() && flags.zeroPad && !flags.leftJustify && precision < 0) {
998 				// Zero padding goes between the sign/prefix and the digits.
999 				out.append(sign).append(prefix);
1000 				out.append(zeros(width - body.length()));
1001 				out.append(digits);
1002 				return;
1003 			}
1004 			appendPadded(body, flags.leftJustify, false, width);
1005 		}
1006 
1007 		private void renderFloat(char conversion, Flags flags, int width, int precision, Object arg) {
1008 			double d = JRT.toDouble(arg);
1009 			if (renderNonFinite(conversion, flags, width, d)) {
1010 				return;
1011 			}
1012 			String magnitude = floatBody(conversion, flags, precision, d);
1013 			if (magnitude == null) {
1014 				return;
1015 			}
1016 			boolean negative = d < 0 || (d == 0 && Double.doubleToRawLongBits(d) != 0L);
1017 			String sign = negative ? "-" : flags.plusSign ? "+" : flags.spaceSign ? " " : "";
1018 			// The hexadecimal prefix of %a/%A stays ahead of any zero padding,
1019 			// like an integer prefix.
1020 			String prefix = "";
1021 			if (magnitude.startsWith("0x") || magnitude.startsWith("0X")) {
1022 				prefix = magnitude.substring(0, 2);
1023 				magnitude = magnitude.substring(2);
1024 			}
1025 			String full = sign + prefix + magnitude;
1026 			if (width > full.length() && flags.zeroPad && !flags.leftJustify) {
1027 				out.append(sign).append(prefix);
1028 				out.append(zeros(width - full.length()));
1029 				out.append(magnitude);
1030 				return;
1031 			}
1032 			appendPadded(full, flags.leftJustify, false, width);
1033 		}
1034 
1035 		/**
1036 		 * Renders the digits of a finite double for a floating-point
1037 		 * conversion, without sign and without width padding: the absolute
1038 		 * value is formatted and the caller applies the sign.
1039 		 */
1040 		private String floatBody(char conversion, Flags flags, int precision, double d) {
1041 			double abs = Math.abs(d);
1042 			switch (conversion) {
1043 			case 'f':
1044 			case 'F': {
1045 				int p = precision < 0 ? 6 : precision;
1046 				String s = decimalString(roundHalfEvenToScale(abs, p));
1047 				if (flags.alternate && p == 0) {
1048 					s = forceDecimalSeparator(s);
1049 				}
1050 				if (flags.grouping) {
1051 					s = groupDigits(s);
1052 				}
1053 				return s;
1054 			}
1055 			case 'e':
1056 			case 'E': {
1057 				int p = precision < 0 ? 6 : precision;
1058 				String s = scientific(abs, p);
1059 				if (flags.alternate && p == 0) {
1060 					int exponentStart = s.indexOf('e');
1061 					s = forceDecimalSeparator(s.substring(0, exponentStart)) + s.substring(exponentStart);
1062 				}
1063 				return conversion == 'E' ? s.toUpperCase(Locale.ROOT) : s;
1064 			}
1065 			case 'g':
1066 			case 'G': {
1067 				int p = precision < 0 ? 6 : precision == 0 ? 1 : precision;
1068 				String s = generalFloat(abs, p, flags.alternate, flags.grouping);
1069 				return conversion == 'G' ? s.toUpperCase(Locale.ROOT) : s;
1070 			}
1071 			case 'a':
1072 			case 'A':
1073 			default: {
1074 				// %a is C-library dependent in gawk; delegate to Java's
1075 				// hexadecimal float notation.
1076 				StringBuilder spec = new StringBuilder("%");
1077 				if (precision >= 0) {
1078 					spec.append('.').append(precision);
1079 				}
1080 				spec.append(conversion);
1081 				try {
1082 					String s = String.format(locale, spec.toString(), Double.valueOf(abs));
1083 					return s;
1084 				} catch (IllegalFormatException e) {
1085 					out.append(spec);
1086 					return null;
1087 				}
1088 			}
1089 			}
1090 		}
1091 
1092 		/** Formats {@code abs >= 0} in C's {@code %e} notation. */
1093 		private String scientific(double abs, int precision) {
1094 			BigDecimal mantissa;
1095 			int exponent;
1096 			if (abs == 0) {
1097 				mantissa = BigDecimal.ZERO.setScale(precision);
1098 				exponent = 0;
1099 			} else {
1100 				BigDecimal rounded = roundHalfEvenToSignificant(abs, precision + 1);
1101 				exponent = rounded.precision() - rounded.scale() - 1;
1102 				mantissa = rounded.movePointLeft(exponent).setScale(precision, RoundingMode.UNNECESSARY);
1103 			}
1104 			return decimalString(mantissa) + "e" + (exponent < 0 ? "-" : "+") + exponentDigits(Math.abs(exponent));
1105 		}
1106 
1107 		/** Formats {@code abs >= 0} in C's {@code %g} notation. */
1108 		private String generalFloat(double abs, int precision, boolean alternate, boolean grouping) {
1109 			if (abs == 0) {
1110 				return alternate ? forceDecimalSeparator("0") + zeros(precision - 1) : "0";
1111 			}
1112 			BigDecimal rounded = roundHalfEvenToSignificant(abs, precision);
1113 			int exponent = rounded.precision() - rounded.scale() - 1;
1114 			if (exponent >= -4 && exponent < precision) {
1115 				String s = decimalString(rounded.setScale(precision - 1 - exponent, RoundingMode.UNNECESSARY));
1116 				s = alternate ? forceDecimalSeparator(s) : stripTrailingFractionZeros(s);
1117 				// gawk groups %g in fixed notation, like %f, but never in
1118 				// exponential notation.
1119 				return grouping ? groupDigits(s) : s;
1120 			}
1121 			String mantissa = decimalString(
1122 					rounded.movePointLeft(exponent).setScale(precision - 1, RoundingMode.UNNECESSARY));
1123 			mantissa = alternate ? forceDecimalSeparator(mantissa) : stripTrailingFractionZeros(mantissa);
1124 			return mantissa + "e" + (exponent < 0 ? "-" : "+") + exponentDigits(Math.abs(exponent));
1125 		}
1126 
1127 		/**
1128 		 * Renders NaN and infinities for any numeric conversion, honoring the
1129 		 * sign flags and field width, and returns {@code true} when the value
1130 		 * was such a special value.
1131 		 */
1132 		private boolean renderNonFinite(char conversion, Flags flags, int width, double d) {
1133 			if (!Double.isNaN(d) && !Double.isInfinite(d)) {
1134 				return false;
1135 			}
1136 			String body;
1137 			if (Double.isNaN(d)) {
1138 				body = flags.plusSign ? "+nan" : flags.spaceSign ? " nan" : "nan";
1139 			} else if (d > 0) {
1140 				body = flags.plusSign ? "+inf" : flags.spaceSign ? " inf" : "inf";
1141 			} else {
1142 				body = "-inf";
1143 			}
1144 			if (isUpperCaseConversion(conversion)) {
1145 				body = body.toUpperCase(Locale.ROOT);
1146 			}
1147 			// The zero flag is ignored for non-finite values, like C.
1148 			appendPadded(body, flags.leftJustify, false, width);
1149 			return true;
1150 		}
1151 
1152 		/** Renders a {@link BigDecimal} using the locale's decimal separator. */
1153 		private String decimalString(BigDecimal value) {
1154 			String s = value.toPlainString();
1155 			return decimalSeparator == '.' ? s : s.replace('.', decimalSeparator);
1156 		}
1157 
1158 		/** Inserts locale grouping separators into the integer part of {@code s}. */
1159 		private String groupDigits(String s) {
1160 			int end = s.indexOf(decimalSeparator);
1161 			if (end < 0) {
1162 				end = s.length();
1163 			}
1164 			StringBuilder sb = new StringBuilder(s.length() + 8);
1165 			for (int i = 0; i < end; i++) {
1166 				sb.append(s.charAt(i));
1167 				int remaining = end - 1 - i;
1168 				if (remaining > 0 && remaining % 3 == 0 && isAsciiDigit(s.charAt(i))) {
1169 					sb.append(groupingSeparator);
1170 				}
1171 			}
1172 			sb.append(s, end, s.length());
1173 			return sb.toString();
1174 		}
1175 
1176 		/**
1177 		 * Appends the locale decimal separator when {@code s} has none, as
1178 		 * the '#' flag requires for {@code %g} results without fractional
1179 		 * digits.
1180 		 */
1181 		private String forceDecimalSeparator(String s) {
1182 			return s.indexOf(decimalSeparator) < 0 ? s + decimalSeparator : s;
1183 		}
1184 
1185 		private String stripTrailingFractionZeros(String s) {
1186 			if (s.indexOf(decimalSeparator) < 0) {
1187 				return s;
1188 			}
1189 			int end = s.length();
1190 			while (end > 0 && s.charAt(end - 1) == '0') {
1191 				end--;
1192 			}
1193 			if (end > 0 && s.charAt(end - 1) == decimalSeparator) {
1194 				end--;
1195 			}
1196 			return s.substring(0, end);
1197 		}
1198 
1199 		private void appendPadded(String body, boolean leftJustify, boolean zeroPad, int width) {
1200 			// The field width counts characters (code points), so that a
1201 			// supplementary character fills one column, not two.
1202 			int bodyLength = body.codePointCount(0, body.length());
1203 			if (width <= bodyLength) {
1204 				out.append(body);
1205 				return;
1206 			}
1207 			int padLength = width - bodyLength;
1208 			if (leftJustify) {
1209 				out.append(body);
1210 				appendSpaces(padLength);
1211 			} else if (zeroPad) {
1212 				out.append(zeros(padLength)).append(body);
1213 			} else {
1214 				appendSpaces(padLength);
1215 				out.append(body);
1216 			}
1217 		}
1218 
1219 		private void appendSpaces(int count) {
1220 			out.append(repeat(' ', count));
1221 		}
1222 	}
1223 
1224 	/**
1225 	 * Rounds the exact binary value of {@code abs} to {@code scale} fractional
1226 	 * digits with {@link RoundingMode#HALF_EVEN}, producing exactly the same
1227 	 * result as {@code new BigDecimal(abs).setScale(scale, HALF_EVEN)}.
1228 	 * <p>
1229 	 * When the shortest decimal representation of {@code abs} provably rounds
1230 	 * to the same value (see {@link #roundsLikeExact}), it is used instead of
1231 	 * the exact expansion, which is much cheaper for values like {@code 0.1}
1232 	 * whose exact binary expansion has dozens or hundreds of digits.
1233 	 * </p>
1234 	 */
1235 	private static BigDecimal roundHalfEvenToScale(double abs, int scale) {
1236 		BigDecimal shortest = shortestDecimal(abs);
1237 		if (shortest != null && roundsLikeExact(abs, shortest, shortest.scale() - scale, -scale)) {
1238 			return shortest.setScale(scale, RoundingMode.HALF_EVEN);
1239 		}
1240 		// The exact binary value of the double is intended: it makes rounding match gawk's C library.
1241 		return new BigDecimal(abs).setScale(scale, RoundingMode.HALF_EVEN); // NOPMD
1242 	}
1243 
1244 	/**
1245 	 * Rounds the exact binary value of {@code abs} to {@code digits}
1246 	 * significant digits with {@link RoundingMode#HALF_EVEN}, producing a
1247 	 * result numerically equal to
1248 	 * {@code new BigDecimal(abs).round(new MathContext(digits, HALF_EVEN))}.
1249 	 */
1250 	private static BigDecimal roundHalfEvenToSignificant(double abs, int digits) {
1251 		if (digits > 0) {
1252 			BigDecimal shortest = shortestDecimal(abs);
1253 			if (shortest != null) {
1254 				// Decimal exponent of the rounding unit: eS - digits + 1,
1255 				// where eS = precision - scale - 1.
1256 				int unitExponent = shortest.precision() - shortest.scale() - digits;
1257 				if (roundsLikeExact(abs, shortest, shortest.precision() - digits, unitExponent)) {
1258 					return shortest.round(new MathContext(digits, RoundingMode.HALF_EVEN));
1259 				}
1260 			}
1261 		}
1262 		// The exact binary value of the double is intended: it makes rounding match gawk's C library.
1263 		return new BigDecimal(abs).round(new MathContext(digits, RoundingMode.HALF_EVEN)); // NOPMD
1264 	}
1265 
1266 	/**
1267 	 * Returns the shortest decimal representation of {@code abs}, or
1268 	 * {@code null} when {@code abs} is zero, subnormal, or non-finite (those
1269 	 * always take the exact path).
1270 	 */
1271 	private static BigDecimal shortestDecimal(double abs) {
1272 		if (!(abs >= Double.MIN_NORMAL) || abs > Double.MAX_VALUE) {
1273 			return null;
1274 		}
1275 		return new BigDecimal(Double.toString(abs));
1276 	}
1277 
1278 	/**
1279 	 * Decides whether rounding the shortest decimal representation of
1280 	 * {@code abs} at the position of the unit {@code 10^unitExponent}
1281 	 * provably yields the same value as rounding the exact binary expansion.
1282 	 * <p>
1283 	 * The exact value differs from the shortest representation by at most
1284 	 * half an ulp (the shortest representation parses back to the same
1285 	 * double). Requiring the rounding unit to exceed 100 ulps and the first
1286 	 * dropped digit to be away from the halfway point guarantees that no
1287 	 * rounding boundary — and no power of ten, where the two values could
1288 	 * disagree on the position of the leading digit — lies between the two
1289 	 * values, so both round identically.
1290 	 * </p>
1291 	 *
1292 	 * @param abs the positive, normal double being rounded
1293 	 * @param shortest its shortest decimal representation
1294 	 * @param remainderDigits how many digits of {@code shortest} fall below
1295 	 *        the rounding unit
1296 	 * @param unitExponent decimal exponent of the rounding unit
1297 	 * @return whether the shortest representation can be rounded instead of
1298 	 *         the exact expansion
1299 	 */
1300 	private static boolean roundsLikeExact(double abs, BigDecimal shortest, int remainderDigits, int unitExponent) {
1301 		if (unitExponent < -307 || unitExponent > 308) {
1302 			// Math.pow(10, unitExponent) would leave the normal double range.
1303 			return false;
1304 		}
1305 		if (Math.ulp(abs) * 100.0 >= Math.pow(10.0, unitExponent)) {
1306 			return false;
1307 		}
1308 		if (remainderDigits <= 0) {
1309 			// The shortest representation is an exact multiple of the
1310 			// rounding unit; the exact value rounds to it.
1311 			return true;
1312 		}
1313 		String digits = shortest.unscaledValue().toString();
1314 		if (remainderDigits > digits.length()) {
1315 			// The dropped fraction starts with a zero digit: far from the
1316 			// halfway point.
1317 			return true;
1318 		}
1319 		// With the unit at least 200 times the maximum difference between the
1320 		// exact value and its shortest representation, only a first dropped
1321 		// digit of 4 or 5 can put the two values on opposite sides of a
1322 		// rounding boundary.
1323 		char first = digits.charAt(digits.length() - remainderDigits);
1324 		return first != '4' && first != '5';
1325 	}
1326 
1327 	/** Renders an exponent value with at least two digits, like C. */
1328 	private static String exponentDigits(int exponent) {
1329 		String digits = Integer.toString(exponent);
1330 		return digits.length() < 2 ? "0" + digits : digits;
1331 	}
1332 
1333 	private static boolean isUpperCaseConversion(char conversion) {
1334 		return conversion == 'X' || conversion == 'E' || conversion == 'F' || conversion == 'G' || conversion == 'A';
1335 	}
1336 
1337 	private static boolean isZeroMagnitude(String magnitude) {
1338 		for (int i = 0; i < magnitude.length(); i++) {
1339 			if (magnitude.charAt(i) != '0') {
1340 				return false;
1341 			}
1342 		}
1343 		return true;
1344 	}
1345 
1346 	private static boolean isAsciiDigit(char c) {
1347 		return c >= '0' && c <= '9';
1348 	}
1349 
1350 	/**
1351 	 * Parses a run of decimal digits, clamping absurd widths, precisions, and
1352 	 * argument positions to {@link Integer#MAX_VALUE} instead of failing the
1353 	 * way {@link Integer#parseInt(String)} would.
1354 	 */
1355 	private static int parseInt(String s, int from, int to) {
1356 		try {
1357 			return Integer.parseInt(s.substring(from, to));
1358 		} catch (NumberFormatException e) {
1359 			return Integer.MAX_VALUE;
1360 		}
1361 	}
1362 
1363 	private static String zeros(int count) {
1364 		return repeat('0', count);
1365 	}
1366 
1367 	private static String repeat(char c, int count) {
1368 		if (count <= 0) {
1369 			return "";
1370 		}
1371 		char[] chars = new char[count];
1372 		Arrays.fill(chars, c);
1373 		return new String(chars);
1374 	}
1375 }