8267587: Update java.util to use enhanced switch

Reviewed-by: iris
This commit is contained in:
Tagir F. Valeev 2021-05-31 08:48:38 +00:00
parent 35916ed57f
commit ab5a7ff230
15 changed files with 556 additions and 776 deletions

View file

@ -1477,7 +1477,6 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
if (zone == null) { if (zone == null) {
zone = defaultTimeZone(locale); zone = defaultTimeZone(locale);
} }
Calendar cal;
if (type == null) { if (type == null) {
type = locale.getUnicodeLocaleType("ca"); type = locale.getUnicodeLocaleType("ca");
} }
@ -1489,28 +1488,24 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
type = "gregory"; type = "gregory";
} }
} }
switch (type) { final Calendar cal = switch (type) {
case "gregory": case "gregory" -> new GregorianCalendar(zone, locale, true);
cal = new GregorianCalendar(zone, locale, true); case "iso8601" -> {
break;
case "iso8601":
GregorianCalendar gcal = new GregorianCalendar(zone, locale, true); GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);
// make gcal a proleptic Gregorian // make gcal a proleptic Gregorian
gcal.setGregorianChange(new Date(Long.MIN_VALUE)); gcal.setGregorianChange(new Date(Long.MIN_VALUE));
// and week definition to be compatible with ISO 8601 // and week definition to be compatible with ISO 8601
setWeekDefinition(MONDAY, 4); setWeekDefinition(MONDAY, 4);
cal = gcal; yield gcal;
break;
case "buddhist":
cal = new BuddhistCalendar(zone, locale);
cal.clear();
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, locale, true);
break;
default:
throw new IllegalArgumentException("unknown calendar type: " + type);
} }
case "buddhist" -> {
var buddhistCalendar = new BuddhistCalendar(zone, locale);
buddhistCalendar.clear();
yield buddhistCalendar;
}
case "japanese" -> new JapaneseImperialCalendar(zone, locale, true);
default -> throw new IllegalArgumentException("unknown calendar type: " + type);
};
cal.setLenient(lenient); cal.setLenient(lenient);
if (firstDayOfWeek != 0) { if (firstDayOfWeek != 0) {
cal.setFirstDayOfWeek(firstDayOfWeek); cal.setFirstDayOfWeek(firstDayOfWeek);
@ -1705,17 +1700,12 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
if (aLocale.hasExtensions()) { if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca"); String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) { if (caltype != null) {
switch (caltype) { cal = switch (caltype) {
case "buddhist": case "buddhist" -> new BuddhistCalendar(zone, aLocale);
cal = new BuddhistCalendar(zone, aLocale); case "japanese" -> new JapaneseImperialCalendar(zone, aLocale);
break; case "gregory" -> new GregorianCalendar(zone, aLocale);
case "japanese": default -> null;
cal = new JapaneseImperialCalendar(zone, aLocale); };
break;
case "gregory":
cal = new GregorianCalendar(zone, aLocale);
break;
}
} }
} }
if (cal == null) { if (cal == null) {
@ -2267,25 +2257,13 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
return null; return null;
} }
String[] strings = null; return switch (field) {
switch (field) { case ERA -> symbols.getEras();
case ERA: case MONTH -> (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
strings = symbols.getEras(); case DAY_OF_WEEK -> (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
break; case AM_PM -> symbols.getAmPmStrings();
default -> null;
case MONTH: };
strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
break;
case DAY_OF_WEEK:
strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
break;
case AM_PM:
strings = symbols.getAmPmStrings();
break;
}
return strings;
} }
/** /**

View file

@ -2674,27 +2674,26 @@ public final class Formatter implements Closeable, Flushable {
int index = fs.index(); int index = fs.index();
try { try {
switch (index) { switch (index) {
case -2: // fixed string, "%n", or "%%" case -2 -> // fixed string, "%n", or "%%"
fs.print(null, l); fs.print(null, l);
break; case -1 -> { // relative index
case -1: // relative index
if (last < 0 || (args != null && last > args.length - 1)) if (last < 0 || (args != null && last > args.length - 1))
throw new MissingFormatArgumentException(fs.toString()); throw new MissingFormatArgumentException(fs.toString());
fs.print((args == null ? null : args[last]), l); fs.print((args == null ? null : args[last]), l);
break; }
case 0: // ordinary index case 0 -> { // ordinary index
lasto++; lasto++;
last = lasto; last = lasto;
if (args != null && lasto > args.length - 1) if (args != null && lasto > args.length - 1)
throw new MissingFormatArgumentException(fs.toString()); throw new MissingFormatArgumentException(fs.toString());
fs.print((args == null ? null : args[lasto]), l); fs.print((args == null ? null : args[lasto]), l);
break; }
default: // explicit index default -> { // explicit index
last = index - 1; last = index - 1;
if (args != null && last > args.length - 1) if (args != null && last > args.length - 1)
throw new MissingFormatArgumentException(fs.toString()); throw new MissingFormatArgumentException(fs.toString());
fs.print((args == null ? null : args[last]), l); fs.print((args == null ? null : args[last]), l);
break; }
} }
} catch (IOException x) { } catch (IOException x) {
lastException = x; lastException = x;
@ -4111,15 +4110,9 @@ public final class Formatter implements Closeable, Flushable {
int i = t.get(Calendar.YEAR); int i = t.get(Calendar.YEAR);
int size = 2; int size = 2;
switch (c) { switch (c) {
case DateTime.CENTURY: case DateTime.CENTURY -> i /= 100;
i /= 100; case DateTime.YEAR_2 -> i %= 100;
break; case DateTime.YEAR_4 -> size = 4;
case DateTime.YEAR_2:
i %= 100;
break;
case DateTime.YEAR_4:
size = 4;
break;
} }
Flags flags = Flags.ZERO_PAD; Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, size, l)); sb.append(localizedMagnitude(null, i, flags, size, l));
@ -4352,15 +4345,9 @@ public final class Formatter implements Closeable, Flushable {
int i = t.get(ChronoField.YEAR_OF_ERA); int i = t.get(ChronoField.YEAR_OF_ERA);
int size = 2; int size = 2;
switch (c) { switch (c) {
case DateTime.CENTURY: case DateTime.CENTURY -> i /= 100;
i /= 100; case DateTime.YEAR_2 -> i %= 100;
break; case DateTime.YEAR_4 -> size = 4;
case DateTime.YEAR_2:
i %= 100;
break;
case DateTime.YEAR_4:
size = 4;
break;
} }
Flags flags = Flags.ZERO_PAD; Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, size, l)); sb.append(localizedMagnitude(null, i, flags, size, l));
@ -4836,46 +4823,16 @@ public final class Formatter implements Closeable, Flushable {
static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d) static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d)
static boolean isValid(char c) { static boolean isValid(char c) {
switch (c) { return switch (c) {
case HOUR_OF_DAY_0: case HOUR_OF_DAY_0, HOUR_0, HOUR_OF_DAY, HOUR, MINUTE, NANOSECOND, MILLISECOND, MILLISECOND_SINCE_EPOCH,
case HOUR_0: AM_PM, SECONDS_SINCE_EPOCH, SECOND, TIME, ZONE_NUMERIC, ZONE -> true;
case HOUR_OF_DAY:
case HOUR:
case MINUTE:
case NANOSECOND:
case MILLISECOND:
case MILLISECOND_SINCE_EPOCH:
case AM_PM:
case SECONDS_SINCE_EPOCH:
case SECOND:
case TIME:
case ZONE_NUMERIC:
case ZONE:
// Date // Date
case NAME_OF_DAY_ABBREV: case NAME_OF_DAY_ABBREV, NAME_OF_DAY, NAME_OF_MONTH_ABBREV, NAME_OF_MONTH, CENTURY, DAY_OF_MONTH_0,
case NAME_OF_DAY: DAY_OF_MONTH, NAME_OF_MONTH_ABBREV_X, DAY_OF_YEAR, MONTH, YEAR_2, YEAR_4 -> true;
case NAME_OF_MONTH_ABBREV:
case NAME_OF_MONTH:
case CENTURY:
case DAY_OF_MONTH_0:
case DAY_OF_MONTH:
case NAME_OF_MONTH_ABBREV_X:
case DAY_OF_YEAR:
case MONTH:
case YEAR_2:
case YEAR_4:
// Composites // Composites
case TIME_12_HOUR: case TIME_12_HOUR, TIME_24_HOUR, DATE_TIME, DATE, ISO_STANDARD_DATE -> true;
case TIME_24_HOUR: default -> false;
case DATE_TIME: };
case DATE:
case ISO_STANDARD_DATE:
return true;
default:
return false;
}
} }
} }
} }

View file

@ -1555,14 +1555,7 @@ public class GregorianCalendar extends Calendar {
@Override @Override
public int getMaximum(int field) { public int getMaximum(int field) {
switch (field) { switch (field) {
case MONTH: case MONTH, DAY_OF_MONTH, DAY_OF_YEAR, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, YEAR -> {
case DAY_OF_MONTH:
case DAY_OF_YEAR:
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
case YEAR:
{
// On or after Gregorian 200-3-1, Julian and Gregorian // On or after Gregorian 200-3-1, Julian and Gregorian
// calendar dates are the same or Gregorian dates are // calendar dates are the same or Gregorian dates are
// larger (i.e., there is a "gap") after 300-3-1. // larger (i.e., there is a "gap") after 300-3-1.
@ -1574,7 +1567,7 @@ public class GregorianCalendar extends Calendar {
gc.setLenient(true); gc.setLenient(true);
gc.setTimeInMillis(gregorianCutover); gc.setTimeInMillis(gregorianCutover);
int v1 = gc.getActualMaximum(field); int v1 = gc.getActualMaximum(field);
gc.setTimeInMillis(gregorianCutover-1); gc.setTimeInMillis(gregorianCutover - 1);
int v2 = gc.getActualMaximum(field); int v2 = gc.getActualMaximum(field);
return Math.max(MAX_VALUES[field], Math.max(v1, v2)); return Math.max(MAX_VALUES[field], Math.max(v1, v2));
} }
@ -1634,19 +1627,12 @@ public class GregorianCalendar extends Calendar {
@Override @Override
public int getLeastMaximum(int field) { public int getLeastMaximum(int field) {
switch (field) { switch (field) {
case MONTH: case MONTH, DAY_OF_MONTH, DAY_OF_YEAR, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, YEAR -> {
case DAY_OF_MONTH:
case DAY_OF_YEAR:
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
case YEAR:
{
GregorianCalendar gc = (GregorianCalendar) clone(); GregorianCalendar gc = (GregorianCalendar) clone();
gc.setLenient(true); gc.setLenient(true);
gc.setTimeInMillis(gregorianCutover); gc.setTimeInMillis(gregorianCutover);
int v1 = gc.getActualMaximum(field); int v1 = gc.getActualMaximum(field);
gc.setTimeInMillis(gregorianCutover-1); gc.setTimeInMillis(gregorianCutover - 1);
int v2 = gc.getActualMaximum(field); int v2 = gc.getActualMaximum(field);
return Math.min(LEAST_MAX_VALUES[field], Math.min(v1, v2)); return Math.min(LEAST_MAX_VALUES[field], Math.min(v1, v2));
} }
@ -1741,8 +1727,7 @@ public class GregorianCalendar extends Calendar {
int value = -1; int value = -1;
switch (field) { switch (field) {
case MONTH: case MONTH -> {
{
if (!gc.isCutoverYear(normalizedYear)) { if (!gc.isCutoverYear(normalizedYear)) {
value = DECEMBER; value = DECEMBER;
break; break;
@ -1757,10 +1742,7 @@ public class GregorianCalendar extends Calendar {
cal.getCalendarDateFromFixedDate(d, nextJan1 - 1); cal.getCalendarDateFromFixedDate(d, nextJan1 - 1);
value = d.getMonth() - 1; value = d.getMonth() - 1;
} }
break; case DAY_OF_MONTH -> {
case DAY_OF_MONTH:
{
value = cal.getMonthLength(date); value = cal.getMonthLength(date);
if (!gc.isCutoverYear(normalizedYear) || date.getDayOfMonth() == value) { if (!gc.isCutoverYear(normalizedYear) || date.getDayOfMonth() == value) {
break; break;
@ -1777,10 +1759,7 @@ public class GregorianCalendar extends Calendar {
BaseCalendar.Date d = gc.getCalendarDate(monthEnd); BaseCalendar.Date d = gc.getCalendarDate(monthEnd);
value = d.getDayOfMonth(); value = d.getDayOfMonth();
} }
break; case DAY_OF_YEAR -> {
case DAY_OF_YEAR:
{
if (!gc.isCutoverYear(normalizedYear)) { if (!gc.isCutoverYear(normalizedYear)) {
value = cal.getYearLength(date); value = cal.getYearLength(date);
break; break;
@ -1807,10 +1786,7 @@ public class GregorianCalendar extends Calendar {
date.getDayOfMonth(), date); date.getDayOfMonth(), date);
value = (int)(nextJan1 - jan1); value = (int)(nextJan1 - jan1);
} }
break; case WEEK_OF_YEAR -> {
case WEEK_OF_YEAR:
{
if (!gc.isCutoverYear(normalizedYear)) { if (!gc.isCutoverYear(normalizedYear)) {
// Get the day of week of January 1 of the year // Get the day of week of January 1 of the year
CalendarDate d = cal.newCalendarDate(TimeZone.NO_TIMEZONE); CalendarDate d = cal.newCalendarDate(TimeZone.NO_TIMEZONE);
@ -1841,10 +1817,7 @@ public class GregorianCalendar extends Calendar {
value = gc.get(WEEK_OF_YEAR); value = gc.get(WEEK_OF_YEAR);
} }
} }
break; case WEEK_OF_MONTH -> {
case WEEK_OF_MONTH:
{
if (!gc.isCutoverYear(normalizedYear)) { if (!gc.isCutoverYear(normalizedYear)) {
CalendarDate d = cal.newCalendarDate(null); CalendarDate d = cal.newCalendarDate(null);
d.setDate(date.getYear(), date.getMonth(), 1); d.setDate(date.getYear(), date.getMonth(), 1);
@ -1880,10 +1853,7 @@ public class GregorianCalendar extends Calendar {
gc.add(WEEK_OF_MONTH, +1); gc.add(WEEK_OF_MONTH, +1);
} while (gc.get(YEAR) == y && gc.get(MONTH) == m); } while (gc.get(YEAR) == y && gc.get(MONTH) == m);
} }
break; case DAY_OF_WEEK_IN_MONTH -> {
case DAY_OF_WEEK_IN_MONTH:
{
// may be in the Gregorian cutover month // may be in the Gregorian cutover month
int ndays, dow1; int ndays, dow1;
int dow = date.getDayOfWeek(); int dow = date.getDayOfWeek();
@ -1909,9 +1879,7 @@ public class GregorianCalendar extends Calendar {
ndays -= x; ndays -= x;
value = (ndays + 6) / 7; value = (ndays + 6) / 7;
} }
break; case YEAR -> {
case YEAR:
/* The year computation is no different, in principle, from the /* The year computation is no different, in principle, from the
* others, however, the range of possible maxima is large. In * others, however, the range of possible maxima is large. In
* addition, the way we know we've exceeded the range is different. * addition, the way we know we've exceeded the range is different.
@ -1931,7 +1899,6 @@ public class GregorianCalendar extends Calendar {
* added to check the month and date in the future for some reason, * added to check the month and date in the future for some reason,
* Feb 29 must be allowed to shift to Mar 1 when setting the year. * Feb 29 must be allowed to shift to Mar 1 when setting the year.
*/ */
{
if (gc == this) { if (gc == this) {
gc = (GregorianCalendar) clone(); gc = (GregorianCalendar) clone();
} }
@ -1970,10 +1937,7 @@ public class GregorianCalendar extends Calendar {
} }
} }
} }
break; default -> throw new ArrayIndexOutOfBoundsException(field);
default:
throw new ArrayIndexOutOfBoundsException(field);
} }
return value; return value;
} }

View file

@ -1115,16 +1115,14 @@ class JapaneseImperialCalendar extends Calendar {
* @see #getActualMaximum(int) * @see #getActualMaximum(int)
*/ */
public int getMaximum(int field) { public int getMaximum(int field) {
switch (field) { return switch (field) {
case YEAR: case YEAR -> {
{
// The value should depend on the time zone of this calendar. // The value should depend on the time zone of this calendar.
LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
getZone()); yield Math.max(LEAST_MAX_VALUES[YEAR], d.getYear());
return Math.max(LEAST_MAX_VALUES[YEAR], d.getYear());
} }
} default -> MAX_VALUES[field];
return MAX_VALUES[field]; };
} }
/** /**
@ -1168,13 +1166,10 @@ class JapaneseImperialCalendar extends Calendar {
* @see #getActualMaximum(int) * @see #getActualMaximum(int)
*/ */
public int getLeastMaximum(int field) { public int getLeastMaximum(int field) {
switch (field) { return switch (field) {
case YEAR: case YEAR -> Math.min(LEAST_MAX_VALUES[YEAR], getMaximum(YEAR));
{ default -> LEAST_MAX_VALUES[field];
return Math.min(LEAST_MAX_VALUES[YEAR], getMaximum(YEAR)); };
}
}
return LEAST_MAX_VALUES[field];
} }
/** /**
@ -1207,8 +1202,7 @@ class JapaneseImperialCalendar extends Calendar {
getZone()); getZone());
int eraIndex = getEraIndex(jd); int eraIndex = getEraIndex(jd);
switch (field) { switch (field) {
case YEAR: case YEAR -> {
{
if (eraIndex > BEFORE_MEIJI) { if (eraIndex > BEFORE_MEIJI) {
value = 1; value = 1;
long since = eras[eraIndex].getSince(getZone()); long since = eras[eraIndex].getSince(getZone());
@ -1239,10 +1233,7 @@ class JapaneseImperialCalendar extends Calendar {
} }
} }
} }
break; case MONTH -> {
case MONTH:
{
// In Before Meiji and Meiji, January is the first month. // In Before Meiji and Meiji, January is the first month.
if (eraIndex > MEIJI && jd.getYear() == 1) { if (eraIndex > MEIJI && jd.getYear() == 1) {
long since = eras[eraIndex].getSince(getZone()); long since = eras[eraIndex].getSince(getZone());
@ -1253,10 +1244,7 @@ class JapaneseImperialCalendar extends Calendar {
} }
} }
} }
break; case WEEK_OF_YEAR -> {
case WEEK_OF_YEAR:
{
value = 1; value = 1;
CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
// shift 400 years to avoid underflow // shift 400 years to avoid underflow
@ -1276,7 +1264,6 @@ class JapaneseImperialCalendar extends Calendar {
value++; value++;
} }
} }
break;
} }
return value; return value;
} }
@ -1313,13 +1300,10 @@ class JapaneseImperialCalendar extends Calendar {
JapaneseImperialCalendar jc = getNormalizedCalendar(); JapaneseImperialCalendar jc = getNormalizedCalendar();
LocalGregorianCalendar.Date date = jc.jdate; LocalGregorianCalendar.Date date = jc.jdate;
int normalizedYear = date.getNormalizedYear();
int value = -1; return switch (field) {
switch (field) { case MONTH -> {
case MONTH: int month = DECEMBER;
{
value = DECEMBER;
if (isTransitionYear(date.getNormalizedYear())) { if (isTransitionYear(date.getNormalizedYear())) {
// TODO: there may be multiple transitions in a year. // TODO: there may be multiple transitions in a year.
int eraIndex = getEraIndex(date); int eraIndex = getEraIndex(date);
@ -1333,24 +1317,18 @@ class JapaneseImperialCalendar extends Calendar {
LocalGregorianCalendar.Date ldate LocalGregorianCalendar.Date ldate
= (LocalGregorianCalendar.Date) date.clone(); = (LocalGregorianCalendar.Date) date.clone();
jcal.getCalendarDateFromFixedDate(ldate, transition - 1); jcal.getCalendarDateFromFixedDate(ldate, transition - 1);
value = ldate.getMonth() - 1; month = ldate.getMonth() - 1;
} }
} else { } else {
LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
getZone());
if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) { if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) {
value = d.getMonth() - 1; month = d.getMonth() - 1;
} }
} }
yield month;
} }
break; case DAY_OF_MONTH -> jcal.getMonthLength(date);
case DAY_OF_YEAR -> {
case DAY_OF_MONTH:
value = jcal.getMonthLength(date);
break;
case DAY_OF_YEAR:
{
if (isTransitionYear(date.getNormalizedYear())) { if (isTransitionYear(date.getNormalizedYear())) {
// Handle transition year. // Handle transition year.
// TODO: there may be multiple transitions in a year. // TODO: there may be multiple transitions in a year.
@ -1364,18 +1342,16 @@ class JapaneseImperialCalendar extends Calendar {
CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1); d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1);
if (fd < transition) { if (fd < transition) {
value = (int)(transition - gcal.getFixedDate(d)); yield (int) (transition - gcal.getFixedDate(d));
} else {
d.addYear(+1);
value = (int)(gcal.getFixedDate(d) - transition);
} }
} else { d.addYear(1);
LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, yield (int) (gcal.getFixedDate(d) - transition);
getZone()); }
LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) { if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) {
long fd = jcal.getFixedDate(d); long fd = jcal.getFixedDate(d);
long jan1 = getFixedDateJan1(d, fd); long jan1 = getFixedDateJan1(d, fd);
value = (int)(fd - jan1) + 1; yield (int) (fd - jan1) + 1;
} else if (date.getYear() == getMinimum(YEAR)) { } else if (date.getYear() == getMinimum(YEAR)) {
CalendarDate d1 = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); CalendarDate d1 = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
long fd1 = jcal.getFixedDate(d1); long fd1 = jcal.getFixedDate(d1);
@ -1383,23 +1359,18 @@ class JapaneseImperialCalendar extends Calendar {
d1.setMonth(BaseCalendar.JANUARY).setDayOfMonth(1); d1.setMonth(BaseCalendar.JANUARY).setDayOfMonth(1);
jcal.normalize(d1); jcal.normalize(d1);
long fd2 = jcal.getFixedDate(d1); long fd2 = jcal.getFixedDate(d1);
value = (int)(fd2 - fd1); yield (int) (fd2 - fd1);
} else { } else {
value = jcal.getYearLength(date); yield jcal.getYearLength(date);
} }
} }
} case WEEK_OF_YEAR -> {
break;
case WEEK_OF_YEAR:
{
if (!isTransitionYear(date.getNormalizedYear())) { if (!isTransitionYear(date.getNormalizedYear())) {
LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE, LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
getZone());
if (date.getEra() == jd.getEra() && date.getYear() == jd.getYear()) { if (date.getEra() == jd.getEra() && date.getYear() == jd.getYear()) {
long fd = jcal.getFixedDate(jd); long fd = jcal.getFixedDate(jd);
long jan1 = getFixedDateJan1(jd, fd); long jan1 = getFixedDateJan1(jd, fd);
value = getWeekNumber(jan1, fd); yield getWeekNumber(jan1, fd);
} else if (date.getEra() == null && date.getYear() == getMinimum(YEAR)) { } else if (date.getEra() == null && date.getYear() == getMinimum(YEAR)) {
CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
// shift 400 years to avoid underflow // shift 400 years to avoid underflow
@ -1412,12 +1383,12 @@ class JapaneseImperialCalendar extends Calendar {
long nextJan1 = jcal.getFixedDate(jd); long nextJan1 = jcal.getFixedDate(jd);
long nextJan1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6, long nextJan1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
getFirstDayOfWeek()); getFirstDayOfWeek());
int ndays = (int)(nextJan1st - nextJan1); int ndays = (int) (nextJan1st - nextJan1);
if (ndays >= getMinimalDaysInFirstWeek()) { if (ndays >= getMinimalDaysInFirstWeek()) {
nextJan1st -= 7; nextJan1st -= 7;
} }
value = getWeekNumber(jan1, nextJan1st); yield getWeekNumber(jan1, nextJan1st);
} else { }
// Get the day of week of January 1 of the year // Get the day of week of January 1 of the year
CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1); d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1);
@ -1427,14 +1398,12 @@ class JapaneseImperialCalendar extends Calendar {
if (dayOfWeek < 0) { if (dayOfWeek < 0) {
dayOfWeek += 7; dayOfWeek += 7;
} }
value = 52;
int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1; int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1;
if ((magic == 6) || if ((magic == 6) ||
(date.isLeapYear() && (magic == 5 || magic == 12))) { (date.isLeapYear() && (magic == 5 || magic == 12))) {
value++; yield 53;
} }
} yield 52;
break;
} }
if (jc == this) { if (jc == this) {
@ -1442,19 +1411,20 @@ class JapaneseImperialCalendar extends Calendar {
} }
int max = getActualMaximum(DAY_OF_YEAR); int max = getActualMaximum(DAY_OF_YEAR);
jc.set(DAY_OF_YEAR, max); jc.set(DAY_OF_YEAR, max);
value = jc.get(WEEK_OF_YEAR); int weekOfYear = jc.get(WEEK_OF_YEAR);
if (value == 1 && max > 7) { if (weekOfYear == 1 && max > 7) {
jc.add(WEEK_OF_YEAR, -1); jc.add(WEEK_OF_YEAR, -1);
value = jc.get(WEEK_OF_YEAR); weekOfYear = jc.get(WEEK_OF_YEAR);
} }
yield weekOfYear;
}
case WEEK_OF_MONTH -> {
LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
if (date.getEra() == jd.getEra() && date.getYear() == jd.getYear()) {
long fd = jcal.getFixedDate(jd);
long month1 = fd - jd.getDayOfMonth() + 1;
yield getWeekNumber(month1, fd);
} }
break;
case WEEK_OF_MONTH:
{
LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE,
getZone());
if (!(date.getEra() == jd.getEra() && date.getYear() == jd.getYear())) {
CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
d.setDate(date.getNormalizedYear(), date.getMonth(), 1); d.setDate(date.getNormalizedYear(), date.getMonth(), 1);
int dayOfWeek = gcal.getDayOfWeek(d); int dayOfWeek = gcal.getDayOfWeek(d);
@ -1464,27 +1434,20 @@ class JapaneseImperialCalendar extends Calendar {
dayOfWeek += 7; dayOfWeek += 7;
} }
int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week
value = 3; int weekOfMonth = 3;
if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) { if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) {
value++; weekOfMonth++;
} }
monthLength -= nDaysFirstWeek + 7 * 3; monthLength -= nDaysFirstWeek + 7 * 3;
if (monthLength > 0) { if (monthLength > 0) {
value++; weekOfMonth++;
if (monthLength > 7) { if (monthLength > 7) {
value++; weekOfMonth++;
} }
} }
} else { yield weekOfMonth;
long fd = jcal.getFixedDate(jd);
long month1 = fd - jd.getDayOfMonth() + 1;
value = getWeekNumber(month1, fd);
} }
} case DAY_OF_WEEK_IN_MONTH -> {
break;
case DAY_OF_WEEK_IN_MONTH:
{
int ndays, dow1; int ndays, dow1;
int dow = date.getDayOfWeek(); int dow = date.getDayOfWeek();
BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); BaseCalendar.Date d = (BaseCalendar.Date) date.clone();
@ -1497,42 +1460,36 @@ class JapaneseImperialCalendar extends Calendar {
x += 7; x += 7;
} }
ndays -= x; ndays -= x;
value = (ndays + 6) / 7; yield (ndays + 6) / 7;
} }
break; case YEAR -> {
case YEAR:
{
CalendarDate jd = jcal.getCalendarDate(jc.getTimeInMillis(), getZone()); CalendarDate jd = jcal.getCalendarDate(jc.getTimeInMillis(), getZone());
CalendarDate d; CalendarDate d;
int eraIndex = getEraIndex(date); int eraIndex = getEraIndex(date);
int year;
if (eraIndex == eras.length - 1) { if (eraIndex == eras.length - 1) {
d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
value = d.getYear(); year = d.getYear();
// Use an equivalent year for the // Use an equivalent year for the
// getYearOffsetInMillis call to avoid overflow. // getYearOffsetInMillis call to avoid overflow.
if (value > 400) { if (year > 400) {
jd.setYear(value - 400); jd.setYear(year - 400);
} }
} else { } else {
d = jcal.getCalendarDate(eras[eraIndex + 1].getSince(getZone()) - 1, d = jcal.getCalendarDate(eras[eraIndex + 1].getSince(getZone()) - 1, getZone());
getZone()); year = d.getYear();
value = d.getYear();
// Use the same year as d.getYear() to be // Use the same year as d.getYear() to be
// consistent with leap and common years. // consistent with leap and common years.
jd.setYear(value); jd.setYear(year);
} }
jcal.normalize(jd); jcal.normalize(jd);
if (getYearOffsetInMillis(jd) > getYearOffsetInMillis(d)) { if (getYearOffsetInMillis(jd) > getYearOffsetInMillis(d)) {
value--; year--;
} }
yield year;
} }
break; default -> throw new ArrayIndexOutOfBoundsException(field);
};
default:
throw new ArrayIndexOutOfBoundsException(field);
}
return value;
} }
/** /**

View file

@ -2257,13 +2257,10 @@ public final class Locale implements Cloneable, Serializable {
return Arrays.stream(stringList).collect(Collectors.joining(",")); return Arrays.stream(stringList).collect(Collectors.joining(","));
} }
switch (stringList.length) { return switch (stringList.length) {
case 0: case 0 -> "";
return ""; case 1 -> stringList[0];
case 1: default -> Arrays.stream(stringList).reduce("",
return stringList[0];
default:
return Arrays.stream(stringList).reduce("",
(s1, s2) -> { (s1, s2) -> {
if (s1.isEmpty()) { if (s1.isEmpty()) {
return s2; return s2;
@ -2273,7 +2270,7 @@ public final class Locale implements Cloneable, Serializable {
} }
return MessageFormat.format(pattern, s1, s2); return MessageFormat.format(pattern, s1, s2);
}); });
} };
} }
// Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to // Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to

View file

@ -655,23 +655,12 @@ public class Properties extends Hashtable<Object,Object> {
int value = 0; int value = 0;
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
aChar = in[off++]; aChar = in[off++];
switch (aChar) { value = switch (aChar) {
case '0': case '1': case '2': case '3': case '4': case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> (value << 4) + aChar - '0';
case '5': case '6': case '7': case '8': case '9': case 'a', 'b', 'c', 'd', 'e', 'f' -> (value << 4) + 10 + aChar - 'a';
value = (value << 4) + aChar - '0'; case 'A', 'B', 'C', 'D', 'E', 'F' -> (value << 4) + 10 + aChar - 'A';
break; default -> throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
case 'a': case 'b': case 'c': };
case 'd': case 'e': case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
} }
out.append((char)value); out.append((char)value);
} else { } else {

View file

@ -326,16 +326,12 @@ public final class PropertyPermission extends BasicPermission {
* @return the canonical string representation of the actions. * @return the canonical string representation of the actions.
*/ */
static String getActions(int mask) { static String getActions(int mask) {
switch (mask & (READ|WRITE)) { return switch (mask & (READ | WRITE)) {
case READ: case READ -> SecurityConstants.PROPERTY_READ_ACTION;
return SecurityConstants.PROPERTY_READ_ACTION; case WRITE -> SecurityConstants.PROPERTY_WRITE_ACTION;
case WRITE: case READ | WRITE -> SecurityConstants.PROPERTY_RW_ACTION;
return SecurityConstants.PROPERTY_WRITE_ACTION; default -> "";
case READ|WRITE: };
return SecurityConstants.PROPERTY_RW_ACTION;
default:
return "";
}
} }
/** /**

View file

@ -1829,19 +1829,13 @@ public abstract class ResourceBundle {
if (bundle == null && !cacheKey.callerHasProvider()) { if (bundle == null && !cacheKey.callerHasProvider()) {
for (String format : formats) { for (String format : formats) {
try { try {
switch (format) { bundle = switch (format) {
case "java.class": case "java.class" -> ResourceBundleProviderHelper
bundle = ResourceBundleProviderHelper
.loadResourceBundle(callerModule, module, baseName, targetLocale); .loadResourceBundle(callerModule, module, baseName, targetLocale);
case "java.properties" -> ResourceBundleProviderHelper
break;
case "java.properties":
bundle = ResourceBundleProviderHelper
.loadPropertyResourceBundle(callerModule, module, baseName, targetLocale); .loadPropertyResourceBundle(callerModule, module, baseName, targetLocale);
break; default -> throw new InternalError("unexpected format: " + format);
default: };
throw new InternalError("unexpected format: " + format);
}
if (bundle != null) { if (bundle != null) {
cacheKey.setFormat(format); cacheKey.setFormat(format);
@ -2916,15 +2910,8 @@ public abstract class ResourceBundle {
// Supply script for users who want to use zh_Hans/zh_Hant // Supply script for users who want to use zh_Hans/zh_Hant
// as bundle names (recommended for Java7+) // as bundle names (recommended for Java7+)
switch (region) { switch (region) {
case "TW": case "TW", "HK", "MO" -> script = "Hant";
case "HK": case "CN", "SG" -> script = "Hans";
case "MO":
script = "Hant";
break;
case "CN":
case "SG":
script = "Hans";
break;
} }
} }
} }
@ -2962,12 +2949,8 @@ public abstract class ResourceBundle {
// Supply region(country) for users who still package Chinese // Supply region(country) for users who still package Chinese
// bundles using old convension. // bundles using old convension.
switch (script) { switch (script) {
case "Hans": case "Hans" -> region = "CN";
region = "CN"; case "Hant" -> region = "TW";
break;
case "Hant":
region = "TW";
break;
} }
} }
} }

View file

@ -738,27 +738,22 @@ public class SimpleTimeZone extends TimeZone {
cdate.setNormalizedYear(year); cdate.setNormalizedYear(year);
cdate.setMonth(month + 1); cdate.setMonth(month + 1);
switch (mode) { switch (mode) {
case DOM_MODE: case DOM_MODE -> cdate.setDayOfMonth(dayOfMonth);
cdate.setDayOfMonth(dayOfMonth); case DOW_IN_MONTH_MODE -> {
break;
case DOW_IN_MONTH_MODE:
cdate.setDayOfMonth(1); cdate.setDayOfMonth(1);
if (dayOfMonth < 0) { if (dayOfMonth < 0) {
cdate.setDayOfMonth(cal.getMonthLength(cdate)); cdate.setDayOfMonth(cal.getMonthLength(cdate));
} }
cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(dayOfMonth, dayOfWeek, cdate); cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(dayOfMonth, dayOfWeek, cdate);
break; }
case DOW_GE_DOM_MODE -> {
case DOW_GE_DOM_MODE:
cdate.setDayOfMonth(dayOfMonth); cdate.setDayOfMonth(dayOfMonth);
cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(1, dayOfWeek, cdate); cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(1, dayOfWeek, cdate);
break; }
case DOW_LE_DOM_MODE -> {
case DOW_LE_DOM_MODE:
cdate.setDayOfMonth(dayOfMonth); cdate.setDayOfMonth(dayOfMonth);
cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(-1, dayOfWeek, cdate); cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(-1, dayOfWeek, cdate);
break; }
} }
return cal.getTime(cdate) + timeOfDay; return cal.getTime(cdate) + timeOfDay;
} }
@ -1527,9 +1522,7 @@ public class SimpleTimeZone extends TimeZone {
* rules anyway. * rules anyway.
*/ */
switch (startTimeMode) { switch (startTimeMode) {
case UTC_TIME: case UTC_TIME -> startTime += rawOffset;
startTime += rawOffset;
break;
} }
while (startTime < 0) { while (startTime < 0) {
startTime += millisPerDay; startTime += millisPerDay;
@ -1541,11 +1534,8 @@ public class SimpleTimeZone extends TimeZone {
} }
switch (endTimeMode) { switch (endTimeMode) {
case UTC_TIME: case UTC_TIME -> endTime += rawOffset + dstSavings;
endTime += rawOffset + dstSavings; case STANDARD_TIME -> endTime += dstSavings;
break;
case STANDARD_TIME:
endTime += dstSavings;
} }
while (endTime < 0) { while (endTime < 0) {
endTime += millisPerDay; endTime += millisPerDay;

View file

@ -190,19 +190,18 @@ public class JarFile extends ZipFile {
String enableMultiRelease = GetPropertyAction String enableMultiRelease = GetPropertyAction
.privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true"); .privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true");
switch (enableMultiRelease) { switch (enableMultiRelease) {
case "true": case "false" -> {
default:
MULTI_RELEASE_ENABLED = true;
MULTI_RELEASE_FORCED = false;
break;
case "false":
MULTI_RELEASE_ENABLED = false; MULTI_RELEASE_ENABLED = false;
MULTI_RELEASE_FORCED = false; MULTI_RELEASE_FORCED = false;
break; }
case "force": case "force" -> {
MULTI_RELEASE_ENABLED = true; MULTI_RELEASE_ENABLED = true;
MULTI_RELEASE_FORCED = true; MULTI_RELEASE_FORCED = true;
break; }
default -> {
MULTI_RELEASE_ENABLED = true;
MULTI_RELEASE_FORCED = false;
}
} }
} }

View file

@ -170,55 +170,51 @@ class CharPredicates {
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
private static CharPredicate getPosixPredicate(String name, boolean caseIns) { private static CharPredicate getPosixPredicate(String name, boolean caseIns) {
switch (name) { return switch (name) {
case "ALPHA": return ALPHABETIC(); case "ALPHA" -> ALPHABETIC();
case "LOWER": return caseIns case "LOWER" -> caseIns
? LOWERCASE().union(UPPERCASE(), TITLECASE()) ? LOWERCASE().union(UPPERCASE(), TITLECASE())
: LOWERCASE(); : LOWERCASE();
case "UPPER": return caseIns case "UPPER" -> caseIns
? UPPERCASE().union(LOWERCASE(), TITLECASE()) ? UPPERCASE().union(LOWERCASE(), TITLECASE())
: UPPERCASE(); : UPPERCASE();
case "SPACE": return WHITE_SPACE(); case "SPACE" -> WHITE_SPACE();
case "PUNCT": return PUNCTUATION(); case "PUNCT" -> PUNCTUATION();
case "XDIGIT": return HEX_DIGIT(); case "XDIGIT" -> HEX_DIGIT();
case "ALNUM": return ALNUM(); case "ALNUM" -> ALNUM();
case "CNTRL": return CONTROL(); case "CNTRL" -> CONTROL();
case "DIGIT": return DIGIT(); case "DIGIT" -> DIGIT();
case "BLANK": return BLANK(); case "BLANK" -> BLANK();
case "GRAPH": return GRAPH(); case "GRAPH" -> GRAPH();
case "PRINT": return PRINT(); case "PRINT" -> PRINT();
default: return null; default -> null;
} };
} }
private static CharPredicate getUnicodePredicate(String name, boolean caseIns) { private static CharPredicate getUnicodePredicate(String name, boolean caseIns) {
switch (name) { return switch (name) {
case "ALPHABETIC": return ALPHABETIC(); case "ALPHABETIC" -> ALPHABETIC();
case "ASSIGNED": return ASSIGNED(); case "ASSIGNED" -> ASSIGNED();
case "CONTROL": return CONTROL(); case "CONTROL" -> CONTROL();
case "HEXDIGIT": case "HEXDIGIT", "HEX_DIGIT" -> HEX_DIGIT();
case "HEX_DIGIT": return HEX_DIGIT(); case "IDEOGRAPHIC" -> IDEOGRAPHIC();
case "IDEOGRAPHIC": return IDEOGRAPHIC(); case "JOINCONTROL", "JOIN_CONTROL" -> JOIN_CONTROL();
case "JOINCONTROL": case "LETTER" -> LETTER();
case "JOIN_CONTROL": return JOIN_CONTROL(); case "LOWERCASE" -> caseIns
case "LETTER": return LETTER();
case "LOWERCASE": return caseIns
? LOWERCASE().union(UPPERCASE(), TITLECASE()) ? LOWERCASE().union(UPPERCASE(), TITLECASE())
: LOWERCASE(); : LOWERCASE();
case "NONCHARACTERCODEPOINT": case "NONCHARACTERCODEPOINT", "NONCHARACTER_CODE_POINT" -> NONCHARACTER_CODE_POINT();
case "NONCHARACTER_CODE_POINT": return NONCHARACTER_CODE_POINT(); case "TITLECASE" -> caseIns
case "TITLECASE": return caseIns
? TITLECASE().union(LOWERCASE(), UPPERCASE()) ? TITLECASE().union(LOWERCASE(), UPPERCASE())
: TITLECASE(); : TITLECASE();
case "PUNCTUATION": return PUNCTUATION(); case "PUNCTUATION" -> PUNCTUATION();
case "UPPERCASE": return caseIns case "UPPERCASE" -> caseIns
? UPPERCASE().union(LOWERCASE(), TITLECASE()) ? UPPERCASE().union(LOWERCASE(), TITLECASE())
: UPPERCASE(); : UPPERCASE();
case "WHITESPACE": case "WHITESPACE", "WHITE_SPACE" -> WHITE_SPACE();
case "WHITE_SPACE": return WHITE_SPACE(); case "WORD" -> WORD();
case "WORD": return WORD(); default -> null;
default: return null; };
}
} }
public static CharPredicate forUnicodeProperty(String propName, boolean caseIns) { public static CharPredicate forUnicodeProperty(String propName, boolean caseIns) {
@ -267,135 +263,135 @@ class CharPredicates {
static CharPredicate forProperty(String name, boolean caseIns) { static CharPredicate forProperty(String name, boolean caseIns) {
// Unicode character property aliases, defined in // Unicode character property aliases, defined in
// http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
switch (name) { return switch (name) {
case "Cn": return category(1<<Character.UNASSIGNED); case "Cn" -> category(1 << Character.UNASSIGNED);
case "Lu": return category(caseIns ? (1<<Character.LOWERCASE_LETTER) | case "Lu" -> category(caseIns ? (1 << Character.LOWERCASE_LETTER) |
(1<<Character.UPPERCASE_LETTER) | (1 << Character.UPPERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER) (1 << Character.TITLECASE_LETTER)
: (1<<Character.UPPERCASE_LETTER)); : (1 << Character.UPPERCASE_LETTER));
case "Ll": return category(caseIns ? (1<<Character.LOWERCASE_LETTER) | case "Ll" -> category(caseIns ? (1 << Character.LOWERCASE_LETTER) |
(1<<Character.UPPERCASE_LETTER) | (1 << Character.UPPERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER) (1 << Character.TITLECASE_LETTER)
: (1<<Character.LOWERCASE_LETTER)); : (1 << Character.LOWERCASE_LETTER));
case "Lt": return category(caseIns ? (1<<Character.LOWERCASE_LETTER) | case "Lt" -> category(caseIns ? (1 << Character.LOWERCASE_LETTER) |
(1<<Character.UPPERCASE_LETTER) | (1 << Character.UPPERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER) (1 << Character.TITLECASE_LETTER)
: (1<<Character.TITLECASE_LETTER)); : (1 << Character.TITLECASE_LETTER));
case "Lm": return category(1<<Character.MODIFIER_LETTER); case "Lm" -> category(1 << Character.MODIFIER_LETTER);
case "Lo": return category(1<<Character.OTHER_LETTER); case "Lo" -> category(1 << Character.OTHER_LETTER);
case "Mn": return category(1<<Character.NON_SPACING_MARK); case "Mn" -> category(1 << Character.NON_SPACING_MARK);
case "Me": return category(1<<Character.ENCLOSING_MARK); case "Me" -> category(1 << Character.ENCLOSING_MARK);
case "Mc": return category(1<<Character.COMBINING_SPACING_MARK); case "Mc" -> category(1 << Character.COMBINING_SPACING_MARK);
case "Nd": return category(1<<Character.DECIMAL_DIGIT_NUMBER); case "Nd" -> category(1 << Character.DECIMAL_DIGIT_NUMBER);
case "Nl": return category(1<<Character.LETTER_NUMBER); case "Nl" -> category(1 << Character.LETTER_NUMBER);
case "No": return category(1<<Character.OTHER_NUMBER); case "No" -> category(1 << Character.OTHER_NUMBER);
case "Zs": return category(1<<Character.SPACE_SEPARATOR); case "Zs" -> category(1 << Character.SPACE_SEPARATOR);
case "Zl": return category(1<<Character.LINE_SEPARATOR); case "Zl" -> category(1 << Character.LINE_SEPARATOR);
case "Zp": return category(1<<Character.PARAGRAPH_SEPARATOR); case "Zp" -> category(1 << Character.PARAGRAPH_SEPARATOR);
case "Cc": return category(1<<Character.CONTROL); case "Cc" -> category(1 << Character.CONTROL);
case "Cf": return category(1<<Character.FORMAT); case "Cf" -> category(1 << Character.FORMAT);
case "Co": return category(1<<Character.PRIVATE_USE); case "Co" -> category(1 << Character.PRIVATE_USE);
case "Cs": return category(1<<Character.SURROGATE); case "Cs" -> category(1 << Character.SURROGATE);
case "Pd": return category(1<<Character.DASH_PUNCTUATION); case "Pd" -> category(1 << Character.DASH_PUNCTUATION);
case "Ps": return category(1<<Character.START_PUNCTUATION); case "Ps" -> category(1 << Character.START_PUNCTUATION);
case "Pe": return category(1<<Character.END_PUNCTUATION); case "Pe" -> category(1 << Character.END_PUNCTUATION);
case "Pc": return category(1<<Character.CONNECTOR_PUNCTUATION); case "Pc" -> category(1 << Character.CONNECTOR_PUNCTUATION);
case "Po": return category(1<<Character.OTHER_PUNCTUATION); case "Po" -> category(1 << Character.OTHER_PUNCTUATION);
case "Sm": return category(1<<Character.MATH_SYMBOL); case "Sm" -> category(1 << Character.MATH_SYMBOL);
case "Sc": return category(1<<Character.CURRENCY_SYMBOL); case "Sc" -> category(1 << Character.CURRENCY_SYMBOL);
case "Sk": return category(1<<Character.MODIFIER_SYMBOL); case "Sk" -> category(1 << Character.MODIFIER_SYMBOL);
case "So": return category(1<<Character.OTHER_SYMBOL); case "So" -> category(1 << Character.OTHER_SYMBOL);
case "Pi": return category(1<<Character.INITIAL_QUOTE_PUNCTUATION); case "Pi" -> category(1 << Character.INITIAL_QUOTE_PUNCTUATION);
case "Pf": return category(1<<Character.FINAL_QUOTE_PUNCTUATION); case "Pf" -> category(1 << Character.FINAL_QUOTE_PUNCTUATION);
case "L": return category(((1<<Character.UPPERCASE_LETTER) | case "L" -> category(((1 << Character.UPPERCASE_LETTER) |
(1<<Character.LOWERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER) | (1 << Character.TITLECASE_LETTER) |
(1<<Character.MODIFIER_LETTER) | (1 << Character.MODIFIER_LETTER) |
(1<<Character.OTHER_LETTER))); (1 << Character.OTHER_LETTER)));
case "M": return category(((1<<Character.NON_SPACING_MARK) | case "M" -> category(((1 << Character.NON_SPACING_MARK) |
(1<<Character.ENCLOSING_MARK) | (1 << Character.ENCLOSING_MARK) |
(1<<Character.COMBINING_SPACING_MARK))); (1 << Character.COMBINING_SPACING_MARK)));
case "N": return category(((1<<Character.DECIMAL_DIGIT_NUMBER) | case "N" -> category(((1 << Character.DECIMAL_DIGIT_NUMBER) |
(1<<Character.LETTER_NUMBER) | (1 << Character.LETTER_NUMBER) |
(1<<Character.OTHER_NUMBER))); (1 << Character.OTHER_NUMBER)));
case "Z": return category(((1<<Character.SPACE_SEPARATOR) | case "Z" -> category(((1 << Character.SPACE_SEPARATOR) |
(1<<Character.LINE_SEPARATOR) | (1 << Character.LINE_SEPARATOR) |
(1<<Character.PARAGRAPH_SEPARATOR))); (1 << Character.PARAGRAPH_SEPARATOR)));
case "C": return category(((1<<Character.CONTROL) | case "C" -> category(((1 << Character.CONTROL) |
(1<<Character.FORMAT) | (1 << Character.FORMAT) |
(1<<Character.PRIVATE_USE) | (1 << Character.PRIVATE_USE) |
(1<<Character.SURROGATE) | (1 << Character.SURROGATE) |
(1<<Character.UNASSIGNED))); // Other (1 << Character.UNASSIGNED))); // Other
case "P": return category(((1<<Character.DASH_PUNCTUATION) | case "P" -> category(((1 << Character.DASH_PUNCTUATION) |
(1<<Character.START_PUNCTUATION) | (1 << Character.START_PUNCTUATION) |
(1<<Character.END_PUNCTUATION) | (1 << Character.END_PUNCTUATION) |
(1<<Character.CONNECTOR_PUNCTUATION) | (1 << Character.CONNECTOR_PUNCTUATION) |
(1<<Character.OTHER_PUNCTUATION) | (1 << Character.OTHER_PUNCTUATION) |
(1<<Character.INITIAL_QUOTE_PUNCTUATION) | (1 << Character.INITIAL_QUOTE_PUNCTUATION) |
(1<<Character.FINAL_QUOTE_PUNCTUATION))); (1 << Character.FINAL_QUOTE_PUNCTUATION)));
case "S": return category(((1<<Character.MATH_SYMBOL) | case "S" -> category(((1 << Character.MATH_SYMBOL) |
(1<<Character.CURRENCY_SYMBOL) | (1 << Character.CURRENCY_SYMBOL) |
(1<<Character.MODIFIER_SYMBOL) | (1 << Character.MODIFIER_SYMBOL) |
(1<<Character.OTHER_SYMBOL))); (1 << Character.OTHER_SYMBOL)));
case "LC": return category(((1<<Character.UPPERCASE_LETTER) | case "LC" -> category(((1 << Character.UPPERCASE_LETTER) |
(1<<Character.LOWERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER))); (1 << Character.TITLECASE_LETTER)));
case "LD": return category(((1<<Character.UPPERCASE_LETTER) | case "LD" -> category(((1 << Character.UPPERCASE_LETTER) |
(1<<Character.LOWERCASE_LETTER) | (1 << Character.LOWERCASE_LETTER) |
(1<<Character.TITLECASE_LETTER) | (1 << Character.TITLECASE_LETTER) |
(1<<Character.MODIFIER_LETTER) | (1 << Character.MODIFIER_LETTER) |
(1<<Character.OTHER_LETTER) | (1 << Character.OTHER_LETTER) |
(1<<Character.DECIMAL_DIGIT_NUMBER))); (1 << Character.DECIMAL_DIGIT_NUMBER)));
case "L1": return range(0x00, 0xFF); // Latin-1 case "L1" -> range(0x00, 0xFF); // Latin-1
case "all": return Pattern.ALL(); case "all" -> Pattern.ALL();
// Posix regular expression character classes, defined in // Posix regular expression character classes, defined in
// http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
case "ASCII": return range(0x00, 0x7F); // ASCII case "ASCII" -> range(0x00, 0x7F); // ASCII
case "Alnum": return ctype(ASCII.ALNUM); // Alphanumeric characters case "Alnum" -> ctype(ASCII.ALNUM); // Alphanumeric characters
case "Alpha": return ctype(ASCII.ALPHA); // Alphabetic characters case "Alpha" -> ctype(ASCII.ALPHA); // Alphabetic characters
case "Blank": return ctype(ASCII.BLANK); // Space and tab characters case "Blank" -> ctype(ASCII.BLANK); // Space and tab characters
case "Cntrl": return ctype(ASCII.CNTRL); // Control characters case "Cntrl" -> ctype(ASCII.CNTRL); // Control characters
case "Digit": return range('0', '9'); // Numeric characters case "Digit" -> range('0', '9'); // Numeric characters
case "Graph": return ctype(ASCII.GRAPH); // printable and visible case "Graph" -> ctype(ASCII.GRAPH); // printable and visible
case "Lower": return caseIns ? ctype(ASCII.ALPHA) case "Lower" -> caseIns ? ctype(ASCII.ALPHA)
: range('a', 'z'); // Lower-case alphabetic : range('a', 'z'); // Lower-case alphabetic
case "Print": return range(0x20, 0x7E); // Printable characters case "Print" -> range(0x20, 0x7E); // Printable characters
case "Punct": return ctype(ASCII.PUNCT); // Punctuation characters case "Punct" -> ctype(ASCII.PUNCT); // Punctuation characters
case "Space": return ctype(ASCII.SPACE); // Space characters case "Space" -> ctype(ASCII.SPACE); // Space characters
case "Upper": return caseIns ? ctype(ASCII.ALPHA) case "Upper" -> caseIns ? ctype(ASCII.ALPHA)
: range('A', 'Z'); // Upper-case alphabetic : range('A', 'Z'); // Upper-case alphabetic
case "XDigit": return ctype(ASCII.XDIGIT); // hexadecimal digits case "XDigit" -> ctype(ASCII.XDIGIT); // hexadecimal digits
// Java character properties, defined by methods in Character.java // Java character properties, defined by methods in Character.java
case "javaLowerCase": return caseIns ? c -> Character.isLowerCase(c) || case "javaLowerCase" -> caseIns ? c -> Character.isLowerCase(c) ||
Character.isUpperCase(c) || Character.isUpperCase(c) ||
Character.isTitleCase(c) Character.isTitleCase(c)
: Character::isLowerCase; : Character::isLowerCase;
case "javaUpperCase": return caseIns ? c -> Character.isUpperCase(c) || case "javaUpperCase" -> caseIns ? c -> Character.isUpperCase(c) ||
Character.isLowerCase(c) || Character.isLowerCase(c) ||
Character.isTitleCase(c) Character.isTitleCase(c)
: Character::isUpperCase; : Character::isUpperCase;
case "javaAlphabetic": return Character::isAlphabetic; case "javaAlphabetic" -> Character::isAlphabetic;
case "javaIdeographic": return Character::isIdeographic; case "javaIdeographic" -> Character::isIdeographic;
case "javaTitleCase": return caseIns ? c -> Character.isTitleCase(c) || case "javaTitleCase" -> caseIns ? c -> Character.isTitleCase(c) ||
Character.isLowerCase(c) || Character.isLowerCase(c) ||
Character.isUpperCase(c) Character.isUpperCase(c)
: Character::isTitleCase; : Character::isTitleCase;
case "javaDigit": return Character::isDigit; case "javaDigit" -> Character::isDigit;
case "javaDefined": return Character::isDefined; case "javaDefined" -> Character::isDefined;
case "javaLetter": return Character::isLetter; case "javaLetter" -> Character::isLetter;
case "javaLetterOrDigit": return Character::isLetterOrDigit; case "javaLetterOrDigit" -> Character::isLetterOrDigit;
case "javaJavaIdentifierStart": return Character::isJavaIdentifierStart; case "javaJavaIdentifierStart" -> Character::isJavaIdentifierStart;
case "javaJavaIdentifierPart": return Character::isJavaIdentifierPart; case "javaJavaIdentifierPart" -> Character::isJavaIdentifierPart;
case "javaUnicodeIdentifierStart": return Character::isUnicodeIdentifierStart; case "javaUnicodeIdentifierStart" -> Character::isUnicodeIdentifierStart;
case "javaUnicodeIdentifierPart": return Character::isUnicodeIdentifierPart; case "javaUnicodeIdentifierPart" -> Character::isUnicodeIdentifierPart;
case "javaIdentifierIgnorable": return Character::isIdentifierIgnorable; case "javaIdentifierIgnorable" -> Character::isIdentifierIgnorable;
case "javaSpaceChar": return Character::isSpaceChar; case "javaSpaceChar" -> Character::isSpaceChar;
case "javaWhitespace": return Character::isWhitespace; case "javaWhitespace" -> Character::isWhitespace;
case "javaISOControl": return Character::isISOControl; case "javaISOControl" -> Character::isISOControl;
case "javaMirrored": return Character::isMirrored; case "javaMirrored" -> Character::isMirrored;
default: return null; default -> null;
} };
} }
private static CharPredicate category(final int typeMask) { private static CharPredicate category(final int typeMask) {

View file

@ -2343,17 +2343,8 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
boolean done = false; boolean done = false;
while(!done) { while(!done) {
int ch = peek(); int ch = peek();
switch(ch) { switch (ch) {
case '0': case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
int newRefNum = (refNum * 10) + (ch - '0'); int newRefNum = (refNum * 10) + (ch - '0');
// Add another number if it doesn't make a group // Add another number if it doesn't make a group
// that doesn't exist // that doesn't exist
@ -2363,10 +2354,8 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
} }
refNum = newRefNum; refNum = newRefNum;
read(); read();
break; }
default: default -> done = true;
done = true;
break;
} }
} }
hasGroupRef = true; hasGroupRef = true;
@ -2973,13 +2962,12 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
if (ch == '?') { if (ch == '?') {
ch = skip(); ch = skip();
switch (ch) { switch (ch) {
case ':': // (?:xxx) pure group case ':' -> { // (?:xxx) pure group
head = createGroup(true); head = createGroup(true);
tail = root; tail = root;
head.next = expr(tail); head.next = expr(tail);
break; }
case '=': // (?=xxx) and (?!xxx) lookahead case '=', '!' -> { // (?=xxx) and (?!xxx) lookahead
case '!':
head = createGroup(true); head = createGroup(true);
tail = root; tail = root;
head.next = expr(tail); head.next = expr(tail);
@ -2988,14 +2976,14 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
} else { } else {
head = tail = new Neg(head); head = tail = new Neg(head);
} }
break; }
case '>': // (?>xxx) independent group case '>' -> { // (?>xxx) independent group
head = createGroup(true); head = createGroup(true);
tail = root; tail = root;
head.next = expr(tail); head.next = expr(tail);
head = tail = new Ques(head, Qtype.INDEPENDENT); head = tail = new Ques(head, Qtype.INDEPENDENT);
break; }
case '<': // (?<xxx) look behind case '<' -> { // (?<xxx) look behind
ch = read(); ch = read();
if (ch != '=' && ch != '!') { if (ch != '=' && ch != '!') {
// named captured group // named captured group
@ -3006,7 +2994,7 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
capturingGroup = true; capturingGroup = true;
head = createGroup(false); head = createGroup(false);
tail = root; tail = root;
namedGroups().put(name, capturingGroupCount-1); namedGroups().put(name, capturingGroupCount - 1);
head.next = expr(tail); head.next = expr(tail);
break; break;
} }
@ -3038,11 +3026,9 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
// clear all top-closure-nodes inside lookbehind // clear all top-closure-nodes inside lookbehind
if (saveTCNCount < topClosureNodes.size()) if (saveTCNCount < topClosureNodes.size())
topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear(); topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear();
break; }
case '$': case '$', '@' -> throw error("Unknown group type");
case '@': default -> { // (?xxx:) inlined match flags
throw error("Unknown group type");
default: // (?xxx:) inlined match flags
unread(); unread();
addFlag(); addFlag();
ch = read(); ch = read();
@ -3055,7 +3041,7 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
head = createGroup(true); head = createGroup(true);
tail = root; tail = root;
head.next = expr(tail); head.next = expr(tail);
break; }
} }
} else { // (xxx) a regular group } else { // (xxx) a regular group
capturingGroup = true; capturingGroup = true;

View file

@ -76,23 +76,23 @@ class PrintPattern {
} }
private static String toStringCtype(int type) { private static String toStringCtype(int type) {
switch(type) { return switch (type) {
case UPPER: return "ASCII.UPPER"; case UPPER -> "ASCII.UPPER";
case LOWER: return "ASCII.LOWER"; case LOWER -> "ASCII.LOWER";
case DIGIT: return "ASCII.DIGIT"; case DIGIT -> "ASCII.DIGIT";
case SPACE: return "ASCII.SPACE"; case SPACE -> "ASCII.SPACE";
case PUNCT: return "ASCII.PUNCT"; case PUNCT -> "ASCII.PUNCT";
case CNTRL: return "ASCII.CNTRL"; case CNTRL -> "ASCII.CNTRL";
case BLANK: return "ASCII.BLANK"; case BLANK -> "ASCII.BLANK";
case UNDER: return "ASCII.UNDER"; case UNDER -> "ASCII.UNDER";
case ASCII: return "ASCII.ASCII"; case ASCII -> "ASCII.ASCII";
case ALPHA: return "ASCII.ALPHA"; case ALPHA -> "ASCII.ALPHA";
case ALNUM: return "ASCII.ALNUM"; case ALNUM -> "ASCII.ALNUM";
case GRAPH: return "ASCII.GRAPH"; case GRAPH -> "ASCII.GRAPH";
case WORD: return "ASCII.WORD"; case WORD -> "ASCII.WORD";
case XDIGIT: return "ASCII.XDIGIT"; case XDIGIT -> "ASCII.XDIGIT";
default: return "ASCII ?"; default -> "ASCII ?";
} };
} }
private static String toString(Pattern.Node node) { private static String toString(Pattern.Node node) {

View file

@ -88,14 +88,12 @@ final class Nodes {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static <T> Node<T> emptyNode(StreamShape shape) { static <T> Node<T> emptyNode(StreamShape shape) {
switch (shape) { return (Node<T>) switch (shape) {
case REFERENCE: return (Node<T>) EMPTY_NODE; case REFERENCE -> EMPTY_NODE;
case INT_VALUE: return (Node<T>) EMPTY_INT_NODE; case INT_VALUE -> EMPTY_INT_NODE;
case LONG_VALUE: return (Node<T>) EMPTY_LONG_NODE; case LONG_VALUE -> EMPTY_LONG_NODE;
case DOUBLE_VALUE: return (Node<T>) EMPTY_DOUBLE_NODE; case DOUBLE_VALUE -> EMPTY_DOUBLE_NODE;
default: };
throw new IllegalStateException("Unknown shape " + shape);
}
} }
/** /**
@ -119,18 +117,12 @@ final class Nodes {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static <T> Node<T> conc(StreamShape shape, Node<T> left, Node<T> right) { static <T> Node<T> conc(StreamShape shape, Node<T> left, Node<T> right) {
switch (shape) { return (Node<T>) switch (shape) {
case REFERENCE: case REFERENCE -> new ConcNode<>(left, right);
return new ConcNode<>(left, right); case INT_VALUE -> new ConcNode.OfInt((Node.OfInt) left, (Node.OfInt) right);
case INT_VALUE: case LONG_VALUE -> new ConcNode.OfLong((Node.OfLong) left, (Node.OfLong) right);
return (Node<T>) new ConcNode.OfInt((Node.OfInt) left, (Node.OfInt) right); case DOUBLE_VALUE -> new ConcNode.OfDouble((Node.OfDouble) left, (Node.OfDouble) right);
case LONG_VALUE: };
return (Node<T>) new ConcNode.OfLong((Node.OfLong) left, (Node.OfLong) right);
case DOUBLE_VALUE:
return (Node<T>) new ConcNode.OfDouble((Node.OfDouble) left, (Node.OfDouble) right);
default:
throw new IllegalStateException("Unknown shape " + shape);
}
} }
// Reference-based node methods // Reference-based node methods

View file

@ -81,11 +81,11 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
private final ZipCoder zc; private final ZipCoder zc;
private static int version(ZipEntry e) throws ZipException { private static int version(ZipEntry e) throws ZipException {
switch (e.method) { return switch (e.method) {
case DEFLATED: return 20; case DEFLATED -> 20;
case STORED: return 10; case STORED -> 10;
default: throw new ZipException("unsupported compression method"); default -> throw new ZipException("unsupported compression method");
} };
} }
/** /**
@ -258,7 +258,7 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
if (current != null) { if (current != null) {
ZipEntry e = current.entry; ZipEntry e = current.entry;
switch (e.method) { switch (e.method) {
case DEFLATED: case DEFLATED -> {
def.finish(); def.finish();
while (!def.finished()) { while (!def.finished()) {
deflate(); deflate();
@ -289,8 +289,8 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
} }
def.reset(); def.reset();
written += e.csize; written += e.csize;
break; }
case STORED: case STORED -> {
// we already know that both e.size and e.csize are the same // we already know that both e.size and e.csize are the same
if (e.size != written - locoff) { if (e.size != written - locoff) {
throw new ZipException( throw new ZipException(
@ -303,9 +303,8 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
Long.toHexString(e.crc) + " but got 0x" + Long.toHexString(e.crc) + " but got 0x" +
Long.toHexString(crc.getValue()) + ")"); Long.toHexString(crc.getValue()) + ")");
} }
break; }
default: default -> throw new ZipException("invalid compression method");
throw new ZipException("invalid compression method");
} }
crc.reset(); crc.reset();
current = null; current = null;
@ -336,19 +335,16 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
} }
ZipEntry entry = current.entry; ZipEntry entry = current.entry;
switch (entry.method) { switch (entry.method) {
case DEFLATED: case DEFLATED -> super.write(b, off, len);
super.write(b, off, len); case STORED -> {
break;
case STORED:
written += len; written += len;
if (written - locoff > entry.size) { if (written - locoff > entry.size) {
throw new ZipException( throw new ZipException(
"attempt to write past end of STORED entry"); "attempt to write past end of STORED entry");
} }
out.write(b, off, len); out.write(b, off, len);
break; }
default: default -> throw new ZipException("invalid compression method");
throw new ZipException("invalid compression method");
} }
crc.update(b, off, len); crc.update(b, off, len);
} }