1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.format;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.HOUR_OF_DAY;
  66 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  67 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
  68 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  69 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  70 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
  71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
  72 import static java.time.temporal.ChronoField.YEAR;
  73 
  74 import java.lang.ref.SoftReference;
  75 import java.math.BigDecimal;
  76 import java.math.BigInteger;
  77 import java.math.RoundingMode;
  78 import java.text.ParsePosition;
  79 import java.time.DateTimeException;
  80 import java.time.Instant;
  81 import java.time.LocalDateTime;
  82 import java.time.ZoneId;
  83 import java.time.ZoneOffset;
  84 import java.time.format.DateTimeTextProvider.LocaleStore;
  85 import java.time.temporal.Chrono;
  86 import java.time.temporal.ChronoField;
  87 import java.time.temporal.ISOChrono;
  88 import java.time.temporal.ISOFields;
  89 import java.time.temporal.Queries;
  90 import java.time.temporal.TemporalAccessor;
  91 import java.time.temporal.TemporalField;
  92 import java.time.temporal.TemporalQuery;
  93 import java.time.temporal.ValueRange;
  94 import java.time.temporal.WeekFields;
  95 import java.time.zone.ZoneRulesProvider;
  96 import java.util.AbstractMap.SimpleImmutableEntry;
  97 import java.util.ArrayList;
  98 import java.util.Arrays;
  99 import java.util.Collections;
 100 import java.util.Comparator;
 101 import java.util.HashMap;
 102 import java.util.Iterator;
 103 import java.util.LinkedHashMap;
 104 import java.util.List;
 105 import java.util.Locale;
 106 import java.util.Map;
 107 import java.util.Map.Entry;
 108 import java.util.Objects;
 109 import java.util.Set;
 110 import java.util.TimeZone;
 111 import java.util.concurrent.ConcurrentHashMap;
 112 
 113 import sun.util.locale.provider.TimeZoneNameUtility;
 114 
 115 /**
 116  * Builder to create date-time formatters.
 117  * <p>
 118  * This allows a {@code DateTimeFormatter} to be created.
 119  * All date-time formatters are created ultimately using this builder.
 120  * <p>
 121  * The basic elements of date-time can all be added:
 122  * <p><ul>
 123  * <li>Value - a numeric value</li>
 124  * <li>Fraction - a fractional value including the decimal place. Always use this when
 125  * outputting fractions to ensure that the fraction is parsed correctly</li>
 126  * <li>Text - the textual equivalent for the value</li>
 127  * <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li>
 128  * <li>ZoneId - the {@linkplain ZoneId time-zone} id</li>
 129  * <li>ZoneText - the name of the time-zone</li>
 130  * <li>Literal - a text literal</li>
 131  * <li>Nested and Optional - formats can be nested or made optional</li>
 132  * <li>Other - the printer and parser interfaces can be used to add user supplied formatting</li>
 133  * </ul><p>
 134  * In addition, any of the elements may be decorated by padding, either with spaces or any other character.
 135  * <p>
 136  * Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat}
 137  * can be used, see {@link #appendPattern(String)}.
 138  * In practice, this simply parses the pattern and calls other methods on the builder.
 139  *
 140  * <h3>Specification for implementors</h3>
 141  * This class is a mutable builder intended for use from a single thread.
 142  *
 143  * @since 1.8
 144  */
 145 public final class DateTimeFormatterBuilder {
 146 
 147     /**
 148      * Query for a time-zone that is region-only.
 149      */
 150     private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = (temporal) -> {
 151         ZoneId zone = temporal.query(Queries.zoneId());
 152         return (zone != null && zone instanceof ZoneOffset == false ? zone : null);
 153     };
 154 
 155     /**
 156      * The currently active builder, used by the outermost builder.
 157      */
 158     private DateTimeFormatterBuilder active = this;
 159     /**
 160      * The parent builder, null for the outermost builder.
 161      */
 162     private final DateTimeFormatterBuilder parent;
 163     /**
 164      * The list of printers that will be used.
 165      */
 166     private final List<DateTimePrinterParser> printerParsers = new ArrayList<>();
 167     /**
 168      * Whether this builder produces an optional formatter.
 169      */
 170     private final boolean optional;
 171     /**
 172      * The width to pad the next field to.
 173      */
 174     private int padNextWidth;
 175     /**
 176      * The character to pad the next field with.
 177      */
 178     private char padNextChar;
 179     /**
 180      * The index of the last variable width value parser.
 181      */
 182     private int valueParserIndex = -1;
 183 
 184     /**
 185      * Constructs a new instance of the builder.
 186      */
 187     public DateTimeFormatterBuilder() {
 188         super();
 189         parent = null;
 190         optional = false;
 191     }
 192 
 193     /**
 194      * Constructs a new instance of the builder.
 195      *
 196      * @param parent  the parent builder, not null
 197      * @param optional  whether the formatter is optional, not null
 198      */
 199     private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) {
 200         super();
 201         this.parent = parent;
 202         this.optional = optional;
 203     }
 204 
 205     //-----------------------------------------------------------------------
 206     /**
 207      * Changes the parse style to be case sensitive for the remainder of the formatter.
 208      * <p>
 209      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 210      * This method allows the case sensitivity setting of parsing to be changed.
 211      * <p>
 212      * Calling this method changes the state of the builder such that all
 213      * subsequent builder method calls will parse text in case sensitive mode.
 214      * See {@link #parseCaseInsensitive} for the opposite setting.
 215      * The parse case sensitive/insensitive methods may be called at any point
 216      * in the builder, thus the parser can swap between case parsing modes
 217      * multiple times during the parse.
 218      * <p>
 219      * Since the default is case sensitive, this method should only be used after
 220      * a previous call to {@code #parseCaseInsensitive}.
 221      *
 222      * @return this, for chaining, not null
 223      */
 224     public DateTimeFormatterBuilder parseCaseSensitive() {
 225         appendInternal(SettingsParser.SENSITIVE);
 226         return this;
 227     }
 228 
 229     /**
 230      * Changes the parse style to be case insensitive for the remainder of the formatter.
 231      * <p>
 232      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 233      * This method allows the case sensitivity setting of parsing to be changed.
 234      * <p>
 235      * Calling this method changes the state of the builder such that all
 236      * subsequent builder method calls will parse text in case insensitive mode.
 237      * See {@link #parseCaseSensitive()} for the opposite setting.
 238      * The parse case sensitive/insensitive methods may be called at any point
 239      * in the builder, thus the parser can swap between case parsing modes
 240      * multiple times during the parse.
 241      *
 242      * @return this, for chaining, not null
 243      */
 244     public DateTimeFormatterBuilder parseCaseInsensitive() {
 245         appendInternal(SettingsParser.INSENSITIVE);
 246         return this;
 247     }
 248 
 249     //-----------------------------------------------------------------------
 250     /**
 251      * Changes the parse style to be strict for the remainder of the formatter.
 252      * <p>
 253      * Parsing can be strict or lenient - by default its strict.
 254      * This controls the degree of flexibility in matching the text and sign styles.
 255      * <p>
 256      * When used, this method changes the parsing to be strict from this point onwards.
 257      * As strict is the default, this is normally only needed after calling {@link #parseLenient()}.
 258      * The change will remain in force until the end of the formatter that is eventually
 259      * constructed or until {@code parseLenient} is called.
 260      *
 261      * @return this, for chaining, not null
 262      */
 263     public DateTimeFormatterBuilder parseStrict() {
 264         appendInternal(SettingsParser.STRICT);
 265         return this;
 266     }
 267 
 268     /**
 269      * Changes the parse style to be lenient for the remainder of the formatter.
 270      * Note that case sensitivity is set separately to this method.
 271      * <p>
 272      * Parsing can be strict or lenient - by default its strict.
 273      * This controls the degree of flexibility in matching the text and sign styles.
 274      * Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
 275      * <p>
 276      * When used, this method changes the parsing to be lenient from this point onwards.
 277      * The change will remain in force until the end of the formatter that is eventually
 278      * constructed or until {@code parseStrict} is called.
 279      *
 280      * @return this, for chaining, not null
 281      */
 282     public DateTimeFormatterBuilder parseLenient() {
 283         appendInternal(SettingsParser.LENIENT);
 284         return this;
 285     }
 286 
 287     //-----------------------------------------------------------------------
 288     /**
 289      * Appends the value of a date-time field to the formatter using a normal
 290      * output style.
 291      * <p>
 292      * The value of the field will be output during a print.
 293      * If the value cannot be obtained then an exception will be thrown.
 294      * <p>
 295      * The value will be printed as per the normal print of an integer value.
 296      * Only negative numbers will be signed. No padding will be added.
 297      * <p>
 298      * The parser for a variable width value such as this normally behaves greedily,
 299      * requiring one digit, but accepting as many digits as possible.
 300      * This behavior can be affected by 'adjacent value parsing'.
 301      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 302      *
 303      * @param field  the field to append, not null
 304      * @return this, for chaining, not null
 305      */
 306     public DateTimeFormatterBuilder appendValue(TemporalField field) {
 307         Objects.requireNonNull(field, "field");
 308         active.valueParserIndex = appendInternal(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
 309         return this;
 310     }
 311 
 312     /**
 313      * Appends the value of a date-time field to the formatter using a fixed
 314      * width, zero-padded approach.
 315      * <p>
 316      * The value of the field will be output during a print.
 317      * If the value cannot be obtained then an exception will be thrown.
 318      * <p>
 319      * The value will be zero-padded on the left. If the size of the value
 320      * means that it cannot be printed within the width then an exception is thrown.
 321      * If the value of the field is negative then an exception is thrown during printing.
 322      * <p>
 323      * This method supports a special technique of parsing known as 'adjacent value parsing'.
 324      * This technique solves the problem where a variable length value is followed by one or more
 325      * fixed length values. The standard parser is greedy, and thus it would normally
 326      * steal the digits that are needed by the fixed width value parsers that follow the
 327      * variable width one.
 328      * <p>
 329      * No action is required to initiate 'adjacent value parsing'.
 330      * When a call to {@code appendValue} with a variable width is made, the builder
 331      * enters adjacent value parsing setup mode. If the immediately subsequent method
 332      * call or calls on the same builder are to this method, then the parser will reserve
 333      * space so that the fixed width values can be parsed.
 334      * <p>
 335      * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);}
 336      * The year is a variable width parse of between 1 and 19 digits.
 337      * The month is a fixed width parse of 2 digits.
 338      * Because these were appended to the same builder immediately after one another,
 339      * the year parser will reserve two digits for the month to parse.
 340      * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6.
 341      * Without adjacent value parsing, the year would greedily parse all six digits and leave
 342      * nothing for the month.
 343      * <p>
 344      * Adjacent value parsing applies to each set of fixed width not-negative values in the parser
 345      * that immediately follow any kind of variable width value.
 346      * Calling any other append method will end the setup of adjacent value parsing.
 347      * Thus, in the unlikely event that you need to avoid adjacent value parsing behavior,
 348      * simply add the {@code appendValue} to another {@code DateTimeFormatterBuilder}
 349      * and add that to this builder.
 350      * <p>
 351      * If adjacent parsing is active, then parsing must match exactly the specified
 352      * number of digits in both strict and lenient modes.
 353      * In addition, no positive or negative sign is permitted.
 354      *
 355      * @param field  the field to append, not null
 356      * @param width  the width of the printed field, from 1 to 19
 357      * @return this, for chaining, not null
 358      * @throws IllegalArgumentException if the width is invalid
 359      */
 360     public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
 361         Objects.requireNonNull(field, "field");
 362         if (width < 1 || width > 19) {
 363             throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
 364         }
 365         NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
 366         return appendFixedWidth(width, pp);
 367     }
 368 
 369     /**
 370      * Appends the value of a date-time field to the formatter providing full
 371      * control over printing.
 372      * <p>
 373      * The value of the field will be output during a print.
 374      * If the value cannot be obtained then an exception will be thrown.
 375      * <p>
 376      * This method provides full control of the numeric formatting, including
 377      * zero-padding and the positive/negative sign.
 378      * <p>
 379      * The parser for a variable width value such as this normally behaves greedily,
 380      * accepting as many digits as possible.
 381      * This behavior can be affected by 'adjacent value parsing'.
 382      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 383      * <p>
 384      * In strict parsing mode, the minimum number of parsed digits is {@code minWidth}.
 385      * In lenient parsing mode, the minimum number of parsed digits is one.
 386      * <p>
 387      * If this method is invoked with equal minimum and maximum widths and a sign style of
 388      * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}.
 389      * In this scenario, the printing and parsing behavior described there occur.
 390      *
 391      * @param field  the field to append, not null
 392      * @param minWidth  the minimum field width of the printed field, from 1 to 19
 393      * @param maxWidth  the maximum field width of the printed field, from 1 to 19
 394      * @param signStyle  the positive/negative output style, not null
 395      * @return this, for chaining, not null
 396      * @throws IllegalArgumentException if the widths are invalid
 397      */
 398     public DateTimeFormatterBuilder appendValue(
 399             TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
 400         if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
 401             return appendValue(field, maxWidth);
 402         }
 403         Objects.requireNonNull(field, "field");
 404         Objects.requireNonNull(signStyle, "signStyle");
 405         if (minWidth < 1 || minWidth > 19) {
 406             throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
 407         }
 408         if (maxWidth < 1 || maxWidth > 19) {
 409             throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
 410         }
 411         if (maxWidth < minWidth) {
 412             throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
 413                     maxWidth + " < " + minWidth);
 414         }
 415         NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
 416         if (minWidth == maxWidth) {
 417             appendInternal(pp);
 418         } else {
 419             active.valueParserIndex = appendInternal(pp);
 420         }
 421         return this;
 422     }
 423 
 424     //-----------------------------------------------------------------------
 425     /**
 426      * Appends the reduced value of a date-time field to the formatter.
 427      * <p>
 428      * This is typically used for printing and parsing a two digit year.
 429      * The {@code width} is the printed and parsed width.
 430      * The {@code baseValue} is used during parsing to determine the valid range.
 431      * <p>
 432      * For printing, the width is used to determine the number of characters to print.
 433      * The rightmost characters are output to match the width, left padding with zero.
 434      * <p>
 435      * For parsing, exactly the number of characters specified by the width are parsed.
 436      * This is incomplete information however, so the base value is used to complete the parse.
 437      * The base value is the first valid value in a range of ten to the power of width.
 438      * <p>
 439      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 440      * valid values from {@code 1980} to {@code 2079}.
 441      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 442      * is the value within the range where the last two digits are "12".
 443      * <p>
 444      * This is a fixed width parser operating using 'adjacent value parsing'.
 445      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 446      *
 447      * @param field  the field to append, not null
 448      * @param width  the width of the printed and parsed field, from 1 to 18
 449      * @param baseValue  the base value of the range of valid values
 450      * @return this, for chaining, not null
 451      * @throws IllegalArgumentException if the width or base value is invalid
 452      */
 453     public DateTimeFormatterBuilder appendValueReduced(
 454             TemporalField field, int width, int baseValue) {
 455         Objects.requireNonNull(field, "field");
 456         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, baseValue);
 457         appendFixedWidth(width, pp);
 458         return this;
 459     }
 460 
 461     /**
 462      * Appends a fixed width printer-parser.
 463      *
 464      * @param width  the width
 465      * @param pp  the printer-parser, not null
 466      * @return this, for chaining, not null
 467      */
 468     private DateTimeFormatterBuilder appendFixedWidth(int width, NumberPrinterParser pp) {
 469         if (active.valueParserIndex >= 0) {
 470             // adjacent parsing mode, update setting in previous parsers
 471             NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(active.valueParserIndex);
 472             basePP = basePP.withSubsequentWidth(width);
 473             int activeValueParser = active.valueParserIndex;
 474             active.printerParsers.set(active.valueParserIndex, basePP);
 475             appendInternal(pp.withFixedWidth());
 476             active.valueParserIndex = activeValueParser;
 477         } else {
 478             // not adjacent parsing
 479             appendInternal(pp);
 480         }
 481         return this;
 482     }
 483 
 484     //-----------------------------------------------------------------------
 485     /**
 486      * Appends the fractional value of a date-time field to the formatter.
 487      * <p>
 488      * The fractional value of the field will be output including the
 489      * preceding decimal point. The preceding value is not output.
 490      * For example, the second-of-minute value of 15 would be output as {@code .25}.
 491      * <p>
 492      * The width of the printed fraction can be controlled. Setting the
 493      * minimum width to zero will cause no output to be generated.
 494      * The printed fraction will have the minimum width necessary between
 495      * the minimum and maximum widths - trailing zeroes are omitted.
 496      * No rounding occurs due to the maximum width - digits are simply dropped.
 497      * <p>
 498      * When parsing in strict mode, the number of parsed digits must be between
 499      * the minimum and maximum width. When parsing in lenient mode, the minimum
 500      * width is considered to be zero and the maximum is nine.
 501      * <p>
 502      * If the value cannot be obtained then an exception will be thrown.
 503      * If the value is negative an exception will be thrown.
 504      * If the field does not have a fixed set of valid values then an
 505      * exception will be thrown.
 506      * If the field value in the date-time to be printed is invalid it
 507      * cannot be printed and an exception will be thrown.
 508      *
 509      * @param field  the field to append, not null
 510      * @param minWidth  the minimum width of the field excluding the decimal point, from 0 to 9
 511      * @param maxWidth  the maximum width of the field excluding the decimal point, from 1 to 9
 512      * @param decimalPoint  whether to output the localized decimal point symbol
 513      * @return this, for chaining, not null
 514      * @throws IllegalArgumentException if the field has a variable set of valid values or
 515      *  either width is invalid
 516      */
 517     public DateTimeFormatterBuilder appendFraction(
 518             TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
 519         appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 520         return this;
 521     }
 522 
 523     //-----------------------------------------------------------------------
 524     /**
 525      * Appends the text of a date-time field to the formatter using the full
 526      * text style.
 527      * <p>
 528      * The text of the field will be output during a print.
 529      * The value must be within the valid range of the field.
 530      * If the value cannot be obtained then an exception will be thrown.
 531      * If the field has no textual representation, then the numeric value will be used.
 532      * <p>
 533      * The value will be printed as per the normal print of an integer value.
 534      * Only negative numbers will be signed. No padding will be added.
 535      *
 536      * @param field  the field to append, not null
 537      * @return this, for chaining, not null
 538      */
 539     public DateTimeFormatterBuilder appendText(TemporalField field) {
 540         return appendText(field, TextStyle.FULL);
 541     }
 542 
 543     /**
 544      * Appends the text of a date-time field to the formatter.
 545      * <p>
 546      * The text of the field will be output during a print.
 547      * The value must be within the valid range of the field.
 548      * If the value cannot be obtained then an exception will be thrown.
 549      * If the field has no textual representation, then the numeric value will be used.
 550      * <p>
 551      * The value will be printed as per the normal print of an integer value.
 552      * Only negative numbers will be signed. No padding will be added.
 553      *
 554      * @param field  the field to append, not null
 555      * @param textStyle  the text style to use, not null
 556      * @return this, for chaining, not null
 557      */
 558     public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
 559         Objects.requireNonNull(field, "field");
 560         Objects.requireNonNull(textStyle, "textStyle");
 561         appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
 562         return this;
 563     }
 564 
 565     /**
 566      * Appends the text of a date-time field to the formatter using the specified
 567      * map to supply the text.
 568      * <p>
 569      * The standard text outputting methods use the localized text in the JDK.
 570      * This method allows that text to be specified directly.
 571      * The supplied map is not validated by the builder to ensure that printing or
 572      * parsing is possible, thus an invalid map may throw an error during later use.
 573      * <p>
 574      * Supplying the map of text provides considerable flexibility in printing and parsing.
 575      * For example, a legacy application might require or supply the months of the
 576      * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
 577      * for localized month names. Using this method, a map can be created which
 578      * defines the connection between each value and the text:
 579      * <pre>
 580      * Map&lt;Long, String&gt; map = new HashMap&lt;&gt;();
 581      * map.put(1, "JNY");
 582      * map.put(2, "FBY");
 583      * map.put(3, "MCH");
 584      * ...
 585      * builder.appendText(MONTH_OF_YEAR, map);
 586      * </pre>
 587      * <p>
 588      * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
 589      * or as Roman numerals "I", "II", "III", "IV".
 590      * <p>
 591      * During printing, the value is obtained and checked that it is in the valid range.
 592      * If text is not available for the value then it is output as a number.
 593      * During parsing, the parser will match against the map of text and numeric values.
 594      *
 595      * @param field  the field to append, not null
 596      * @param textLookup  the map from the value to the text
 597      * @return this, for chaining, not null
 598      */
 599     public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
 600         Objects.requireNonNull(field, "field");
 601         Objects.requireNonNull(textLookup, "textLookup");
 602         Map<Long, String> copy = new LinkedHashMap<>(textLookup);
 603         Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
 604         final LocaleStore store = new LocaleStore(map);
 605         DateTimeTextProvider provider = new DateTimeTextProvider() {
 606             @Override
 607             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
 608                 return store.getText(value, style);
 609             }
 610             @Override
 611             public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
 612                 return store.getTextIterator(style);
 613             }
 614         };
 615         appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
 616         return this;
 617     }
 618 
 619     //-----------------------------------------------------------------------
 620     /**
 621      * Appends an instant using ISO-8601 to the formatter.
 622      * <p>
 623      * Instants have a fixed output format.
 624      * They are converted to a date-time with a zone-offset of UTC and printed
 625      * using the standard ISO-8601 format.
 626      * <p>
 627      * An alternative to this method is to print/parse the instant as a single
 628      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 629      *
 630      * @return this, for chaining, not null
 631      */
 632     public DateTimeFormatterBuilder appendInstant() {
 633         appendInternal(new InstantPrinterParser());
 634         return this;
 635     }
 636 
 637     /**
 638      * Appends the zone offset, such as '+01:00', to the formatter.
 639      * <p>
 640      * This appends an instruction to print/parse the offset ID to the builder.
 641      * This is equivalent to calling {@code appendOffset("HH:MM:ss", "Z")}.
 642      *
 643      * @return this, for chaining, not null
 644      */
 645     public DateTimeFormatterBuilder appendOffsetId() {
 646         appendInternal(OffsetIdPrinterParser.INSTANCE_ID);
 647         return this;
 648     }
 649 
 650     /**
 651      * Appends the zone offset, such as '+01:00', to the formatter.
 652      * <p>
 653      * This appends an instruction to print/parse the offset ID to the builder.
 654      * <p>
 655      * During printing, the offset is obtained using a mechanism equivalent
 656      * to querying the temporal with {@link Queries#offset()}.
 657      * It will be printed using the format defined below.
 658      * If the offset cannot be obtained then an exception is thrown unless the
 659      * section of the formatter is optional.
 660      * <p>
 661      * During parsing, the offset is parsed using the format defined below.
 662      * If the offset cannot be parsed then an exception is thrown unless the
 663      * section of the formatter is optional.
 664      * <p>
 665      * The format of the offset is controlled by a pattern which must be one
 666      * of the following:
 667      * <p><ul>
 668      * <li>{@code +HH} - hour only, ignoring any minute
 669      * <li>{@code +HHMM} - hour and minute, no colon
 670      * <li>{@code +HH:MM} - hour and minute, with colon
 671      * <li>{@code +HHMMss} - hour and minute, with second if non-zero and no colon
 672      * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero and colon
 673      * <li>{@code +HHMMSS} - hour, minute and second, no colon
 674      * <li>{@code +HH:MM:SS} - hour, minute and second, with colon
 675      * </ul><p>
 676      * The "no offset" text controls what text is printed when the offset is zero.
 677      * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
 678      * Three formats are accepted for parsing UTC - the "no offset" text, and the
 679      * plus and minus versions of zero defined by the pattern.
 680      *
 681      * @param pattern  the pattern to use, not null
 682      * @param noOffsetText  the text to use when the offset is zero, not null
 683      * @return this, for chaining, not null
 684      */
 685     public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
 686         appendInternal(new OffsetIdPrinterParser(noOffsetText, pattern));
 687         return this;
 688     }
 689 
 690     //-----------------------------------------------------------------------
 691     /**
 692      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
 693      * <p>
 694      * This appends an instruction to print/parse the zone ID to the builder.
 695      * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
 696      * By contrast, {@code OffsetDateTime} does not have a zone ID suitable
 697      * for use with this method, see {@link #appendZoneOrOffsetId()}.
 698      * <p>
 699      * During printing, the zone is obtained using a mechanism equivalent
 700      * to querying the temporal with {@link Queries#zoneId()}.
 701      * It will be printed using the result of {@link ZoneId#getId()}.
 702      * If the zone cannot be obtained then an exception is thrown unless the
 703      * section of the formatter is optional.
 704      * <p>
 705      * During parsing, the zone is parsed and must match a known zone or offset.
 706      * If the zone cannot be parsed then an exception is thrown unless the
 707      * section of the formatter is optional.
 708      *
 709      * @return this, for chaining, not null
 710      * @see #appendZoneRegionId()
 711      */
 712     public DateTimeFormatterBuilder appendZoneId() {
 713         appendInternal(new ZoneIdPrinterParser(Queries.zoneId(), "ZoneId()"));
 714         return this;
 715     }
 716 
 717     /**
 718      * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
 719      * rejecting the zone ID if it is a {@code ZoneOffset}.
 720      * <p>
 721      * This appends an instruction to print/parse the zone ID to the builder
 722      * only if it is a region-based ID.
 723      * <p>
 724      * During printing, the zone is obtained using a mechanism equivalent
 725      * to querying the temporal with {@link Queries#zoneId()}.
 726      * If the zone is a {@code ZoneOffset} or it cannot be obtained then
 727      * an exception is thrown unless the section of the formatter is optional.
 728      * If the zone is not an offset, then the zone will be printed using
 729      * the zone ID from {@link ZoneId#getId()}.
 730      * <p>
 731      * During parsing, the zone is parsed and must match a known zone or offset.
 732      * If the zone cannot be parsed then an exception is thrown unless the
 733      * section of the formatter is optional.
 734      * Note that parsing accepts offsets, whereas printing will never produce
 735      * one, thus parsing is equivalent to {@code appendZoneId}.
 736      *
 737      * @return this, for chaining, not null
 738      * @see #appendZoneId()
 739      */
 740     public DateTimeFormatterBuilder appendZoneRegionId() {
 741         appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
 742         return this;
 743     }
 744 
 745     /**
 746      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
 747      * the formatter, using the best available zone ID.
 748      * <p>
 749      * This appends an instruction to print/parse the best available
 750      * zone or offset ID to the builder.
 751      * The zone ID is obtained in a lenient manner that first attempts to
 752      * find a true zone ID, such as that on {@code ZonedDateTime}, and
 753      * then attempts to find an offset, such as that on {@code OffsetDateTime}.
 754      * <p>
 755      * During printing, the zone is obtained using a mechanism equivalent
 756      * to querying the temporal with {@link Queries#zone()}.
 757      * It will be printed using the result of {@link ZoneId#getId()}.
 758      * If the zone cannot be obtained then an exception is thrown unless the
 759      * section of the formatter is optional.
 760      * <p>
 761      * During parsing, the zone is parsed and must match a known zone or offset.
 762      * If the zone cannot be parsed then an exception is thrown unless the
 763      * section of the formatter is optional.
 764      * <p>
 765      * This method is is identical to {@code appendZoneId()} except in the
 766      * mechanism used to obtain the zone.
 767      *
 768      * @return this, for chaining, not null
 769      * @see #appendZoneId()
 770      */
 771     public DateTimeFormatterBuilder appendZoneOrOffsetId() {
 772         appendInternal(new ZoneIdPrinterParser(Queries.zone(), "ZoneOrOffsetId()"));
 773         return this;
 774     }
 775 
 776     /**
 777      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
 778      * <p>
 779      * This appends an instruction to print the textual name of the zone to the builder.
 780      * <p>
 781      * During printing, the zone is obtained using a mechanism equivalent
 782      * to querying the temporal with {@link Queries#zoneId()}.
 783      * If the zone is a {@code ZoneOffset} it will be printed using the
 784      * result of {@link ZoneOffset#getId()}.
 785      * If the zone is not an offset, the textual name will be looked up
 786      * for the locale set in the {@link DateTimeFormatter}.
 787      * If the temporal object being printed represents an instant, then the text
 788      * will be the summer or winter time text as appropriate.
 789      * If the lookup for text does not find any suitable reuslt, then the
 790      * {@link ZoneId#getId() ID} will be printed instead.
 791      * If the zone cannot be obtained then an exception is thrown unless the
 792      * section of the formatter is optional.
 793      * <p>
 794      * Parsing is not currently supported.
 795      *
 796      * @param textStyle  the text style to use, not null
 797      * @return this, for chaining, not null
 798      */
 799     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
 800         // TODO: parsing of zone text?
 801 //        * During parsing, either the textual zone name, the zone ID or the offset
 802 //        * is accepted.
 803 //        * If the zone cannot be parsed then an exception is thrown unless the
 804 //        * section of the formatter is optional.
 805         appendInternal(new ZoneTextPrinterParser(textStyle));
 806         return this;
 807     }
 808 
 809     //-----------------------------------------------------------------------
 810     /**
 811      * Appends the chronology ID to the formatter.
 812      * <p>
 813      * The chronology ID will be output during a print.
 814      * If the chronology cannot be obtained then an exception will be thrown.
 815      *
 816      * @return this, for chaining, not null
 817      */
 818     public DateTimeFormatterBuilder appendChronoId() {
 819         appendInternal(new ChronoPrinterParser(null));
 820         return this;
 821     }
 822 
 823     /**
 824      * Appends the chronology name to the formatter.
 825      * <p>
 826      * The calendar system name will be output during a print.
 827      * If the chronology cannot be obtained then an exception will be thrown.
 828      * The calendar system name is obtained from the formatting symbols.
 829      *
 830      * @param textStyle  the text style to use, not null
 831      * @return this, for chaining, not null
 832      */
 833     public DateTimeFormatterBuilder appendChronoText(TextStyle textStyle) {
 834         Objects.requireNonNull(textStyle, "textStyle");
 835         appendInternal(new ChronoPrinterParser(textStyle));
 836         return this;
 837     }
 838 
 839     //-----------------------------------------------------------------------
 840     /**
 841      * Appends a localized date-time pattern to the formatter.
 842      * <p>
 843      * The pattern is resolved lazily using the locale being used during the print/parse
 844      * (stored in {@link DateTimeFormatter}.
 845      * <p>
 846      * The pattern can vary by chronology, although typically it doesn't.
 847      * This method uses the standard ISO chronology patterns.
 848      *
 849      * @param dateStyle  the date style to use, null means no date required
 850      * @param timeStyle  the time style to use, null means no time required
 851      * @return this, for chaining, not null
 852      */
 853     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
 854         return appendLocalized(dateStyle, timeStyle, ISOChrono.INSTANCE);
 855     }
 856 
 857     /**
 858      * Appends a localized date-time pattern to the formatter.
 859      * <p>
 860      * The pattern is resolved lazily using the locale being used during the print/parse,
 861      * stored in {@link DateTimeFormatter}.
 862      * <p>
 863      * The pattern can vary by chronology, although typically it doesn't.
 864      * This method allows the chronology to be specified.
 865      *
 866      * @param dateStyle  the date style to use, null means no date required
 867      * @param timeStyle  the time style to use, null means no time required
 868      * @param chrono  the chronology to use, not null
 869      * @return this, for chaining, not null
 870      */
 871     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle, Chrono<?> chrono) {
 872         Objects.requireNonNull(chrono, "chrono");
 873         if (dateStyle != null || timeStyle != null) {
 874             appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle, chrono));
 875         }
 876         return this;
 877     }
 878 
 879     //-----------------------------------------------------------------------
 880     /**
 881      * Appends a character literal to the formatter.
 882      * <p>
 883      * This character will be output during a print.
 884      *
 885      * @param literal  the literal to append, not null
 886      * @return this, for chaining, not null
 887      */
 888     public DateTimeFormatterBuilder appendLiteral(char literal) {
 889         appendInternal(new CharLiteralPrinterParser(literal));
 890         return this;
 891     }
 892 
 893     /**
 894      * Appends a string literal to the formatter.
 895      * <p>
 896      * This string will be output during a print.
 897      * <p>
 898      * If the literal is empty, nothing is added to the formatter.
 899      *
 900      * @param literal  the literal to append, not null
 901      * @return this, for chaining, not null
 902      */
 903     public DateTimeFormatterBuilder appendLiteral(String literal) {
 904         Objects.requireNonNull(literal, "literal");
 905         if (literal.length() > 0) {
 906             if (literal.length() == 1) {
 907                 appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
 908             } else {
 909                 appendInternal(new StringLiteralPrinterParser(literal));
 910             }
 911         }
 912         return this;
 913     }
 914 
 915     //-----------------------------------------------------------------------
 916     /**
 917      * Appends all the elements of a formatter to the builder.
 918      * <p>
 919      * This method has the same effect as appending each of the constituent
 920      * parts of the formatter directly to this builder.
 921      *
 922      * @param formatter  the formatter to add, not null
 923      * @return this, for chaining, not null
 924      */
 925     public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
 926         Objects.requireNonNull(formatter, "formatter");
 927         appendInternal(formatter.toPrinterParser(false));
 928         return this;
 929     }
 930 
 931     /**
 932      * Appends a formatter to the builder which will optionally print/parse.
 933      * <p>
 934      * This method has the same effect as appending each of the constituent
 935      * parts directly to this builder surrounded by an {@link #optionalStart()} and
 936      * {@link #optionalEnd()}.
 937      * <p>
 938      * The formatter will print if data is available for all the fields contained within it.
 939      * The formatter will parse if the string matches, otherwise no error is returned.
 940      *
 941      * @param formatter  the formatter to add, not null
 942      * @return this, for chaining, not null
 943      */
 944     public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
 945         Objects.requireNonNull(formatter, "formatter");
 946         appendInternal(formatter.toPrinterParser(true));
 947         return this;
 948     }
 949 
 950     //-----------------------------------------------------------------------
 951     /**
 952      * Appends the elements defined by the specified pattern to the builder.
 953      * <p>
 954      * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
 955      * The characters '{' and '}' are reserved for future use.
 956      * The characters '[' and ']' indicate optional patterns.
 957      * The following pattern letters are defined:
 958      * <pre>
 959      *  Symbol  Meaning                     Presentation      Examples
 960      *  ------  -------                     ------------      -------
 961      *   G       era                         number/text       1; 01; AD; Anno Domini
 962      *   y       year                        year              2004; 04
 963      *   D       day-of-year                 number            189
 964      *   M       month-of-year               number/text       7; 07; Jul; July; J
 965      *   d       day-of-month                number            10
 966      *
 967      *   Q       quarter-of-year             number/text       3; 03; Q3
 968      *   Y       week-based-year             year              1996; 96
 969      *   w       week-of-year                number            27
 970      *   W       week-of-month               number            27
 971      *   e       localized day-of-week       number            2; Tue; Tuesday; T
 972      *   E       day-of-week                 number/text       2; Tue; Tuesday; T
 973      *   F       week-of-month               number            3
 974      *
 975      *   a       am-pm-of-day                text              PM
 976      *   h       clock-hour-of-am-pm (1-12)  number            12
 977      *   K       hour-of-am-pm (0-11)        number            0
 978      *   k       clock-hour-of-am-pm (1-24)  number            0
 979      *
 980      *   H       hour-of-day (0-23)          number            0
 981      *   m       minute-of-hour              number            30
 982      *   s       second-of-minute            number            55
 983      *   S       fraction-of-second          fraction          978
 984      *   A       milli-of-day                number            1234
 985      *   n       nano-of-second              number            987654321
 986      *   N       nano-of-day                 number            1234000000
 987      *
 988      *   I       time-zone ID                zoneId            America/Los_Angeles
 989      *   z       time-zone name              text              Pacific Standard Time; PST
 990      *   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;
 991      *   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
 992      *
 993      *   p       pad next                    pad modifier      1
 994      *
 995      *   '       escape for text             delimiter
 996      *   ''      single quote                literal           '
 997      *   [       optional section start
 998      *   ]       optional section end
 999      *   {}      reserved for future use
1000      * </pre>
1001      * <p>
1002      * The count of pattern letters determine the format.
1003      * <p>
1004      * <b>Text</b>: The text style is determined based on the number of pattern letters used.
1005      * Less than 4 pattern letters will use the {@link TextStyle#SHORT short form}.
1006      * Exactly 4 pattern letters will use the {@link TextStyle#FULL full form}.
1007      * Exactly 5 pattern letters will use the {@link TextStyle#NARROW narrow form}.
1008      * <p>
1009      * <b>Number</b>: If the count of letters is one, then the value is printed using the minimum number
1010      * of digits and without padding as per {@link #appendValue(java.time.temporal.TemporalField)}. Otherwise, the
1011      * count of digits is used as the width of the output field as per {@link #appendValue(java.time.temporal.TemporalField, int)}.
1012      * <p>
1013      * <b>Number/Text</b>: If the count of pattern letters is 3 or greater, use the Text rules above.
1014      * Otherwise use the Number rules above.
1015      * <p>
1016      * <b>Fraction</b>: Outputs the nano-of-second field as a fraction-of-second.
1017      * The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9.
1018      * If it is less than 9, then the nano-of-second value is truncated, with only the most
1019      * significant digits being output.
1020      * When parsing in strict mode, the number of parsed digits must match the count of pattern letters.
1021      * When parsing in lenient mode, the number of parsed digits must be at least the count of pattern
1022      * letters, up to 9 digits.
1023      * <p>
1024      * <b>Year</b>: The count of letters determines the minimum field width below which padding is used.
1025      * If the count of letters is two, then a {@link #appendValueReduced reduced} two digit form is used.
1026      * For printing, this outputs the rightmost two digits. For parsing, this will parse using the
1027      * base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
1028      * If the count of letters is less than four (but not two), then the sign is only output for negative
1029      * years as per {@link SignStyle#NORMAL}.
1030      * Otherwise, the sign is output if the pad width is exceeded, as per {@link SignStyle#EXCEEDS_PAD}
1031      * <p>
1032      * <b>ZoneId</b>: 'I' outputs the zone ID, such as 'Europe/Paris'.
1033      * <p>
1034      * <b>Offset X</b>: This formats the offset using 'Z' when the offset is zero.
1035      * One letter outputs just the hour', such as '+01'
1036      * Two letters outputs the hour and minute, without a colon, such as '+0130'.
1037      * Three letters outputs the hour and minute, with a colon, such as '+01:30'.
1038      * Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
1039      * Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
1040      * <p>
1041      * <b>Offset Z</b>: This formats the offset using '+0000' or '+00:00' when the offset is zero.
1042      * One or two letters outputs the hour and minute, without a colon, such as '+0130'.
1043      * Three letters outputs the hour and minute, with a colon, such as '+01:30'.
1044      * <p>
1045      * <b>Zone names</b>: Time zone names ('z') cannot be parsed.
1046      * <p>
1047      * <b>Optional section</b>: The optional section markers work exactly like calling {@link #optionalStart()}
1048      * and {@link #optionalEnd()}.
1049      * <p>
1050      * <b>Pad modifier</b>: Modifies the pattern that immediately follows to be padded with spaces.
1051      * The pad width is determined by the number of pattern letters.
1052      * This is the same as calling {@link #padNext(int)}.
1053      * <p>
1054      * For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.
1055      * <p>
1056      * Any unrecognized letter is an error.
1057      * Any non-letter character, other than '[', ']', '{', '}' and the single quote will be output directly.
1058      * Despite this, it is recommended to use single quotes around all characters that you want to
1059      * output directly to ensure that future changes do not break your application.
1060      * <p>
1061      * The pattern string is similar, but not identical, to {@link java.text.SimpleDateFormat SimpleDateFormat}.
1062      * Pattern letters 'E' and 'u' are merged, which changes the meaning of "E" and "EE" to be numeric.
1063      * Pattern letters 'Z' and 'X' are extended.
1064      * Pattern letter 'y' and 'Y' parse years of two digits and more than 4 digits differently.
1065      * Pattern letters 'n', 'A', 'N', 'I' and 'p' are added.
1066      * Number types will reject large numbers.
1067      * The pattern string is also similar, but not identical, to that defined by the
1068      * Unicode Common Locale Data Repository (CLDR).
1069      *
1070      * @param pattern  the pattern to add, not null
1071      * @return this, for chaining, not null
1072      * @throws IllegalArgumentException if the pattern is invalid
1073      */
1074     public DateTimeFormatterBuilder appendPattern(String pattern) {
1075         Objects.requireNonNull(pattern, "pattern");
1076         parsePattern(pattern);
1077         return this;
1078     }
1079 
1080     private void parsePattern(String pattern) {
1081         for (int pos = 0; pos < pattern.length(); pos++) {
1082             char cur = pattern.charAt(pos);
1083             if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1084                 int start = pos++;
1085                 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1086                 int count = pos - start;
1087                 // padding
1088                 if (cur == 'p') {
1089                     int pad = 0;
1090                     if (pos < pattern.length()) {
1091                         cur = pattern.charAt(pos);
1092                         if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1093                             pad = count;
1094                             start = pos++;
1095                             for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1096                             count = pos - start;
1097                         }
1098                     }
1099                     if (pad == 0) {
1100                         throw new IllegalArgumentException(
1101                                 "Pad letter 'p' must be followed by valid pad pattern: " + pattern);
1102                     }
1103                     padNext(pad); // pad and continue parsing
1104                 }
1105                 // main rules
1106                 TemporalField field = FIELD_MAP.get(cur);
1107                 if (field != null) {
1108                     parseField(cur, count, field);
1109                 } else if (cur == 'z') {
1110                     if (count < 4) {
1111                         appendZoneText(TextStyle.SHORT);
1112                     } else {
1113                         appendZoneText(TextStyle.FULL);
1114                     }
1115                 } else if (cur == 'I') {
1116                     appendZoneId();
1117                 } else if (cur == 'Z') {
1118                     if (count > 3) {
1119                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1120                     }
1121                     if (count < 3) {
1122                         appendOffset("+HHMM", "+0000");
1123                     } else {
1124                         appendOffset("+HH:MM", "+00:00");
1125                     }
1126                 } else if (cur == 'X') {
1127                     if (count > 5) {
1128                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1129                     }
1130                     appendOffset(OffsetIdPrinterParser.PATTERNS[count - 1], "Z");
1131                 } else if (cur == 'w' || cur == 'e') {
1132                     // Fields defined by Locale
1133                     if (count > 1) {
1134                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1135                     }
1136                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1137                 } else if (cur == 'W') {
1138                     // Fields defined by Locale
1139                     if (count > 2) {
1140                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1141                     }
1142                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1143                 } else {
1144                     throw new IllegalArgumentException("Unknown pattern letter: " + cur);
1145                 }
1146                 pos--;
1147 
1148             } else if (cur == '\'') {
1149                 // parse literals
1150                 int start = pos++;
1151                 for ( ; pos < pattern.length(); pos++) {
1152                     if (pattern.charAt(pos) == '\'') {
1153                         if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') {
1154                             pos++;
1155                         } else {
1156                             break;  // end of literal
1157                         }
1158                     }
1159                 }
1160                 if (pos >= pattern.length()) {
1161                     throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern);
1162                 }
1163                 String str = pattern.substring(start + 1, pos);
1164                 if (str.length() == 0) {
1165                     appendLiteral('\'');
1166                 } else {
1167                     appendLiteral(str.replace("''", "'"));
1168                 }
1169 
1170             } else if (cur == '[') {
1171                 optionalStart();
1172 
1173             } else if (cur == ']') {
1174                 if (active.parent == null) {
1175                     throw new IllegalArgumentException("Pattern invalid as it contains ] without previous [");
1176                 }
1177                 optionalEnd();
1178 
1179             } else if (cur == '{' || cur == '}') {
1180                 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
1181             } else {
1182                 appendLiteral(cur);
1183             }
1184         }
1185     }
1186 
1187     private void parseField(char cur, int count, TemporalField field) {
1188         switch (cur) {
1189             case 'y':
1190             case 'Y':
1191                 if (count == 2) {
1192                     appendValueReduced(field, 2, 2000);
1193                 } else if (count < 4) {
1194                     appendValue(field, count, 19, SignStyle.NORMAL);
1195                 } else {
1196                     appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
1197                 }
1198                 break;
1199             case 'G':
1200             case 'M':
1201             case 'Q':
1202             case 'E':
1203                 switch (count) {
1204                     case 1:
1205                         appendValue(field);
1206                         break;
1207                     case 2:
1208                         appendValue(field, 2);
1209                         break;
1210                     case 3:
1211                         appendText(field, TextStyle.SHORT);
1212                         break;
1213                     case 4:
1214                         appendText(field, TextStyle.FULL);
1215                         break;
1216                     case 5:
1217                         appendText(field, TextStyle.NARROW);
1218                         break;
1219                     default:
1220                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1221                 }
1222                 break;
1223             case 'a':
1224                 switch (count) {
1225                     case 1:
1226                     case 2:
1227                     case 3:
1228                         appendText(field, TextStyle.SHORT);
1229                         break;
1230                     case 4:
1231                         appendText(field, TextStyle.FULL);
1232                         break;
1233                     case 5:
1234                         appendText(field, TextStyle.NARROW);
1235                         break;
1236                     default:
1237                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1238                 }
1239                 break;
1240             case 'S':
1241                 appendFraction(NANO_OF_SECOND, count, count, false);
1242                 break;
1243             default:
1244                 if (count == 1) {
1245                     appendValue(field);
1246                 } else {
1247                     appendValue(field, count);
1248                 }
1249                 break;
1250         }
1251     }
1252 
1253     /** Map of letters to fields. */
1254     private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
1255     static {
1256         FIELD_MAP.put('G', ChronoField.ERA);                       // Java, CLDR (different to both for 1/2 chars)
1257         FIELD_MAP.put('y', ChronoField.YEAR);                      // CLDR
1258         // FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);            // Java, CLDR  // TODO redefine from above
1259         // FIELD_MAP.put('u', ChronoField.YEAR);                   // CLDR  // TODO
1260         // FIELD_MAP.put('Y', ISODateTimeField.WEEK_BASED_YEAR);          // Java7, CLDR (needs localized week number)  // TODO
1261         FIELD_MAP.put('Q', ISOFields.QUARTER_OF_YEAR);             // CLDR (removed quarter from 310)
1262         FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR);             // Java, CLDR
1263         // FIELD_MAP.put('w', WeekFields.weekOfYear());            // Java, CLDR (needs localized week number)
1264         // FIELD_MAP.put('W', WeekFields.weekOfMonth());           // Java, CLDR (needs localized week number)
1265         FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR);               // Java, CLDR
1266         FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH);              // Java, CLDR
1267         FIELD_MAP.put('F', ChronoField.ALIGNED_WEEK_OF_MONTH);     // Java, CLDR
1268         FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK);               // Java, CLDR (different to both for 1/2 chars)
1269         // FIELD_MAP.put('e', WeekFields.dayOfWeek());             // CLDR (needs localized week number)
1270         FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY);               // Java, CLDR
1271         FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY);               // Java, CLDR
1272         FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY);         // Java, CLDR
1273         FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM);              // Java, CLDR
1274         FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM);        // Java, CLDR
1275         FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR);            // Java, CLDR
1276         FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE);          // Java, CLDR
1277         FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND);            // CLDR (Java uses milli-of-second number)
1278         FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY);              // CLDR
1279         FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND);            // 310
1280         FIELD_MAP.put('N', ChronoField.NANO_OF_DAY);               // 310
1281         // reserved - z,Z,X,I,p
1282         // Java - X - compatible, but extended to 4 and 5 letters
1283         // Java - u - clashes with CLDR, go with CLDR (year-proleptic) here
1284         // CLDR - U - cycle year name, not supported by 310 yet
1285         // CLDR - l - deprecated
1286         // CLDR - j - not relevant
1287         // CLDR - g - modified-julian-day
1288         // CLDR - z - time-zone names  // TODO properly
1289         // CLDR - Z - different approach here  // TODO bring 310 in line with CLDR
1290         // CLDR - v,V - extended time-zone names
1291         // CLDR - q/c/L - standalone quarter/day-of-week/month
1292         //  310 - I - time-zone id
1293         //  310 - p - prefix for padding
1294     }
1295 
1296     //-----------------------------------------------------------------------
1297     /**
1298      * Causes the next added printer/parser to pad to a fixed width using a space.
1299      * <p>
1300      * This padding will pad to a fixed width using spaces.
1301      * <p>
1302      * An exception will be thrown during printing if the pad width
1303      * is exceeded.
1304      *
1305      * @param padWidth  the pad width, 1 or greater
1306      * @return this, for chaining, not null
1307      * @throws IllegalArgumentException if pad width is too small
1308      */
1309     public DateTimeFormatterBuilder padNext(int padWidth) {
1310         return padNext(padWidth, ' ');
1311     }
1312 
1313     /**
1314      * Causes the next added printer/parser to pad to a fixed width.
1315      * <p>
1316      * This padding is intended for padding other than zero-padding.
1317      * Zero-padding should be achieved using the appendValue methods.
1318      * <p>
1319      * An exception will be thrown during printing if the pad width
1320      * is exceeded.
1321      *
1322      * @param padWidth  the pad width, 1 or greater
1323      * @param padChar  the pad character
1324      * @return this, for chaining, not null
1325      * @throws IllegalArgumentException if pad width is too small
1326      */
1327     public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
1328         if (padWidth < 1) {
1329             throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
1330         }
1331         active.padNextWidth = padWidth;
1332         active.padNextChar = padChar;
1333         active.valueParserIndex = -1;
1334         return this;
1335     }
1336 
1337     //-----------------------------------------------------------------------
1338     /**
1339      * Mark the start of an optional section.
1340      * <p>
1341      * The output of printing can include optional sections, which may be nested.
1342      * An optional section is started by calling this method and ended by calling
1343      * {@link #optionalEnd()} or by ending the build process.
1344      * <p>
1345      * All elements in the optional section are treated as optional.
1346      * During printing, the section is only output if data is available in the
1347      * {@code TemporalAccessor} for all the elements in the section.
1348      * During parsing, the whole section may be missing from the parsed string.
1349      * <p>
1350      * For example, consider a builder setup as
1351      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
1352      * The optional section ends automatically at the end of the builder.
1353      * During printing, the minute will only be output if its value can be obtained from the date-time.
1354      * During parsing, the input will be successfully parsed whether the minute is present or not.
1355      *
1356      * @return this, for chaining, not null
1357      */
1358     public DateTimeFormatterBuilder optionalStart() {
1359         active.valueParserIndex = -1;
1360         active = new DateTimeFormatterBuilder(active, true);
1361         return this;
1362     }
1363 
1364     /**
1365      * Ends an optional section.
1366      * <p>
1367      * The output of printing can include optional sections, which may be nested.
1368      * An optional section is started by calling {@link #optionalStart()} and ended
1369      * using this method (or at the end of the builder).
1370      * <p>
1371      * Calling this method without having previously called {@code optionalStart}
1372      * will throw an exception.
1373      * Calling this method immediately after calling {@code optionalStart} has no effect
1374      * on the formatter other than ending the (empty) optional section.
1375      * <p>
1376      * All elements in the optional section are treated as optional.
1377      * During printing, the section is only output if data is available in the
1378      * {@code TemporalAccessor} for all the elements in the section.
1379      * During parsing, the whole section may be missing from the parsed string.
1380      * <p>
1381      * For example, consider a builder setup as
1382      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}.
1383      * During printing, the minute will only be output if its value can be obtained from the date-time.
1384      * During parsing, the input will be successfully parsed whether the minute is present or not.
1385      *
1386      * @return this, for chaining, not null
1387      * @throws IllegalStateException if there was no previous call to {@code optionalStart}
1388      */
1389     public DateTimeFormatterBuilder optionalEnd() {
1390         if (active.parent == null) {
1391             throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
1392         }
1393         if (active.printerParsers.size() > 0) {
1394             CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
1395             active = active.parent;
1396             appendInternal(cpp);
1397         } else {
1398             active = active.parent;
1399         }
1400         return this;
1401     }
1402 
1403     //-----------------------------------------------------------------------
1404     /**
1405      * Appends a printer and/or parser to the internal list handling padding.
1406      *
1407      * @param pp  the printer-parser to add, not null
1408      * @return the index into the active parsers list
1409      */
1410     private int appendInternal(DateTimePrinterParser pp) {
1411         Objects.requireNonNull(pp, "pp");
1412         if (active.padNextWidth > 0) {
1413             if (pp != null) {
1414                 pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar);
1415             }
1416             active.padNextWidth = 0;
1417             active.padNextChar = 0;
1418         }
1419         active.printerParsers.add(pp);
1420         active.valueParserIndex = -1;
1421         return active.printerParsers.size() - 1;
1422     }
1423 
1424     //-----------------------------------------------------------------------
1425     /**
1426      * Completes this builder by creating the DateTimeFormatter using the default locale.
1427      * <p>
1428      * This will create a formatter with the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
1429      * Numbers will be printed and parsed using the standard non-localized set of symbols.
1430      * <p>
1431      * Calling this method will end any open optional sections by repeatedly
1432      * calling {@link #optionalEnd()} before creating the formatter.
1433      * <p>
1434      * This builder can still be used after creating the formatter if desired,
1435      * although the state may have been changed by calls to {@code optionalEnd}.
1436      *
1437      * @return the created formatter, not null
1438      */
1439     public DateTimeFormatter toFormatter() {
1440         return toFormatter(Locale.getDefault(Locale.Category.FORMAT));
1441     }
1442 
1443     /**
1444      * Completes this builder by creating the DateTimeFormatter using the specified locale.
1445      * <p>
1446      * This will create a formatter with the specified locale.
1447      * Numbers will be printed and parsed using the standard non-localized set of symbols.
1448      * <p>
1449      * Calling this method will end any open optional sections by repeatedly
1450      * calling {@link #optionalEnd()} before creating the formatter.
1451      * <p>
1452      * This builder can still be used after creating the formatter if desired,
1453      * although the state may have been changed by calls to {@code optionalEnd}.
1454      *
1455      * @param locale  the locale to use for formatting, not null
1456      * @return the created formatter, not null
1457      */
1458     public DateTimeFormatter toFormatter(Locale locale) {
1459         Objects.requireNonNull(locale, "locale");
1460         while (active.parent != null) {
1461             optionalEnd();
1462         }
1463         CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
1464         return new DateTimeFormatter(pp, locale, DateTimeFormatSymbols.STANDARD, null, null);
1465     }
1466 
1467     //-----------------------------------------------------------------------
1468     /**
1469      * Strategy for printing/parsing date-time information.
1470      * <p>
1471      * The printer may print any part, or the whole, of the input date-time object.
1472      * Typically, a complete print is constructed from a number of smaller
1473      * units, each outputting a single field.
1474      * <p>
1475      * The parser may parse any piece of text from the input, storing the result
1476      * in the context. Typically, each individual parser will just parse one
1477      * field, such as the day-of-month, storing the value in the context.
1478      * Once the parse is complete, the caller will then convert the context
1479      * to a {@link DateTimeBuilder} to merge the parsed values to create the
1480      * desired object, such as a {@code LocalDate}.
1481      * <p>
1482      * The parse position will be updated during the parse. Parsing will start at
1483      * the specified index and the return value specifies the new parse position
1484      * for the next parser. If an error occurs, the returned index will be negative
1485      * and will have the error position encoded using the complement operator.
1486      *
1487      * <h3>Specification for implementors</h3>
1488      * This interface must be implemented with care to ensure other classes operate correctly.
1489      * All implementations that can be instantiated must be final, immutable and thread-safe.
1490      * <p>
1491      * The context is not a thread-safe object and a new instance will be created
1492      * for each print that occurs. The context must not be stored in an instance
1493      * variable or shared with any other threads.
1494      */
1495     interface DateTimePrinterParser {
1496 
1497         /**
1498          * Prints the date-time object to the buffer.
1499          * <p>
1500          * The context holds information to use during the print.
1501          * It also contains the date-time information to be printed.
1502          * <p>
1503          * The buffer must not be mutated beyond the content controlled by the implementation.
1504          *
1505          * @param context  the context to print using, not null
1506          * @param buf  the buffer to append to, not null
1507          * @return false if unable to query the value from the date-time, true otherwise
1508          * @throws DateTimeException if the date-time cannot be printed successfully
1509          */
1510         boolean print(DateTimePrintContext context, StringBuilder buf);
1511 
1512         /**
1513          * Parses text into date-time information.
1514          * <p>
1515          * The context holds information to use during the parse.
1516          * It is also used to store the parsed date-time information.
1517          *
1518          * @param context  the context to use and parse into, not null
1519          * @param text  the input text to parse, not null
1520          * @param position  the position to start parsing at, from 0 to the text length
1521          * @return the new parse position, where negative means an error with the
1522          *  error position encoded using the complement ~ operator
1523          * @throws NullPointerException if the context or text is null
1524          * @throws IndexOutOfBoundsException if the position is invalid
1525          */
1526         int parse(DateTimeParseContext context, CharSequence text, int position);
1527     }
1528 
1529     //-----------------------------------------------------------------------
1530     /**
1531      * Composite printer and parser.
1532      */
1533     static final class CompositePrinterParser implements DateTimePrinterParser {
1534         private final DateTimePrinterParser[] printerParsers;
1535         private final boolean optional;
1536 
1537         CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) {
1538             this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional);
1539         }
1540 
1541         CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
1542             this.printerParsers = printerParsers;
1543             this.optional = optional;
1544         }
1545 
1546         /**
1547          * Returns a copy of this printer-parser with the optional flag changed.
1548          *
1549          * @param optional  the optional flag to set in the copy
1550          * @return the new printer-parser, not null
1551          */
1552         public CompositePrinterParser withOptional(boolean optional) {
1553             if (optional == this.optional) {
1554                 return this;
1555             }
1556             return new CompositePrinterParser(printerParsers, optional);
1557         }
1558 
1559         @Override
1560         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1561             int length = buf.length();
1562             if (optional) {
1563                 context.startOptional();
1564             }
1565             try {
1566                 for (DateTimePrinterParser pp : printerParsers) {
1567                     if (pp.print(context, buf) == false) {
1568                         buf.setLength(length);  // reset buffer
1569                         return true;
1570                     }
1571                 }
1572             } finally {
1573                 if (optional) {
1574                     context.endOptional();
1575                 }
1576             }
1577             return true;
1578         }
1579 
1580         @Override
1581         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1582             if (optional) {
1583                 context.startOptional();
1584                 int pos = position;
1585                 for (DateTimePrinterParser pp : printerParsers) {
1586                     pos = pp.parse(context, text, pos);
1587                     if (pos < 0) {
1588                         context.endOptional(false);
1589                         return position;  // return original position
1590                     }
1591                 }
1592                 context.endOptional(true);
1593                 return pos;
1594             } else {
1595                 for (DateTimePrinterParser pp : printerParsers) {
1596                     position = pp.parse(context, text, position);
1597                     if (position < 0) {
1598                         break;
1599                     }
1600                 }
1601                 return position;
1602             }
1603         }
1604 
1605         @Override
1606         public String toString() {
1607             StringBuilder buf = new StringBuilder();
1608             if (printerParsers != null) {
1609                 buf.append(optional ? "[" : "(");
1610                 for (DateTimePrinterParser pp : printerParsers) {
1611                     buf.append(pp);
1612                 }
1613                 buf.append(optional ? "]" : ")");
1614             }
1615             return buf.toString();
1616         }
1617     }
1618 
1619     //-----------------------------------------------------------------------
1620     /**
1621      * Pads the output to a fixed width.
1622      */
1623     static final class PadPrinterParserDecorator implements DateTimePrinterParser {
1624         private final DateTimePrinterParser printerParser;
1625         private final int padWidth;
1626         private final char padChar;
1627 
1628         /**
1629          * Constructor.
1630          *
1631          * @param printerParser  the printer, not null
1632          * @param padWidth  the width to pad to, 1 or greater
1633          * @param padChar  the pad character
1634          */
1635         PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
1636             // input checked by DateTimeFormatterBuilder
1637             this.printerParser = printerParser;
1638             this.padWidth = padWidth;
1639             this.padChar = padChar;
1640         }
1641 
1642         @Override
1643         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1644             int preLen = buf.length();
1645             if (printerParser.print(context, buf) == false) {
1646                 return false;
1647             }
1648             int len = buf.length() - preLen;
1649             if (len > padWidth) {
1650                 throw new DateTimePrintException(
1651                     "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
1652             }
1653             for (int i = 0; i < padWidth - len; i++) {
1654                 buf.insert(preLen, padChar);
1655             }
1656             return true;
1657         }
1658 
1659         @Override
1660         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1661             if (position > text.length()) {
1662                 throw new IndexOutOfBoundsException();
1663             }
1664             int endPos = position + padWidth;
1665             if (endPos > text.length()) {
1666                 return ~position;  // not enough characters in the string to meet the parse width
1667             }
1668             int pos = position;
1669             while (pos < endPos && text.charAt(pos) == padChar) {
1670                 pos++;
1671             }
1672             text = text.subSequence(0, endPos);
1673             int firstError = 0;
1674             while (pos >= position) {
1675                 int resultPos = printerParser.parse(context, text, pos);
1676                 if (resultPos < 0) {
1677                     // parse of decorated field had an error
1678                     if (firstError == 0) {
1679                         firstError = resultPos;
1680                     }
1681                     // loop around in case the decorated parser can handle the padChar at the start
1682                     pos--;
1683                     continue;
1684                 }
1685                 if (resultPos != endPos) {
1686                     return ~position;  // parse of decorated field didn't parse to the end
1687                 }
1688                 return resultPos;
1689             }
1690             // loop runs at least once, so firstError must be set by the time we get here
1691             return firstError;  // return error from first parse of decorated field
1692         }
1693 
1694         @Override
1695         public String toString() {
1696             return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
1697         }
1698     }
1699 
1700     //-----------------------------------------------------------------------
1701     /**
1702      * Enumeration to apply simple parse settings.
1703      */
1704     static enum SettingsParser implements DateTimePrinterParser {
1705         SENSITIVE,
1706         INSENSITIVE,
1707         STRICT,
1708         LENIENT;
1709 
1710         @Override
1711         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1712             return true;  // nothing to do here
1713         }
1714 
1715         @Override
1716         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1717             // using ordinals to avoid javac synthetic inner class
1718             switch (ordinal()) {
1719                 case 0: context.setCaseSensitive(true); break;
1720                 case 1: context.setCaseSensitive(false); break;
1721                 case 2: context.setStrict(true); break;
1722                 case 3: context.setStrict(false); break;
1723             }
1724             return position;
1725         }
1726 
1727         @Override
1728         public String toString() {
1729             // using ordinals to avoid javac synthetic inner class
1730             switch (ordinal()) {
1731                 case 0: return "ParseCaseSensitive(true)";
1732                 case 1: return "ParseCaseSensitive(false)";
1733                 case 2: return "ParseStrict(true)";
1734                 case 3: return "ParseStrict(false)";
1735             }
1736             throw new IllegalStateException("Unreachable");
1737         }
1738     }
1739 
1740     //-----------------------------------------------------------------------
1741     /**
1742      * Prints or parses a character literal.
1743      */
1744     static final class CharLiteralPrinterParser implements DateTimePrinterParser {
1745         private final char literal;
1746 
1747         CharLiteralPrinterParser(char literal) {
1748             this.literal = literal;
1749         }
1750 
1751         @Override
1752         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1753             buf.append(literal);
1754             return true;
1755         }
1756 
1757         @Override
1758         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1759             int length = text.length();
1760             if (position == length) {
1761                 return ~position;
1762             }
1763             char ch = text.charAt(position);
1764             if (ch != literal) {
1765                 if (context.isCaseSensitive() ||
1766                         (Character.toUpperCase(ch) != Character.toUpperCase(literal) &&
1767                          Character.toLowerCase(ch) != Character.toLowerCase(literal))) {
1768                     return ~position;
1769                 }
1770             }
1771             return position + 1;
1772         }
1773 
1774         @Override
1775         public String toString() {
1776             if (literal == '\'') {
1777                 return "''";
1778             }
1779             return "'" + literal + "'";
1780         }
1781     }
1782 
1783     //-----------------------------------------------------------------------
1784     /**
1785      * Prints or parses a string literal.
1786      */
1787     static final class StringLiteralPrinterParser implements DateTimePrinterParser {
1788         private final String literal;
1789 
1790         StringLiteralPrinterParser(String literal) {
1791             this.literal = literal;  // validated by caller
1792         }
1793 
1794         @Override
1795         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1796             buf.append(literal);
1797             return true;
1798         }
1799 
1800         @Override
1801         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1802             int length = text.length();
1803             if (position > length || position < 0) {
1804                 throw new IndexOutOfBoundsException();
1805             }
1806             if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
1807                 return ~position;
1808             }
1809             return position + literal.length();
1810         }
1811 
1812         @Override
1813         public String toString() {
1814             String converted = literal.replace("'", "''");
1815             return "'" + converted + "'";
1816         }
1817     }
1818 
1819     //-----------------------------------------------------------------------
1820     /**
1821      * Prints and parses a numeric date-time field with optional padding.
1822      */
1823     static class NumberPrinterParser implements DateTimePrinterParser {
1824 
1825         /**
1826          * Array of 10 to the power of n.
1827          */
1828         static final int[] EXCEED_POINTS = new int[] {
1829             0,
1830             10,
1831             100,
1832             1000,
1833             10000,
1834             100000,
1835             1000000,
1836             10000000,
1837             100000000,
1838             1000000000,
1839         };
1840 
1841         final TemporalField field;
1842         final int minWidth;
1843         private final int maxWidth;
1844         private final SignStyle signStyle;
1845         private final int subsequentWidth;
1846 
1847         /**
1848          * Constructor.
1849          *
1850          * @param field  the field to print, not null
1851          * @param minWidth  the minimum field width, from 1 to 19
1852          * @param maxWidth  the maximum field width, from minWidth to 19
1853          * @param signStyle  the positive/negative sign style, not null
1854          */
1855         NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
1856             // validated by caller
1857             this.field = field;
1858             this.minWidth = minWidth;
1859             this.maxWidth = maxWidth;
1860             this.signStyle = signStyle;
1861             this.subsequentWidth = 0;
1862         }
1863 
1864         /**
1865          * Constructor.
1866          *
1867          * @param field  the field to print, not null
1868          * @param minWidth  the minimum field width, from 1 to 19
1869          * @param maxWidth  the maximum field width, from minWidth to 19
1870          * @param signStyle  the positive/negative sign style, not null
1871          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
1872          *  -1 if fixed width due to active adjacent parsing
1873          */
1874         private NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
1875             // validated by caller
1876             this.field = field;
1877             this.minWidth = minWidth;
1878             this.maxWidth = maxWidth;
1879             this.signStyle = signStyle;
1880             this.subsequentWidth = subsequentWidth;
1881         }
1882 
1883         /**
1884          * Returns a new instance with fixed width flag set.
1885          *
1886          * @return a new updated printer-parser, not null
1887          */
1888         NumberPrinterParser withFixedWidth() {
1889             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
1890         }
1891 
1892         /**
1893          * Returns a new instance with an updated subsequent width.
1894          *
1895          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
1896          * @return a new updated printer-parser, not null
1897          */
1898         NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
1899             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
1900         }
1901 
1902         @Override
1903         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1904             Long valueLong = context.getValue(field);
1905             if (valueLong == null) {
1906                 return false;
1907             }
1908             long value = getValue(valueLong);
1909             DateTimeFormatSymbols symbols = context.getSymbols();
1910             String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
1911             if (str.length() > maxWidth) {
1912                 throw new DateTimePrintException("Field " + field.getName() +
1913                     " cannot be printed as the value " + value +
1914                     " exceeds the maximum print width of " + maxWidth);
1915             }
1916             str = symbols.convertNumberToI18N(str);
1917 
1918             if (value >= 0) {
1919                 switch (signStyle) {
1920                     case EXCEEDS_PAD:
1921                         if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
1922                             buf.append(symbols.getPositiveSign());
1923                         }
1924                         break;
1925                     case ALWAYS:
1926                         buf.append(symbols.getPositiveSign());
1927                         break;
1928                 }
1929             } else {
1930                 switch (signStyle) {
1931                     case NORMAL:
1932                     case EXCEEDS_PAD:
1933                     case ALWAYS:
1934                         buf.append(symbols.getNegativeSign());
1935                         break;
1936                     case NOT_NEGATIVE:
1937                         throw new DateTimePrintException("Field " + field.getName() +
1938                             " cannot be printed as the value " + value +
1939                             " cannot be negative according to the SignStyle");
1940                 }
1941             }
1942             for (int i = 0; i < minWidth - str.length(); i++) {
1943                 buf.append(symbols.getZeroDigit());
1944             }
1945             buf.append(str);
1946             return true;
1947         }
1948 
1949         /**
1950          * Gets the value to output.
1951          *
1952          * @param value  the base value of the field, not null
1953          * @return the value
1954          */
1955         long getValue(long value) {
1956             return value;
1957         }
1958 
1959         boolean isFixedWidth() {
1960             return subsequentWidth == -1;
1961         }
1962 
1963         @Override
1964         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1965             int length = text.length();
1966             if (position == length) {
1967                 return ~position;
1968             }
1969             char sign = text.charAt(position);  // IOOBE if invalid position
1970             boolean negative = false;
1971             boolean positive = false;
1972             if (sign == context.getSymbols().getPositiveSign()) {
1973                 if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) {
1974                     return ~position;
1975                 }
1976                 positive = true;
1977                 position++;
1978             } else if (sign == context.getSymbols().getNegativeSign()) {
1979                 if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) {
1980                     return ~position;
1981                 }
1982                 negative = true;
1983                 position++;
1984             } else {
1985                 if (signStyle == SignStyle.ALWAYS && context.isStrict()) {
1986                     return ~position;
1987                 }
1988             }
1989             int effMinWidth = (context.isStrict() || isFixedWidth() ? minWidth : 1);
1990             int minEndPos = position + effMinWidth;
1991             if (minEndPos > length) {
1992                 return ~position;
1993             }
1994             int effMaxWidth = maxWidth + Math.max(subsequentWidth, 0);
1995             long total = 0;
1996             BigInteger totalBig = null;
1997             int pos = position;
1998             for (int pass = 0; pass < 2; pass++) {
1999                 int maxEndPos = Math.min(pos + effMaxWidth, length);
2000                 while (pos < maxEndPos) {
2001                     char ch = text.charAt(pos++);
2002                     int digit = context.getSymbols().convertToDigit(ch);
2003                     if (digit < 0) {
2004                         pos--;
2005                         if (pos < minEndPos) {
2006                             return ~position;  // need at least min width digits
2007                         }
2008                         break;
2009                     }
2010                     if ((pos - position) > 18) {
2011                         if (totalBig == null) {
2012                             totalBig = BigInteger.valueOf(total);
2013                         }
2014                         totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
2015                     } else {
2016                         total = total * 10 + digit;
2017                     }
2018                 }
2019                 if (subsequentWidth > 0 && pass == 0) {
2020                     // re-parse now we know the correct width
2021                     int parseLen = pos - position;
2022                     effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth);
2023                     pos = position;
2024                     total = 0;
2025                     totalBig = null;
2026                 } else {
2027                     break;
2028                 }
2029             }
2030             if (negative) {
2031                 if (totalBig != null) {
2032                     if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) {
2033                         return ~(position - 1);  // minus zero not allowed
2034                     }
2035                     totalBig = totalBig.negate();
2036                 } else {
2037                     if (total == 0 && context.isStrict()) {
2038                         return ~(position - 1);  // minus zero not allowed
2039                     }
2040                     total = -total;
2041                 }
2042             } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
2043                 int parseLen = pos - position;
2044                 if (positive) {
2045                     if (parseLen <= minWidth) {
2046                         return ~(position - 1);  // '+' only parsed if minWidth exceeded
2047                     }
2048                 } else {
2049                     if (parseLen > minWidth) {
2050                         return ~position;  // '+' must be parsed if minWidth exceeded
2051                     }
2052                 }
2053             }
2054             if (totalBig != null) {
2055                 if (totalBig.bitLength() > 63) {
2056                     // overflow, parse 1 less digit
2057                     totalBig = totalBig.divide(BigInteger.TEN);
2058                     pos--;
2059                 }
2060                 setValue(context, totalBig.longValue());
2061             } else {
2062                 setValue(context, total);
2063             }
2064             return pos;
2065         }
2066 
2067         /**
2068          * Stores the value.
2069          *
2070          * @param context  the context to store into, not null
2071          * @param value  the value
2072          */
2073         void setValue(DateTimeParseContext context, long value) {
2074             context.setParsedField(field, value);
2075         }
2076 
2077         @Override
2078         public String toString() {
2079             if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
2080                 return "Value(" + field.getName() + ")";
2081             }
2082             if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
2083                 return "Value(" + field.getName() + "," + minWidth + ")";
2084             }
2085             return "Value(" + field.getName() + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
2086         }
2087     }
2088 
2089     //-----------------------------------------------------------------------
2090     /**
2091      * Prints and parses a reduced numeric date-time field.
2092      */
2093     static final class ReducedPrinterParser extends NumberPrinterParser {
2094         private final int baseValue;
2095         private final int range;
2096 
2097         /**
2098          * Constructor.
2099          *
2100          * @param field  the field to print, validated not null
2101          * @param width  the field width, from 1 to 18
2102          * @param baseValue  the base value
2103          */
2104         ReducedPrinterParser(TemporalField field, int width, int baseValue) {
2105             super(field, width, width, SignStyle.NOT_NEGATIVE);
2106             if (width < 1 || width > 18) {
2107                 throw new IllegalArgumentException("The width must be from 1 to 18 inclusive but was " + width);
2108             }
2109             if (field.range().isValidValue(baseValue) == false) {
2110                 throw new IllegalArgumentException("The base value must be within the range of the field");
2111             }
2112             this.baseValue = baseValue;
2113             this.range = EXCEED_POINTS[width];
2114             if ((((long) baseValue) + range) > Integer.MAX_VALUE) {
2115                 throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
2116             }
2117         }
2118 
2119         @Override
2120         long getValue(long value) {
2121             return Math.abs(value % range);
2122         }
2123 
2124         @Override
2125         void setValue(DateTimeParseContext context, long value) {
2126             int lastPart = baseValue % range;
2127             if (baseValue > 0) {
2128                 value = baseValue - lastPart + value;
2129             } else {
2130                 value = baseValue - lastPart - value;
2131             }
2132             if (value < baseValue) {
2133                 value += range;
2134             }
2135             context.setParsedField(field, value);
2136         }
2137 
2138         @Override
2139         NumberPrinterParser withFixedWidth() {
2140             return this;
2141         }
2142 
2143         @Override
2144         boolean isFixedWidth() {
2145             return true;
2146         }
2147 
2148         @Override
2149         public String toString() {
2150             return "ReducedValue(" + field.getName() + "," + minWidth + "," + baseValue + ")";
2151         }
2152     }
2153 
2154     //-----------------------------------------------------------------------
2155     /**
2156      * Prints and parses a numeric date-time field with optional padding.
2157      */
2158     static final class FractionPrinterParser implements DateTimePrinterParser {
2159         private final TemporalField field;
2160         private final int minWidth;
2161         private final int maxWidth;
2162         private final boolean decimalPoint;
2163 
2164         /**
2165          * Constructor.
2166          *
2167          * @param field  the field to output, not null
2168          * @param minWidth  the minimum width to output, from 0 to 9
2169          * @param maxWidth  the maximum width to output, from 0 to 9
2170          * @param decimalPoint  whether to output the localized decimal point symbol
2171          */
2172         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
2173             Objects.requireNonNull(field, "field");
2174             if (field.range().isFixed() == false) {
2175                 throw new IllegalArgumentException("Field must have a fixed set of values: " + field.getName());
2176             }
2177             if (minWidth < 0 || minWidth > 9) {
2178                 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
2179             }
2180             if (maxWidth < 1 || maxWidth > 9) {
2181                 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
2182             }
2183             if (maxWidth < minWidth) {
2184                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2185                         maxWidth + " < " + minWidth);
2186             }
2187             this.field = field;
2188             this.minWidth = minWidth;
2189             this.maxWidth = maxWidth;
2190             this.decimalPoint = decimalPoint;
2191         }
2192 
2193         @Override
2194         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2195             Long value = context.getValue(field);
2196             if (value == null) {
2197                 return false;
2198             }
2199             DateTimeFormatSymbols symbols = context.getSymbols();
2200             BigDecimal fraction = convertToFraction(value);
2201             if (fraction.scale() == 0) {  // scale is zero if value is zero
2202                 if (minWidth > 0) {
2203                     if (decimalPoint) {
2204                         buf.append(symbols.getDecimalSeparator());
2205                     }
2206                     for (int i = 0; i < minWidth; i++) {
2207                         buf.append(symbols.getZeroDigit());
2208                     }
2209                 }
2210             } else {
2211                 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
2212                 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
2213                 String str = fraction.toPlainString().substring(2);
2214                 str = symbols.convertNumberToI18N(str);
2215                 if (decimalPoint) {
2216                     buf.append(symbols.getDecimalSeparator());
2217                 }
2218                 buf.append(str);
2219             }
2220             return true;
2221         }
2222 
2223         @Override
2224         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2225             int effectiveMin = (context.isStrict() ? minWidth : 0);
2226             int effectiveMax = (context.isStrict() ? maxWidth : 9);
2227             int length = text.length();
2228             if (position == length) {
2229                 // valid if whole field is optional, invalid if minimum width
2230                 return (effectiveMin > 0 ? ~position : position);
2231             }
2232             if (decimalPoint) {
2233                 if (text.charAt(position) != context.getSymbols().getDecimalSeparator()) {
2234                     // valid if whole field is optional, invalid if minimum width
2235                     return (effectiveMin > 0 ? ~position : position);
2236                 }
2237                 position++;
2238             }
2239             int minEndPos = position + effectiveMin;
2240             if (minEndPos > length) {
2241                 return ~position;  // need at least min width digits
2242             }
2243             int maxEndPos = Math.min(position + effectiveMax, length);
2244             int total = 0;  // can use int because we are only parsing up to 9 digits
2245             int pos = position;
2246             while (pos < maxEndPos) {
2247                 char ch = text.charAt(pos++);
2248                 int digit = context.getSymbols().convertToDigit(ch);
2249                 if (digit < 0) {
2250                     if (pos < minEndPos) {
2251                         return ~position;  // need at least min width digits
2252                     }
2253                     pos--;
2254                     break;
2255                 }
2256                 total = total * 10 + digit;
2257             }
2258             BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
2259             long value = convertFromFraction(fraction);
2260             context.setParsedField(field, value);
2261             return pos;
2262         }
2263 
2264         /**
2265          * Converts a value for this field to a fraction between 0 and 1.
2266          * <p>
2267          * The fractional value is between 0 (inclusive) and 1 (exclusive).
2268          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
2269          * The fraction is obtained by calculation from the field range using 9 decimal
2270          * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
2271          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
2272          * <p>
2273          * For example, the second-of-minute value of 15 would be returned as 0.25,
2274          * assuming the standard definition of 60 seconds in a minute.
2275          *
2276          * @param value  the value to convert, must be valid for this rule
2277          * @return the value as a fraction within the range, from 0 to 1, not null
2278          * @throws DateTimeException if the value cannot be converted to a fraction
2279          */
2280         private BigDecimal convertToFraction(long value) {
2281             ValueRange range = field.range();
2282             range.checkValidValue(value, field);
2283             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
2284             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
2285             BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
2286             BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
2287             // stripTrailingZeros bug
2288             return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
2289         }
2290 
2291         /**
2292          * Converts a fraction from 0 to 1 for this field to a value.
2293          * <p>
2294          * The fractional value must be between 0 (inclusive) and 1 (exclusive).
2295          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
2296          * The value is obtained by calculation from the field range and a rounding
2297          * mode of {@link RoundingMode#FLOOR FLOOR}.
2298          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
2299          * <p>
2300          * For example, the fractional second-of-minute of 0.25 would be converted to 15,
2301          * assuming the standard definition of 60 seconds in a minute.
2302          *
2303          * @param fraction  the fraction to convert, not null
2304          * @return the value of the field, valid for this rule
2305          * @throws DateTimeException if the value cannot be converted
2306          */
2307         private long convertFromFraction(BigDecimal fraction) {
2308             ValueRange range = field.range();
2309             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
2310             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
2311             BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
2312             return valueBD.longValueExact();
2313         }
2314 
2315         @Override
2316         public String toString() {
2317             String decimal = (decimalPoint ? ",DecimalPoint" : "");
2318             return "Fraction(" + field.getName() + "," + minWidth + "," + maxWidth + decimal + ")";
2319         }
2320     }
2321 
2322     //-----------------------------------------------------------------------
2323     /**
2324      * Prints or parses field text.
2325      */
2326     static final class TextPrinterParser implements DateTimePrinterParser {
2327         private final TemporalField field;
2328         private final TextStyle textStyle;
2329         private final DateTimeTextProvider provider;
2330         /**
2331          * The cached number printer parser.
2332          * Immutable and volatile, so no synchronization needed.
2333          */
2334         private volatile NumberPrinterParser numberPrinterParser;
2335 
2336         /**
2337          * Constructor.
2338          *
2339          * @param field  the field to output, not null
2340          * @param textStyle  the text style, not null
2341          * @param provider  the text provider, not null
2342          */
2343         TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
2344             // validated by caller
2345             this.field = field;
2346             this.textStyle = textStyle;
2347             this.provider = provider;
2348         }
2349 
2350         @Override
2351         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2352             Long value = context.getValue(field);
2353             if (value == null) {
2354                 return false;
2355             }
2356             String text = null;
2357             if (field == ChronoField.ERA) {
2358                 Chrono chrono = context.getTemporal().query(Queries.chrono());
2359                 if (chrono == null) {
2360                     chrono = ISOChrono.INSTANCE;
2361                 }
2362                 text = provider.getEraText(chrono, value, textStyle, context.getLocale());
2363             } else {
2364                 text = provider.getText(field, value, textStyle, context.getLocale());
2365             }
2366             if (text == null) {
2367                 return numberPrinterParser().print(context, buf);
2368             }
2369             buf.append(text);
2370             return true;
2371         }
2372 
2373         @Override
2374         public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
2375             int length = parseText.length();
2376             if (position < 0 || position > length) {
2377                 throw new IndexOutOfBoundsException();
2378             }
2379             TextStyle style = (context.isStrict() ? textStyle : null);
2380             Iterator<Entry<String, Long>> it = provider.getTextIterator(field, style, context.getLocale());
2381             if (it != null) {
2382                 while (it.hasNext()) {
2383                     Entry<String, Long> entry = it.next();
2384                     String itText = entry.getKey();
2385                     if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
2386                         context.setParsedField(field, entry.getValue());
2387                         return position + itText.length();
2388                     }
2389                 }
2390                 if (context.isStrict()) {
2391                     return ~position;
2392                 }
2393             }
2394             return numberPrinterParser().parse(context, parseText, position);
2395         }
2396 
2397         /**
2398          * Create and cache a number printer parser.
2399          * @return the number printer parser for this field, not null
2400          */
2401         private NumberPrinterParser numberPrinterParser() {
2402             if (numberPrinterParser == null) {
2403                 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
2404             }
2405             return numberPrinterParser;
2406         }
2407 
2408         @Override
2409         public String toString() {
2410             if (textStyle == TextStyle.FULL) {
2411                 return "Text(" + field.getName() + ")";
2412             }
2413             return "Text(" + field.getName() + "," + textStyle + ")";
2414         }
2415     }
2416 
2417     //-----------------------------------------------------------------------
2418     /**
2419      * Prints or parses an ISO-8601 instant.
2420      */
2421     static final class InstantPrinterParser implements DateTimePrinterParser {
2422         // days in a 400 year cycle = 146097
2423         // days in a 10,000 year cycle = 146097 * 25
2424         // seconds per day = 86400
2425         private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
2426         private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
2427         private static final CompositePrinterParser PARSER = new DateTimeFormatterBuilder()
2428                     .parseCaseInsensitive()
2429                     .append(DateTimeFormatters.isoLocalDate()).appendLiteral('T')
2430                     .append(DateTimeFormatters.isoLocalTime()).appendLiteral('Z')
2431                     .toFormatter().toPrinterParser(false);
2432 
2433         InstantPrinterParser() {
2434         }
2435 
2436         @Override
2437         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2438             // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
2439             Long inSecs = context.getValue(INSTANT_SECONDS);
2440             Long inNanos = context.getValue(NANO_OF_SECOND);
2441             if (inSecs == null || inNanos == null) {
2442                 return false;
2443             }
2444             long inSec = inSecs;
2445             int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos);
2446             if (inSec >= -SECONDS_0000_TO_1970) {
2447                 // current era
2448                 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
2449                 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
2450                 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
2451                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, inNano, ZoneOffset.UTC);
2452                 if (hi > 0) {
2453                     buf.append('+').append(hi);
2454                 }
2455                 buf.append(ldt).append('Z');
2456             } else {
2457                 // before current era
2458                 long zeroSecs = inSec + SECONDS_0000_TO_1970;
2459                 long hi = zeroSecs / SECONDS_PER_10000_YEARS;
2460                 long lo = zeroSecs % SECONDS_PER_10000_YEARS;
2461                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, inNano, ZoneOffset.UTC);
2462                 int pos = buf.length();
2463                 buf.append(ldt).append('Z');
2464                 if (hi < 0) {
2465                     if (ldt.getYear() == -10_000) {
2466                         buf.replace(pos, pos + 2, Long.toString(hi - 1));
2467                     } else if (lo == 0) {
2468                         buf.insert(pos, hi);
2469                     } else {
2470                         buf.insert(pos + 1, Math.abs(hi));
2471                     }
2472                 }
2473             }
2474             return true;
2475         }
2476 
2477         @Override
2478         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2479             // new context to avoid overwriting fields like year/month/day
2480             DateTimeParseContext newContext = context.copy();
2481             int pos = PARSER.parse(newContext, text, position);
2482             if (pos < 0) {
2483                 return pos;
2484             }
2485             // parser restricts most fields to 2 digits, so definitely int
2486             // correctly parsed nano is also guaranteed to be valid
2487             long yearParsed = newContext.getParsed(YEAR);
2488             int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
2489             int day = newContext.getParsed(DAY_OF_MONTH).intValue();
2490             int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
2491             int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
2492             Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
2493             Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
2494             int sec = (secVal != null ? secVal.intValue() : 0);
2495             int nano = (nanoVal != null ? nanoVal.intValue() : 0);
2496             int year = (int) yearParsed % 10_000;
2497             long instantSecs;
2498             try {
2499                 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0);
2500                 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
2501                 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
2502             } catch (RuntimeException ex) {
2503                 return ~position;
2504             }
2505             context.setParsedField(INSTANT_SECONDS, instantSecs);
2506             context.setParsedField(NANO_OF_SECOND, nano);
2507             return text.length();
2508         }
2509 
2510         @Override
2511         public String toString() {
2512             return "Instant()";
2513         }
2514     }
2515 
2516     //-----------------------------------------------------------------------
2517     /**
2518      * Prints or parses an offset ID.
2519      */
2520     static final class OffsetIdPrinterParser implements DateTimePrinterParser {
2521         static final String[] PATTERNS = new String[] {
2522             "+HH", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS",
2523         };  // order used in pattern builder
2524         static final OffsetIdPrinterParser INSTANCE_ID = new OffsetIdPrinterParser("Z", "+HH:MM:ss");
2525 
2526         private final String noOffsetText;
2527         private final int type;
2528 
2529         /**
2530          * Constructor.
2531          *
2532          * @param noOffsetText  the text to use for UTC, not null
2533          * @param pattern  the pattern
2534          */
2535         OffsetIdPrinterParser(String noOffsetText, String pattern) {
2536             Objects.requireNonNull(noOffsetText, "noOffsetText");
2537             Objects.requireNonNull(pattern, "pattern");
2538             this.noOffsetText = noOffsetText;
2539             this.type = checkPattern(pattern);
2540         }
2541 
2542         private int checkPattern(String pattern) {
2543             for (int i = 0; i < PATTERNS.length; i++) {
2544                 if (PATTERNS[i].equals(pattern)) {
2545                     return i;
2546                 }
2547             }
2548             throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
2549         }
2550 
2551         @Override
2552         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2553             Long offsetSecs = context.getValue(OFFSET_SECONDS);
2554             if (offsetSecs == null) {
2555                 return false;
2556             }
2557             int totalSecs = Math.toIntExact(offsetSecs);
2558             if (totalSecs == 0) {
2559                 buf.append(noOffsetText);
2560             } else {
2561                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
2562                 int absMinutes = Math.abs((totalSecs / 60) % 60);
2563                 int absSeconds = Math.abs(totalSecs % 60);
2564                 buf.append(totalSecs < 0 ? "-" : "+")
2565                     .append((char) (absHours / 10 + '0')).append((char) (absHours % 10 + '0'));
2566                 if (type >= 1) {
2567                     buf.append((type % 2) == 0 ? ":" : "")
2568                         .append((char) (absMinutes / 10 + '0')).append((char) (absMinutes % 10 + '0'));
2569                     if (type >= 5 || (type >= 3 && absSeconds > 0)) {
2570                         buf.append((type % 2) == 0 ? ":" : "")
2571                             .append((char) (absSeconds / 10 + '0')).append((char) (absSeconds % 10 + '0'));
2572                     }
2573                 }
2574             }
2575             return true;
2576         }
2577 
2578         @Override
2579         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2580             int length = text.length();
2581             int noOffsetLen = noOffsetText.length();
2582             if (noOffsetLen == 0) {
2583                 if (position == length) {
2584                     context.setParsedField(OFFSET_SECONDS, 0);
2585                     return position;
2586                 }
2587             } else {
2588                 if (position == length) {
2589                     return ~position;
2590                 }
2591                 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
2592                     context.setParsedField(OFFSET_SECONDS, 0);
2593                     return position + noOffsetLen;
2594                 }
2595             }
2596 
2597             // parse normal plus/minus offset
2598             char sign = text.charAt(position);  // IOOBE if invalid position
2599             if (sign == '+' || sign == '-') {
2600                 // starts
2601                 int negative = (sign == '-' ? -1 : 1);
2602                 int[] array = new int[4];
2603                 array[0] = position + 1;
2604                 if (parseNumber(array, 1, text, true) ||
2605                         parseNumber(array, 2, text, type > 0) ||
2606                         parseNumber(array, 3, text, false)) {
2607                     return ~position;
2608                 }
2609                 long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
2610                 context.setParsedField(OFFSET_SECONDS, offsetSecs);
2611                 return array[0];
2612             } else {
2613                 // handle special case of empty no offset text
2614                 if (noOffsetLen == 0) {
2615                     context.setParsedField(OFFSET_SECONDS, 0);
2616                     return position + noOffsetLen;
2617                 }
2618                 return ~position;
2619             }
2620         }
2621 
2622         /**
2623          * Parse a two digit zero-prefixed number.
2624          *
2625          * @param array  the array of parsed data, 0=pos,1=hours,2=mins,3=secs, not null
2626          * @param arrayIndex  the index to parse the value into
2627          * @param parseText  the offset ID, not null
2628          * @param required  whether this number is required
2629          * @return true if an error occurred
2630          */
2631         private boolean parseNumber(int[] array, int arrayIndex, CharSequence parseText, boolean required) {
2632             if ((type + 3) / 2 < arrayIndex) {
2633                 return false;  // ignore seconds/minutes
2634             }
2635             int pos = array[0];
2636             if ((type % 2) == 0 && arrayIndex > 1) {
2637                 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
2638                     return required;
2639                 }
2640                 pos++;
2641             }
2642             if (pos + 2 > parseText.length()) {
2643                 return required;
2644             }
2645             char ch1 = parseText.charAt(pos++);
2646             char ch2 = parseText.charAt(pos++);
2647             if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
2648                 return required;
2649             }
2650             int value = (ch1 - 48) * 10 + (ch2 - 48);
2651             if (value < 0 || value > 59) {
2652                 return required;
2653             }
2654             array[arrayIndex] = value;
2655             array[0] = pos;
2656             return false;
2657         }
2658 
2659         @Override
2660         public String toString() {
2661             String converted = noOffsetText.replace("'", "''");
2662             return "Offset('" + converted + "'," + PATTERNS[type] + ")";
2663         }
2664     }
2665 
2666     //-----------------------------------------------------------------------
2667     /**
2668      * Prints or parses a zone ID.
2669      */
2670     static final class ZoneTextPrinterParser implements DateTimePrinterParser {
2671 
2672         /** The text style to output. */
2673         private final TextStyle textStyle;
2674 
2675         ZoneTextPrinterParser(TextStyle textStyle) {
2676             this.textStyle = Objects.requireNonNull(textStyle, "textStyle");
2677         }
2678 
2679         private static final int STD = 0;
2680         private static final int DST = 1;
2681         private static final int GENERIC = 2;
2682 
2683         private static final Map<String, SoftReference<Map<Locale, String[]>>> cache =
2684             new ConcurrentHashMap<>();
2685 
2686         private static String getDisplayName(String id, int type, TextStyle style, Locale locale) {
2687             if (style == TextStyle.NARROW) {
2688                 return null;
2689             }
2690             String[] names;
2691             SoftReference<Map<Locale, String[]>> ref = cache.get(id);
2692             Map<Locale, String[]> perLocale;
2693             if (ref == null || (perLocale = ref.get()) == null ||
2694                 (names = perLocale.get(locale)) == null) {
2695                 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
2696                 if (names == null) {
2697                     return null;
2698                 }
2699                 names = Arrays.copyOfRange(names, 0, 7);
2700                 names[5] =
2701                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG,locale);
2702                 if (names[5] == null) {
2703                     names[5] = names[0]; // use the id
2704                 }
2705                 names[6] =
2706                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT,locale);
2707                 if (names[6] == null) {
2708                     names[6] = names[0];
2709                 }
2710                 perLocale = new ConcurrentHashMap<>();
2711                 perLocale.put(locale, names);
2712                 ref = new SoftReference<>(perLocale);
2713                 cache.put(id, ref);
2714             }
2715             switch (type) {
2716             case STD:
2717                 return names[style.ordinal() + 1];
2718             case DST:
2719                 return names[style.ordinal() + 3];
2720             }
2721             return names[style.ordinal() + 5];
2722         }
2723 
2724         @Override
2725         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2726             ZoneId zone = context.getValue(Queries.zoneId());
2727             if (zone == null) {
2728                 return false;
2729             }
2730             if (zone instanceof ZoneOffset) {
2731                 buf.append(zone.getId());
2732             } else {
2733                 TemporalAccessor dt = context.getTemporal();
2734                 Instant instant = null;
2735                 if (dt.isSupported(ChronoField.INSTANT_SECONDS)) {
2736                     instant = Instant.from(dt);
2737                 }
2738                 String name = getDisplayName(zone.getId(),
2739                                              instant == null ? GENERIC
2740                                                              : (zone.getRules().isDaylightSavings(instant) ? DST : STD),
2741                     textStyle, context.getLocale());
2742                 if (name != null) {
2743                     buf.append(name);
2744                 } else {
2745                     buf.append(zone.getId());
2746                 }
2747             }
2748             return true;
2749         }
2750 
2751         @Override
2752         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2753             throw new UnsupportedOperationException();
2754         }
2755 
2756         @Override
2757         public String toString() {
2758             return "ZoneText(" + textStyle + ")";
2759         }
2760     }
2761 
2762     //-----------------------------------------------------------------------
2763     /**
2764      * Prints or parses a zone ID.
2765      */
2766     static final class ZoneIdPrinterParser implements DateTimePrinterParser {
2767         private final TemporalQuery<ZoneId> query;
2768         private final String description;
2769 
2770         ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
2771             this.query = query;
2772             this.description = description;
2773         }
2774 
2775         //-----------------------------------------------------------------------
2776         @Override
2777         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2778             ZoneId zone = context.getValue(query);
2779             if (zone == null) {
2780                 return false;
2781             }
2782             buf.append(zone.getId());
2783             return true;
2784         }
2785 
2786         //-----------------------------------------------------------------------
2787         /**
2788          * The cached tree to speed up parsing.
2789          */
2790         private static volatile Entry<Integer, PrefixTree> cachedPrefixTree;
2791         private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI;
2792 
2793         /**
2794          * This implementation looks for the longest matching string.
2795          * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
2796          * Etc/GMC although both are valid.
2797          */
2798         @Override
2799         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2800             int length = text.length();
2801             if (position > length) {
2802                 throw new IndexOutOfBoundsException();
2803             }
2804 
2805             // handle fixed time-zone IDs
2806             if ((text.length() - position) >= 1) {
2807                 char nextChar = text.charAt(position);
2808                 if (nextChar == '+' || nextChar == '-') {
2809                     DateTimeParseContext newContext = context.copy();
2810                     int endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position);
2811                     if (endPos < 0) {
2812                         return endPos;
2813                     }
2814                     int offset = (int) (long) newContext.getParsed(OFFSET_SECONDS);
2815                     ZoneId zone = ZoneOffset.ofTotalSeconds(offset);
2816                     context.setParsed(zone);
2817                     return endPos;
2818                 }
2819             }
2820 
2821             // prepare parse tree
2822             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
2823             final int regionIdsSize = regionIds.size();
2824             Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
2825                                                 ? cachedPrefixTree : cachedPrefixTreeCI;
2826             if (cached == null || cached.getKey() != regionIdsSize) {
2827                 synchronized (this) {
2828                     cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
2829                     if (cached == null || cached.getKey() != regionIdsSize) {
2830                         cached = new SimpleImmutableEntry<>(regionIdsSize,
2831                             PrefixTree.newTree(regionIds, context.isCaseSensitive()
2832                                                           ? PrefixTree.STRICT : PrefixTree.CASE_INSENSITIVE));
2833                         if (context.isCaseSensitive()) {
2834                             cachedPrefixTree = cached;
2835                         } else {
2836                             cachedPrefixTreeCI = cached;
2837                         }
2838                     }
2839                 }
2840             }
2841             PrefixTree tree = cached.getValue();
2842 
2843             // parse
2844             String parsedZoneId = tree.match(text, position, length);
2845             if (parsedZoneId == null || regionIds.contains(parsedZoneId) == false) {
2846                 if (text.charAt(position) == 'Z') {
2847                     context.setParsed(ZoneOffset.UTC);
2848                     return position + 1;
2849                 }
2850                 return ~position;
2851             }
2852             context.setParsed(ZoneId.of(parsedZoneId));
2853             return position + parsedZoneId.length();
2854         }
2855 
2856 
2857         @Override
2858         public String toString() {
2859             return description;
2860         }
2861     }
2862 
2863     //-----------------------------------------------------------------------
2864     /**
2865      * A String based prefix tree for parsing time-zone names.
2866      */
2867     static class PrefixTree {
2868         protected String key;
2869         protected String value;
2870         protected char c0;    // performance optimization to avoid the
2871                               // boundary check cost of key.charat(0)
2872         protected PrefixTree child;
2873         protected PrefixTree sibling;
2874 
2875         static final int STRICT = 1;
2876         static final int CASE_INSENSITIVE = 2;
2877         static final int LENIENT = 3;
2878 
2879         private PrefixTree(String k, String v, PrefixTree child) {
2880             this.key = k;
2881             this.value = v;
2882             this.child = child;
2883             if (k.length() == 0){
2884                 c0 = 0xffff;
2885             } else {
2886                 c0 = key.charAt(0);
2887             }
2888         }
2889 
2890         /**
2891          * Creates a new prefix parsing tree.
2892          *
2893          * @param type  the type of the prefix tree. One of the three supported
2894          *  types, STRICT, CASE_INSENSITIVE and LENIENT
2895          * @return the tree, not null
2896          */
2897         public static PrefixTree newTree(int type) {
2898             PrefixTree tree;
2899             switch(type) {
2900                 case STRICT:
2901                     tree = new PrefixTree("", null, null);
2902                     break;
2903                 case CASE_INSENSITIVE:
2904                     tree = new CI("", null, null);
2905                     break;
2906                 case LENIENT:
2907                     tree = new LENIENT("", null, null);
2908                     break;
2909                 default:
2910                     throw new IllegalArgumentException("Unknown type");
2911             }
2912             return tree;
2913         }
2914 
2915         /**
2916          * Creates a new prefix parsing tree.
2917          *
2918          * @param keys  a set of strings to build the prefix parsing tree, not null
2919          * @param type  the type of the prefix tree. One of the three supported
2920          *  types, STRICT, CASE_INSENSITIVE and LENIENT
2921          * @return the tree, not null
2922          */
2923         public static  PrefixTree newTree(Set<String> keys, int type) {
2924             PrefixTree tree = newTree(type);
2925             for (String k : keys) {
2926                 tree.add0(k, k);
2927             }
2928             return tree;
2929         }
2930 
2931         /**
2932          * Adds a pair of {key, value} into the prefix tree.
2933          *
2934          * @param k  the key, not null
2935          * @param v  the value, not null
2936          * @return  true if the pair is added successfully
2937          */
2938         public boolean add(String k, String v) {
2939             return add0(k, v);
2940         }
2941 
2942         private boolean add0(String k, String v) {
2943             k = toKey(k);
2944             int prefixLen = prefixLength(k);
2945             if (prefixLen == key.length()) {
2946                 if (prefixLen < k.length()) {  // down the tree
2947                     String subKey = k.substring(prefixLen);
2948                     PrefixTree c = child;
2949                     while (c != null) {
2950                         if (isEqual(c.c0, subKey.charAt(0))) {
2951                             return c.add0(subKey, v);
2952                         }
2953                         c = c.sibling;
2954                     }
2955                     // add the node as the child of the current node
2956                     c = newNode(subKey, v, null);
2957                     c.sibling = child;
2958                     child = c;
2959                     return true;
2960                 }
2961                 // have an existing <key, value> already, keep it.
2962                 if (value != null) {
2963                     return false;
2964                 }
2965                 value = v;
2966                 return true;
2967             }
2968             // split the existing node
2969             PrefixTree n1 = newNode(key.substring(prefixLen), value, child);
2970             key = k.substring(0, prefixLen);
2971             child = n1;
2972             if (prefixLen < k.length()) {
2973                 PrefixTree n2 = newNode(k.substring(prefixLen), v, null);
2974                 child.sibling = n2;
2975                 value = null;
2976             } else {
2977                 value = v;
2978             }
2979             return true;
2980         }
2981 
2982         /**
2983          * Match text with the prefix tree.
2984          *
2985          * @param text  the input text to parse, not null
2986          * @param off  the offset position to start parsing at
2987          * @param end  the end position to stop parsing
2988          * @return the resulting string, or null if no match found.
2989          */
2990         public String match(CharSequence text, int off, int end) {
2991             if (!prefixOf(text, off, end)){
2992                 return null;
2993             }
2994             if (child != null && (off += key.length()) != end) {
2995                 PrefixTree c = child;
2996                 do {
2997                     if (isEqual(c.c0, text.charAt(off))) {
2998                         String found = c.match(text, off, end);
2999                         if (found != null) {
3000                             return found;
3001                         }
3002                         return value;
3003                     }
3004                     c = c.sibling;
3005                 } while (c != null);
3006             }
3007             return value;
3008         }
3009 
3010         /**
3011          * Match text with the prefix tree.
3012          *
3013          * @param text  the input text to parse, not null
3014          * @param pos  the position to start parsing at, from 0 to the text
3015          *  length. Upon return, position will be updated to the new parse
3016          *  position, or unchanged, if no match found.
3017          * @return the resulting string, or null if no match found.
3018          */
3019         public String match(CharSequence text, ParsePosition pos) {
3020             int off = pos.getIndex();
3021             int end = text.length();
3022             if (!prefixOf(text, off, end)){
3023                 return null;
3024             }
3025             off += key.length();
3026             if (child != null && off != end) {
3027                 PrefixTree c = child;
3028                 do {
3029                     if (isEqual(c.c0, text.charAt(off))) {
3030                         pos.setIndex(off);
3031                         String found = c.match(text, pos);
3032                         if (found != null) {
3033                             return found;
3034                         }
3035                         break;
3036                     }
3037                     c = c.sibling;
3038                 } while (c != null);
3039             }
3040             pos.setIndex(off);
3041             return value;
3042         }
3043 
3044         protected String toKey(String k) {
3045             return k;
3046         }
3047 
3048         protected PrefixTree newNode(String k, String v, PrefixTree child) {
3049             return new PrefixTree(k, v, child);
3050         }
3051 
3052         protected boolean isEqual(char c1, char c2) {
3053             return c1 == c2;
3054         }
3055 
3056         protected boolean prefixOf(CharSequence text, int off, int end) {
3057             if (text instanceof String) {
3058                 return ((String)text).startsWith(key, off);
3059             }
3060             int len = key.length();
3061             if (len > end - off) {
3062                 return false;
3063             }
3064             int off0 = 0;
3065             while (len-- > 0) {
3066                 if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
3067                     return false;
3068                 }
3069             }
3070             return true;
3071         }
3072 
3073         private int prefixLength(String k) {
3074             int off = 0;
3075             while (off < k.length() && off < key.length()) {
3076                 if (!isEqual(k.charAt(off), key.charAt(off))) {
3077                     return off;
3078                 }
3079                 off++;
3080             }
3081             return off;
3082         }
3083 
3084         /**
3085          * Case Insensitive prefix tree.
3086          */
3087         private static class CI extends PrefixTree {
3088 
3089             private CI(String k, String v, PrefixTree child) {
3090                 super(k, v, child);
3091             }
3092 
3093             @Override
3094             protected CI newNode(String k, String v, PrefixTree child) {
3095                 return new CI(k, v, child);
3096             }
3097 
3098             @Override
3099             protected boolean isEqual(char c1, char c2) {
3100                 return c1 == c2 ||
3101                        Character.toUpperCase(c1) == Character.toUpperCase(c2) ||
3102                        Character.toLowerCase(c1) == Character.toLowerCase(c2);
3103             }
3104 
3105             @Override
3106             protected boolean prefixOf(CharSequence text, int off, int end) {
3107                 int len = key.length();
3108                 if (len > end - off) {
3109                     return false;
3110                 }
3111                 int off0 = 0;
3112                 while (len-- > 0) {
3113                     if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
3114                         return false;
3115                     }
3116                 }
3117                 return true;
3118             }
3119         }
3120 
3121         /**
3122          * Lenient prefix tree. Case insensitive and ignores characters
3123          * like space, underscore and slash.
3124          */
3125         private static class LENIENT extends CI {
3126 
3127             private LENIENT(String k, String v, PrefixTree child) {
3128                 super(k, v, child);
3129             }
3130 
3131             @Override
3132             protected CI newNode(String k, String v, PrefixTree child) {
3133                 return new LENIENT(k, v, child);
3134             }
3135 
3136             private boolean isLenientChar(char c) {
3137                 return c == ' ' || c == '_' || c == '/';
3138             }
3139 
3140             protected String toKey(String k) {
3141                 for (int i = 0; i < k.length(); i++) {
3142                     if (isLenientChar(k.charAt(i))) {
3143                         StringBuilder sb = new StringBuilder(k.length());
3144                         sb.append(k, 0, i);
3145                         i++;
3146                         while (i < k.length()) {
3147                             if (!isLenientChar(k.charAt(i))) {
3148                                 sb.append(k.charAt(i));
3149                             }
3150                             i++;
3151                         }
3152                         return sb.toString();
3153                     }
3154                 }
3155                 return k;
3156             }
3157 
3158             @Override
3159             public String match(CharSequence text, ParsePosition pos) {
3160                 int off = pos.getIndex();
3161                 int end = text.length();
3162                 int len = key.length();
3163                 int koff = 0;
3164                 while (koff < len && off < end) {
3165                     if (isLenientChar(text.charAt(off))) {
3166                         off++;
3167                         continue;
3168                     }
3169                     if (!isEqual(key.charAt(koff++), text.charAt(off++))) {
3170                         return null;
3171                     }
3172                 }
3173                 if (koff != len) {
3174                     return null;
3175                 }
3176                 if (child != null && off != end) {
3177                     int off0 = off;
3178                     while (off0 < end && isLenientChar(text.charAt(off0))) {
3179                         off0++;
3180                     }
3181                     if (off0 < end) {
3182                         PrefixTree c = child;
3183                         do {
3184                             if (isEqual(c.c0, text.charAt(off0))) {
3185                                 pos.setIndex(off0);
3186                                 String found = c.match(text, pos);
3187                                 if (found != null) {
3188                                     return found;
3189                                 }
3190                                 break;
3191                             }
3192                             c = c.sibling;
3193                         } while (c != null);
3194                     }
3195                 }
3196                 pos.setIndex(off);
3197                 return value;
3198             }
3199         }
3200     }
3201 
3202     //-----------------------------------------------------------------------
3203     /**
3204      * Prints or parses a chronology.
3205      */
3206     static final class ChronoPrinterParser implements DateTimePrinterParser {
3207         /** The text style to output, null means the ID. */
3208         private final TextStyle textStyle;
3209 
3210         ChronoPrinterParser(TextStyle textStyle) {
3211             // validated by caller
3212             this.textStyle = textStyle;
3213         }
3214 
3215         @Override
3216         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3217             Chrono<?> chrono = context.getValue(Queries.chrono());
3218             if (chrono == null) {
3219                 return false;
3220             }
3221             if (textStyle == null) {
3222                 buf.append(chrono.getId());
3223             } else {
3224                 buf.append(chrono.getId());  // TODO: Use symbols
3225             }
3226             return true;
3227         }
3228 
3229         @Override
3230         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3231             return ~position;  // TODO, including case insensitive
3232         }
3233     }
3234 
3235     //-----------------------------------------------------------------------
3236     /**
3237      * Prints or parses a localized pattern.
3238      */
3239     static final class LocalizedPrinterParser implements DateTimePrinterParser {
3240         private final FormatStyle dateStyle;
3241         private final FormatStyle timeStyle;
3242         private final Chrono<?> chrono;
3243 
3244         /**
3245          * Constructor.
3246          *
3247          * @param dateStyle  the date style to use, may be null
3248          * @param timeStyle  the time style to use, may be null
3249          * @param chrono  the chronology to use, not null
3250          */
3251         LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle, Chrono<?> chrono) {
3252             // validated by caller
3253             this.dateStyle = dateStyle;
3254             this.timeStyle = timeStyle;
3255             this.chrono = chrono;
3256         }
3257 
3258         @Override
3259         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3260             return formatter(context.getLocale()).toPrinterParser(false).print(context, buf);
3261         }
3262 
3263         @Override
3264         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3265             return formatter(context.getLocale()).toPrinterParser(false).parse(context, text, position);
3266         }
3267 
3268         /**
3269          * Gets the formatter to use.
3270          *
3271          * @param locale  the locale to use, not null
3272          * @return the formatter, not null
3273          * @throws IllegalArgumentException if the formatter cannot be found
3274          */
3275         private DateTimeFormatter formatter(Locale locale) {
3276             return DateTimeFormatStyleProvider.getInstance()
3277                                               .getFormatter(dateStyle, timeStyle, chrono, locale);
3278         }
3279 
3280         @Override
3281         public String toString() {
3282             return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
3283                 (timeStyle != null ? timeStyle : "") + "," + chrono.getId() + ")";
3284         }
3285     }
3286 
3287 
3288     //-----------------------------------------------------------------------
3289     /**
3290      * Prints or parses a localized pattern from a localized field.
3291      * The specific formatter and parameters is not selected until the
3292      * the field is to be printed or parsed.
3293      * The locale is needed to select the proper WeekFields from which
3294      * the field for day-of-week, week-of-month, or week-of-year is selected.
3295      */
3296     static final class WeekBasedFieldPrinterParser implements DateTimePrinterParser {
3297         private char chr;
3298         private int count;
3299 
3300         /**
3301          * Constructor.
3302          *
3303          * @param chr the pattern format letter that added this PrinterParser.
3304          * @param count the repeat count of the format letter
3305          */
3306         WeekBasedFieldPrinterParser(char chr, int count) {
3307             this.chr = chr;
3308             this.count = count;
3309         }
3310 
3311         @Override
3312         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3313             return printerParser(context.getLocale()).print(context, buf);
3314         }
3315 
3316         @Override
3317         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3318             return printerParser(context.getLocale()).parse(context, text, position);
3319         }
3320 
3321         /**
3322          * Gets the printerParser to use based on the field and the locale.
3323          *
3324          * @param locale  the locale to use, not null
3325          * @return the formatter, not null
3326          * @throws IllegalArgumentException if the formatter cannot be found
3327          */
3328         private DateTimePrinterParser printerParser(Locale locale) {
3329             WeekFields weekDef = WeekFields.of(locale);
3330             TemporalField field = null;
3331             switch (chr) {
3332                 case 'e':
3333                     field = weekDef.dayOfWeek();
3334                     break;
3335                 case 'w':
3336                     field = weekDef.weekOfMonth();
3337                     break;
3338                 case 'W':
3339                     field = weekDef.weekOfYear();
3340                     break;
3341                 default:
3342                     throw new IllegalStateException("unreachable");
3343             }
3344             return new NumberPrinterParser(field, (count == 2 ? 2 : 1), 2, SignStyle.NOT_NEGATIVE);
3345         }
3346 
3347         @Override
3348         public String toString() {
3349             return String.format("WeekBased(%c%d)", chr, count);
3350         }
3351     }
3352 
3353 
3354     //-------------------------------------------------------------------------
3355     /**
3356      * Length comparator.
3357      */
3358     static final Comparator<String> LENGTH_SORT = new Comparator<String>() {
3359         @Override
3360         public int compare(String str1, String str2) {
3361             return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length();
3362         }
3363     };
3364 
3365 }