Leverage basic Java 17 features (#451)

- Refactor code to use the following basic Java 17 features:
  - pattern matching for instanceof
  - @Serial annotation
  - switch expressions
  - enhanced switch statements
  - StringBuilder.isEmpty()
- Replace two switch statements with simpler if statements.
- Rename a few local variables.
This commit is contained in:
translatenix
2024-04-25 12:52:28 -07:00
committed by GitHub
parent 3ab9e4184e
commit a7c7e51180
142 changed files with 1333 additions and 1798 deletions

View File

@@ -17,13 +17,14 @@ package org.pkl.core;
import static org.pkl.core.DataSizeUnit.*;
import java.io.Serial;
import java.util.Objects;
import org.pkl.core.util.MathUtils;
import org.pkl.core.util.Nullable;
/** Java representation of a {@code pkl.base#DataSize} value. */
public final class DataSize implements Value {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final double value;
private final DataSizeUnit unit;
@@ -240,9 +241,7 @@ public final class DataSize implements Value {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof DataSize)) return false;
var other = (DataSize) obj;
if (!(obj instanceof DataSize other)) return false;
return convertValueTo(DataSizeUnit.BYTES) == other.convertValueTo(DataSizeUnit.BYTES);
}

View File

@@ -48,32 +48,20 @@ public enum DataSizeUnit {
* exists.
*/
public static @Nullable DataSizeUnit parse(String symbol) {
switch (symbol) {
case "b":
return BYTES;
case "kb":
return KILOBYTES;
case "kib":
return KIBIBYTES;
case "mb":
return MEGABYTES;
case "mib":
return MEBIBYTES;
case "gb":
return GIGABYTES;
case "gib":
return GIBIBYTES;
case "tb":
return TERABYTES;
case "tib":
return TEBIBYTES;
case "pb":
return PETABYTES;
case "pib":
return PEBIBYTES;
default:
return null;
}
return switch (symbol) {
case "b" -> BYTES;
case "kb" -> KILOBYTES;
case "kib" -> KIBIBYTES;
case "mb" -> MEGABYTES;
case "mib" -> MEBIBYTES;
case "gb" -> GIGABYTES;
case "gib" -> GIBIBYTES;
case "tb" -> TERABYTES;
case "tib" -> TEBIBYTES;
case "pb" -> PETABYTES;
case "pib" -> PEBIBYTES;
default -> null;
};
}
/** Returns the String symbol of this unit. */

View File

@@ -17,13 +17,14 @@ package org.pkl.core;
import static org.pkl.core.DurationUnit.*;
import java.io.Serial;
import java.util.Objects;
import org.pkl.core.util.DurationUtils;
import org.pkl.core.util.Nullable;
/** Java representation of a {@code pkl.base#Duration} value. */
public final class Duration implements Value {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final double value;
private final DurationUnit unit;
@@ -215,9 +216,7 @@ public final class Duration implements Value {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Duration)) return false;
var other = (Duration) obj;
if (!(obj instanceof Duration other)) return false;
return convertValueTo(DurationUnit.NANOS) == other.convertValueTo(DurationUnit.NANOS);
}

View File

@@ -46,24 +46,16 @@ public enum DurationUnit {
* exists.
*/
public static @Nullable DurationUnit parse(String symbol) {
switch (symbol) {
case "ns":
return NANOS;
case "us":
return MICROS;
case "ms":
return MILLIS;
case "s":
return SECONDS;
case "min":
return MINUTES;
case "h":
return HOURS;
case "d":
return DAYS;
default:
return null;
}
return switch (symbol) {
case "ns" -> NANOS;
case "us" -> MICROS;
case "ms" -> MILLIS;
case "s" -> SECONDS;
case "min" -> MINUTES;
case "h" -> HOURS;
case "d" -> DAYS;
default -> null;
};
}
/** Returns the string symbol of this unit. */
@@ -78,24 +70,15 @@ public enum DurationUnit {
/** Converts this unit to a {@link java.time.temporal.ChronoUnit}. */
public ChronoUnit toChronoUnit() {
switch (this) {
case NANOS:
return ChronoUnit.NANOS;
case MICROS:
return ChronoUnit.MICROS;
case MILLIS:
return ChronoUnit.MILLIS;
case SECONDS:
return ChronoUnit.SECONDS;
case MINUTES:
return ChronoUnit.MINUTES;
case HOURS:
return ChronoUnit.HOURS;
case DAYS:
return ChronoUnit.DAYS;
default:
throw new AssertionError("Unknown duration unit: " + this);
}
return switch (this) {
case NANOS -> ChronoUnit.NANOS;
case MICROS -> ChronoUnit.MICROS;
case MILLIS -> ChronoUnit.MILLIS;
case SECONDS -> ChronoUnit.SECONDS;
case MINUTES -> ChronoUnit.MINUTES;
case HOURS -> ChronoUnit.HOURS;
case DAYS -> ChronoUnit.DAYS;
};
}
/** Converts this unit to a {@link java.util.concurrent.TimeUnit}. */

View File

@@ -148,8 +148,7 @@ public class EvaluatorImpl implements Evaluator {
(module) -> {
var output = (VmTyped) VmUtils.readMember(module, Identifier.OUTPUT);
var value = VmUtils.readMember(output, Identifier.VALUE);
if (value instanceof VmValue) {
var vmValue = (VmValue) value;
if (value instanceof VmValue vmValue) {
vmValue.force(false);
return vmValue.export();
}
@@ -194,8 +193,7 @@ public class EvaluatorImpl implements Evaluator {
(module) -> {
var expressionResult =
VmUtils.evaluateExpression(module, expression, securityManager, moduleResolver);
if (expressionResult instanceof VmValue) {
var value = (VmValue) expressionResult;
if (expressionResult instanceof VmValue value) {
value.force(false);
return value.export();
}
@@ -248,8 +246,7 @@ public class EvaluatorImpl implements Evaluator {
var value = VmUtils.readMember(output, Identifier.VALUE);
var valueClassInfo = VmUtils.getClass(value).getPClassInfo();
if (valueClassInfo.equals(classInfo)) {
if (value instanceof VmValue) {
var vmValue = (VmValue) value;
if (value instanceof VmValue vmValue) {
vmValue.force(false);
//noinspection unchecked
return (T) vmValue.export();
@@ -317,10 +314,10 @@ public class EvaluatorImpl implements Evaluator {
} catch (Exception e) {
throw new PklBugException(e);
} catch (ExceptionInInitializerError e) {
if (!(e.getCause() instanceof VmException)) {
if (!(e.getCause() instanceof VmException vmException)) {
throw new PklBugException(e);
}
var pklException = ((VmException) e.getCause()).toPklException(frameTransformer);
var pklException = vmException.toPklException(frameTransformer);
var error = new ExceptionInInitializerError(pklException);
error.setStackTrace(e.getStackTrace());
throw new PklBugException(error);

View File

@@ -15,6 +15,7 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
@@ -23,8 +24,7 @@ import org.pkl.core.util.Nullable;
/** Common base class for TypeAlias, PClass, PClass.Property, and PClass.Method. */
public abstract class Member implements Serializable {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final @Nullable String docComment;
private final SourceLocation sourceLocation;
@@ -99,8 +99,7 @@ public abstract class Member implements Serializable {
}
public static class SourceLocation implements Serializable {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final int startLine;
private final int endLine;

View File

@@ -15,12 +15,13 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.util.*;
import org.pkl.core.util.Nullable;
/** Java representation of a {@code pkl.base#Class} value. */
public final class PClass extends Member implements Value {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PClassInfo<?> classInfo;
private final List<TypeParameter> typeParameters;
@@ -138,8 +139,7 @@ public final class PClass extends Member implements Value {
}
public abstract static class ClassMember extends Member {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PClass owner;
@@ -176,8 +176,7 @@ public final class PClass extends Member implements Value {
}
public static final class Property extends ClassMember {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PType type;
@@ -213,8 +212,7 @@ public final class PClass extends Member implements Value {
}
public static final class Method extends ClassMember {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final List<TypeParameter> typeParameters;
private final Map<String, PType> parameters;

View File

@@ -17,6 +17,7 @@ package org.pkl.core;
import static java.util.Map.*;
import java.io.Serial;
import java.io.Serializable;
import java.net.URI;
import java.util.*;
@@ -26,8 +27,7 @@ import org.pkl.core.util.Nullable;
/** Information about a Pkl class and its Java representation. */
@SuppressWarnings("rawtypes")
public final class PClassInfo<T> implements Serializable {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
// Simple name of a module's class.
// User-facing via `module.getClass()` and error messages.
@@ -100,7 +100,7 @@ public final class PClassInfo<T> implements Serializable {
/** Returns the class info for the given value's class. */
@SuppressWarnings("unchecked")
public static <T> PClassInfo<T> forValue(T value) {
if (value instanceof Value) return (PClassInfo<T>) ((Value) value).getClassInfo();
if (value instanceof Value v) return (PClassInfo<T>) v.getClassInfo();
if (value instanceof String) return (PClassInfo<T>) String;
if (value instanceof Boolean) return (PClassInfo<T>) Boolean;
@@ -179,9 +179,7 @@ public final class PClassInfo<T> implements Serializable {
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof PClassInfo)) return false;
var other = (PClassInfo<?>) obj;
if (!(obj instanceof PClassInfo<?> other)) return false;
return qualifiedName.equals(other.qualifiedName);
}

View File

@@ -15,6 +15,7 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.net.URI;
import java.util.Map;
import java.util.Objects;
@@ -22,7 +23,7 @@ import org.pkl.core.util.Nullable;
/** Java representation of a Pkl module. */
public final class PModule extends PObject {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final URI moduleUri;
private final String moduleName;
@@ -62,10 +63,7 @@ public final class PModule extends PObject {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof PModule)) return false;
var other = (PModule) obj;
if (!(obj instanceof PModule other)) return false;
return moduleUri.equals(other.moduleUri)
&& moduleName.equals(other.moduleName)
&& classInfo.equals(other.classInfo)

View File

@@ -15,9 +15,11 @@
*/
package org.pkl.core;
import java.io.Serial;
/** Java representation of a {@code pkl.base#Null} value. */
public final class PNull implements Value {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private static final PNull INSTANCE = new PNull();
/** Returns the sole instance of this class. */

View File

@@ -15,13 +15,14 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.util.Map;
import java.util.Objects;
import org.pkl.core.util.Nullable;
/** Java representation of a Pkl object. */
public class PObject implements Composite {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
protected final PClassInfo<?> classInfo;
protected final Map<String, Object> properties;

View File

@@ -15,30 +15,30 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.io.Serializable;
import java.util.*;
/** A Pkl type as used in type annotations. */
public abstract class PType implements Serializable {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
/** The `unknown` type. Omitting a type annotation is equivalent to stating this type. */
public static final PType UNKNOWN =
new PType() {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
};
/** The bottom type. */
public static final PType NOTHING =
new PType() {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
};
/** The type of the enclosing module. */
public static final PType MODULE =
new PType() {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
};
private PType() {}
@@ -48,8 +48,7 @@ public abstract class PType implements Serializable {
}
public static final class StringLiteral extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final String literal;
@@ -63,8 +62,7 @@ public abstract class PType implements Serializable {
}
public static final class Class extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PClass pClass;
private final List<PType> typeArguments;
@@ -97,8 +95,7 @@ public abstract class PType implements Serializable {
}
public static final class Nullable extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PType baseType;
@@ -133,8 +130,7 @@ public abstract class PType implements Serializable {
}
public static final class Alias extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final TypeAlias typeAlias;
private final List<PType> typeArguments;
@@ -169,8 +165,7 @@ public abstract class PType implements Serializable {
}
public static final class Function extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final List<PType> parameterTypes;
private final PType returnType;
@@ -190,8 +185,7 @@ public abstract class PType implements Serializable {
}
public static final class Union extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final List<PType> elementTypes;
@@ -205,8 +199,7 @@ public abstract class PType implements Serializable {
}
public static final class TypeVariable extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final TypeParameter typeParameter;

View File

@@ -15,13 +15,14 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.pkl.core.util.Nullable;
/** Java representation of a {@code pkl.base#Pair} value. */
public final class Pair<F, S> implements Value, Iterable<Object> {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final F first;
private final S second;
@@ -54,14 +55,11 @@ public final class Pair<F, S> implements Value, Iterable<Object> {
@Override
public Object next() {
switch (pos++) {
case 0:
return first;
case 1:
return second;
default:
throw new NoSuchElementException("Pair only has two elements.");
}
return switch (pos++) {
case 0 -> first;
case 1 -> second;
default -> throw new NoSuchElementException("Pair only has two elements.");
};
}
};
}
@@ -84,9 +82,7 @@ public final class Pair<F, S> implements Value, Iterable<Object> {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Pair)) return false;
var other = (Pair<?, ?>) obj;
if (!(obj instanceof Pair<?, ?> other)) return false;
return first.equals(other.first) && second.equals(other.second);
}

View File

@@ -42,14 +42,14 @@ final class PcfRenderer implements ValueRenderer {
@Override
public void renderDocument(Object value) {
if (!(value instanceof Composite)) {
if (!(value instanceof Composite composite)) {
throw new RendererException(
String.format(
"The top-level value of a Pcf document must have type `Composite`, but got type `%s`.",
value.getClass().getTypeName()));
}
new Visitor().doVisitProperties(((Composite) value).getProperties());
new Visitor().doVisitProperties(composite.getProperties());
}
@Override

View File

@@ -101,9 +101,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Platform)) return false;
var other = (Platform) obj;
if (!(obj instanceof Platform other)) return false;
return language.equals(other.language)
&& runtime.equals(other.runtime)
&& virtualMachine.equals(other.virtualMachine)
@@ -133,9 +131,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Language)) return false;
var other = (Language) obj;
if (!(obj instanceof Language other)) return false;
return version.equals(other.version);
}
@@ -169,9 +165,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Runtime)) return false;
var other = (Runtime) obj;
if (!(obj instanceof Runtime other)) return false;
return name.equals(other.name) && version.equals(other.version);
}
@@ -205,9 +199,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof VirtualMachine)) return false;
var other = (VirtualMachine) obj;
if (!(obj instanceof VirtualMachine other)) return false;
return name.equals(other.name) && version.equals(other.version);
}
@@ -241,9 +233,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof OperatingSystem)) return false;
var other = (OperatingSystem) obj;
if (!(obj instanceof OperatingSystem other)) return false;
return name.equals(other.name) && version.equals(other.version);
}
@@ -270,9 +260,7 @@ public final class Platform {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Processor)) return false;
var other = (Processor) obj;
if (!(obj instanceof Processor other)) return false;
return architecture.equals(other.architecture);
}

View File

@@ -49,12 +49,11 @@ final class PropertiesRenderer implements ValueRenderer {
private class Visitor implements ValueConverter<String> {
public void renderDocument(Object value) {
if (value instanceof Composite) {
doVisitMap(null, ((Composite) value).getProperties());
} else if (value instanceof Map) {
doVisitMap(null, (Map<?, ?>) value);
} else if (value instanceof Pair) {
Pair<?, ?> pair = (Pair<?, ?>) value;
if (value instanceof Composite composite) {
doVisitMap(null, composite.getProperties());
} else if (value instanceof Map<?, ?> map) {
doVisitMap(null, map);
} else if (value instanceof Pair<?, ?> pair) {
doVisitKeyAndValue(null, pair.getFirst(), pair.getSecond());
} else {
throw new RendererException(
@@ -181,10 +180,10 @@ final class PropertiesRenderer implements ValueRenderer {
var keyString = keyPrefix == null ? convert(key) : keyPrefix + "." + convert(key);
if (value instanceof Composite) {
doVisitMap(keyString, ((Composite) value).getProperties());
} else if (value instanceof Map) {
doVisitMap(keyString, (Map<?, ?>) value);
if (value instanceof Composite composite) {
doVisitMap(keyString, composite.getProperties());
} else if (value instanceof Map<?, ?> map) {
doVisitMap(keyString, map);
} else {
write(keyString, true, restrictCharset);
writeSeparator();

View File

@@ -148,9 +148,7 @@ public class Release {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Release)) return false;
var other = (Release) obj;
if (!(obj instanceof Release other)) return false;
return version.equals(other.version)
&& versionInfo.equals(other.versionInfo)
&& commitId.equals(other.commitId)
@@ -200,9 +198,7 @@ public class Release {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof SourceCode)) return false;
var other = (SourceCode) obj;
if (!(obj instanceof SourceCode other)) return false;
return homepage.equals(other.homepage) && version.equals(other.version);
}
@@ -229,9 +225,7 @@ public class Release {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Documentation)) return false;
var other = (Documentation) obj;
if (!(obj instanceof Documentation other)) return false;
return homepage.equals(other.homepage);
}
@@ -262,9 +256,7 @@ public class Release {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof StandardLibrary)) return false;
var other = (StandardLibrary) obj;
if (!(obj instanceof StandardLibrary other)) return false;
return modules.equals(other.modules);
}

View File

@@ -75,21 +75,16 @@ public final class SecurityManagers {
SecurityManagers::getDefaultTrustLevel;
private static int getDefaultTrustLevel(URI uri) {
switch (uri.getScheme()) {
case "repl":
return 40;
case "file":
return uri.getHost() == null ? 30 : 10;
case "jar":
// use trust level of embedded URL
return getDefaultTrustLevel(URI.create(uri.toString().substring(4)));
case "modulepath":
return 20;
case "pkl":
return 0;
default:
return 10;
}
return switch (uri.getScheme()) {
case "repl" -> 40;
case "file" -> uri.getHost() == null ? 30 : 10;
case "jar" ->
// use trust level of embedded URL
getDefaultTrustLevel(URI.create(uri.toString().substring(4)));
case "modulepath" -> 20;
case "pkl" -> 0;
default -> 10;
};
}
/**

View File

@@ -105,10 +105,7 @@ public final class StackFrame {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof StackFrame)) return false;
var other = (StackFrame) obj;
if (!(obj instanceof StackFrame other)) return false;
if (startLine != other.startLine) return false;
if (startColumn != other.startColumn) return false;
if (endLine != other.endLine) return false;

View File

@@ -15,6 +15,7 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.util.List;
import java.util.Set;
import org.pkl.core.util.LateInit;
@@ -22,7 +23,7 @@ import org.pkl.core.util.Nullable;
/** Java representation of a {@code pkl.base#TypeAlias} value. */
public final class TypeAlias extends Member implements Value {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final String moduleName;
private final String qualifiedName;

View File

@@ -15,13 +15,13 @@
*/
package org.pkl.core;
import java.io.Serial;
import java.io.Serializable;
import org.pkl.core.util.LateInit;
/** A type parameter of a generic class, type alias, or method. */
public final class TypeParameter implements Serializable {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final Variance variance;
private final String name;

View File

@@ -56,24 +56,24 @@ public interface ValueConverter<T> {
T convertRegex(Pattern value);
default T convert(Object value) {
if (value instanceof Value) {
return ((Value) value).accept(this);
} else if (value instanceof String) {
return convertString((String) value);
} else if (value instanceof Boolean) {
return convertBoolean((Boolean) value);
} else if (value instanceof Long) {
return convertInt((Long) value);
} else if (value instanceof Double) {
return convertFloat((Double) value);
} else if (value instanceof List) {
return convertList((List<?>) value);
} else if (value instanceof Set) {
return convertSet((Set<?>) value);
} else if (value instanceof Map) {
return convertMap((Map<?, ?>) value);
} else if (value instanceof Pattern) {
return convertRegex((Pattern) value);
if (value instanceof Value v) {
return (v.accept(this));
} else if (value instanceof String string) {
return convertString(string);
} else if (value instanceof Boolean b) {
return convertBoolean(b);
} else if (value instanceof Long l) {
return convertInt(l);
} else if (value instanceof Double d) {
return convertFloat(d);
} else if (value instanceof List<?> list) {
return convertList(list);
} else if (value instanceof Set<?> set) {
return convertSet(set);
} else if (value instanceof Map<?, ?> map) {
return convertMap(map);
} else if (value instanceof Pattern pattern) {
return convertRegex(pattern);
} else {
throw new IllegalArgumentException("Cannot convert value with unexpected type: " + value);
}

View File

@@ -135,31 +135,24 @@ public final class ValueFormatter {
for (; i < value.length(); i++) {
var ch = value.charAt(i);
switch (ch) {
case '\n':
appendable.append(escapeSequence).append('n');
break;
case '\r':
appendable.append(escapeSequence).append('r');
break;
case '\t':
appendable.append(escapeSequence).append('t');
break;
case '\\':
case '\n' -> appendable.append(escapeSequence).append('n');
case '\r' -> appendable.append(escapeSequence).append('r');
case '\t' -> appendable.append(escapeSequence).append('t');
case '\\' -> {
if (useCustomStringDelimiters) {
appendable.append(ch);
} else {
appendable.append("\\\\");
}
break;
case '"':
}
case '"' -> {
if (useCustomStringDelimiters) {
appendable.append(ch);
} else {
appendable.append("\\\"");
}
break;
default:
appendable.append(ch);
}
default -> appendable.append(ch);
}
}
@@ -177,27 +170,27 @@ public final class ValueFormatter {
for (var i = 0; i < value.length(); i++) {
var ch = value.charAt(i);
switch (ch) {
case '\n':
case '\n' -> {
appendable.append('\n').append(lineIndent);
consecutiveQuotes = 0;
break;
case '\r':
}
case '\r' -> {
appendable.append(escapeSequence).append('r');
consecutiveQuotes = 0;
break;
case '\t':
}
case '\t' -> {
appendable.append(escapeSequence).append('t');
consecutiveQuotes = 0;
break;
case '\\':
}
case '\\' -> {
if (useCustomStringDelimiters) {
appendable.append(ch);
} else {
appendable.append("\\\\");
}
consecutiveQuotes = 0;
break;
case '"':
}
case '"' -> {
if (consecutiveQuotes == 2 && !useCustomStringDelimiters) {
appendable.append("\\\"");
consecutiveQuotes = 0;
@@ -205,10 +198,11 @@ public final class ValueFormatter {
appendable.append('"');
consecutiveQuotes += 1;
}
break;
default:
}
default -> {
appendable.append(ch);
consecutiveQuotes = 0;
}
}
}
@@ -272,12 +266,12 @@ public final class ValueFormatter {
for (var i = 0; i < value.length(); i++) {
var ch = value.charAt(i);
switch (ch) {
case '\\':
case '\\' -> {
currentPoundContext = PoundContext.BACKSLASH;
currentPoundCountBackslash = 1;
poundCountBackslash = Math.max(poundCountBackslash, currentPoundCountBackslash);
break;
case '"':
}
case '"' -> {
consecutiveQuoteCount += 1;
if (consecutiveQuoteCount < 3) {
currentPoundContext = PoundContext.SINGLELINE_QUOTE;
@@ -289,34 +283,36 @@ public final class ValueFormatter {
poundCountMultilineQuote =
Math.max(poundCountMultilineQuote, currentPoundCountMultilineQuote);
}
break;
case '#':
}
case '#' -> {
consecutiveQuoteCount = 0;
switch (currentPoundContext) {
case SINGLELINE_QUOTE:
case SINGLELINE_QUOTE -> {
currentPoundCountSingleQuote += 1;
poundCountSingleQuote =
Math.max(poundCountSingleQuote, currentPoundCountSingleQuote);
break;
case MULTILINE_QUOTE:
}
case MULTILINE_QUOTE -> {
currentPoundCountMultilineQuote += 1;
poundCountMultilineQuote =
Math.max(poundCountMultilineQuote, currentPoundCountMultilineQuote);
break;
case BACKSLASH:
}
case BACKSLASH -> {
currentPoundCountBackslash += 1;
poundCountBackslash = Math.max(poundCountBackslash, currentPoundCountBackslash);
break;
default:
break;
}
default -> {}
}
break;
case '\n':
}
case '\n' -> {
isMultiline = true;
default:
consecutiveQuoteCount = 0;
currentPoundContext = PoundContext.OTHER;
break;
}
default -> {
consecutiveQuoteCount = 0;
currentPoundContext = PoundContext.OTHER;
}
}
}
return new StringFacts(

View File

@@ -90,24 +90,24 @@ public interface ValueVisitor {
}
default void visit(Object value) {
if (value instanceof Value) {
((Value) value).accept(this);
} else if (value instanceof String) {
visitString((String) value);
} else if (value instanceof Boolean) {
visitBoolean((Boolean) value);
} else if (value instanceof Long) {
visitInt((Long) value);
} else if (value instanceof Double) {
visitFloat((Double) value);
} else if (value instanceof List) {
visitList((List<?>) value);
} else if (value instanceof Set) {
visitSet((Set<?>) value);
} else if (value instanceof Map) {
visitMap((Map<?, ?>) value);
} else if (value instanceof Pattern) {
visitRegex((Pattern) value);
if (value instanceof Value v) {
v.accept(this);
} else if (value instanceof String string) {
visitString(string);
} else if (value instanceof Boolean b) {
visitBoolean(b);
} else if (value instanceof Long l) {
visitInt(l);
} else if (value instanceof Double d) {
visitFloat(d);
} else if (value instanceof List<?> list) {
visitList(list);
} else if (value instanceof Set<?> set) {
visitSet(set);
} else if (value instanceof Map<?, ?> map) {
visitMap(map);
} else if (value instanceof Pattern pattern) {
visitRegex(pattern);
} else {
throw new IllegalArgumentException("Cannot visit value with unexpected type: " + value);
}

View File

@@ -194,9 +194,7 @@ public final class Version implements Comparable<Version> {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Version)) return false;
var other = (Version) obj;
if (!(obj instanceof Version other)) return false;
return major == other.major
&& minor == other.minor
&& patch == other.patch
@@ -210,8 +208,7 @@ public final class Version implements Comparable<Version> {
@Override
public String toString() {
return ""
+ major
return major
+ "."
+ minor
+ "."

View File

@@ -75,13 +75,12 @@ final class YamlRenderer implements ValueRenderer {
@Override
public void renderDocument(Object value) {
if (isStream) {
if (!(value instanceof Iterable)) {
if (!(value instanceof Iterable<?> iterable)) {
throw new RendererException(
String.format(
"The top-level value of a YAML stream must have type `Collection`, but got type `%s`.",
value.getClass().getTypeName()));
}
var iterable = (Iterable<?>) value;
emitter.emit(new StreamStartEvent());
for (var elem : iterable) {
emitter.emit(new DocumentStartEvent(false, Optional.empty(), Map.of()));

View File

@@ -89,7 +89,6 @@ public abstract class MemberNode extends PklRootNode {
}
public boolean isUndefined() {
return bodyNode instanceof DefaultPropertyBodyNode
&& ((DefaultPropertyBodyNode) bodyNode).isUndefined();
return bodyNode instanceof DefaultPropertyBodyNode propBodyNode && propBodyNode.isUndefined();
}
}

View File

@@ -161,26 +161,19 @@ public final class VmModifier {
}
public static String toString(int modifier) {
switch (modifier) {
case ABSTRACT:
return "abstract";
case OPEN:
return "open";
case LOCAL:
return "local";
case HIDDEN:
return "hidden";
case EXTERNAL:
return "external";
case FIXED:
return "fixed";
case CONST:
return "const";
default:
throw new VmExceptionBuilder()
.bug("Cannot convert internal modifier `%s` to a string.", toString(modifier))
.build();
}
return switch (modifier) {
case ABSTRACT -> "abstract";
case OPEN -> "open";
case LOCAL -> "local";
case HIDDEN -> "hidden";
case EXTERNAL -> "external";
case FIXED -> "fixed";
case CONST -> "const";
default ->
throw new VmExceptionBuilder()
.bug("Cannot convert internal modifier `%s` to a string.", toString(modifier))
.build();
};
}
public static VmSet getMirrors(int modifiers, boolean isClass) {

View File

@@ -43,17 +43,10 @@ public abstract class AbstractAstBuilder<T> extends PklParserBaseVisitor<T> {
var builder = new StringBuilder();
for (var token : ts) {
switch (token.getType()) {
case PklLexer.SLCharacters:
builder.append(token.getText());
break;
case PklLexer.SLCharacterEscape:
builder.append(parseCharacterEscapeSequence(token));
break;
case PklLexer.SLUnicodeEscape:
builder.appendCodePoint(parseUnicodeEscapeSequence(token));
break;
default:
throw exceptionBuilder().unreachableCode().build();
case PklLexer.SLCharacters -> builder.append(token.getText());
case PklLexer.SLCharacterEscape -> builder.append(parseCharacterEscapeSequence(token));
case PklLexer.SLUnicodeEscape -> builder.appendCodePoint(parseUnicodeEscapeSequence(token));
default -> throw exceptionBuilder().unreachableCode().build();
}
}
@@ -88,23 +81,19 @@ public abstract class AbstractAstBuilder<T> extends PklParserBaseVisitor<T> {
var text = token.getText();
var lastChar = text.charAt(text.length() - 1);
switch (lastChar) {
case 'n':
return "\n";
case 'r':
return "\r";
case 't':
return "\t";
case '"':
return "\"";
case '\\':
return "\\";
default:
throw exceptionBuilder()
.evalError("invalidCharacterEscapeSequence", text, text.substring(0, text.length() - 1))
.withSourceSection(createSourceSection(token))
.build();
}
return switch (lastChar) {
case 'n' -> "\n";
case 'r' -> "\r";
case 't' -> "\t";
case '"' -> "\"";
case '\\' -> "\\";
default ->
throw exceptionBuilder()
.evalError(
"invalidCharacterEscapeSequence", text, text.substring(0, text.length() - 1))
.withSourceSection(createSourceSection(token))
.build();
};
}
protected final SourceSection createSourceSection(ParserRuleContext ctx) {

View File

@@ -461,7 +461,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
while (parent instanceof IfExprContext
|| parent instanceof TraceExprContext
|| parent instanceof LetExprContext && ((LetExprContext) parent).r == child) {
|| parent instanceof LetExprContext letExpr && letExpr.r == child) {
if (parent instanceof LetExprContext) {
assert scope != null;
@@ -481,7 +481,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
scope.getName(),
levelsUp == 0 ? new GetOwnerNode() : new GetEnclosingOwnerNode(levelsUp));
} else if (parent instanceof ObjectElementContext
|| parent instanceof ObjectEntryContext && ((ObjectEntryContext) parent).v == child) {
|| parent instanceof ObjectEntryContext objectEntry && objectEntry.v == child) {
inferredParentNode =
ApplyVmFunction1NodeGen.create(
ReadPropertyNodeGen.create(
@@ -506,7 +506,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
language,
scopeName,
levelsUp == 0 ? new GetOwnerNode() : new GetEnclosingOwnerNode(levelsUp));
} else if (parent instanceof LetExprContext && ((LetExprContext) parent).l == child) {
} else if (parent instanceof LetExprContext letExpr && letExpr.l == child) {
// TODO (unclear how to infer type now that let-expression is implemented as lambda
// invocation)
throw exceptionBuilder()
@@ -604,8 +604,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
if (VmModifier.isExternal(modifiers)) {
bodyNode =
externalMemberRegistry.getPropertyBody(scope.getQualifiedName(), headerSection);
if (bodyNode instanceof LanguageAwareNode) {
((LanguageAwareNode) bodyNode).initLanguage(language);
if (bodyNode instanceof LanguageAwareNode languageAwareNode) {
languageAwareNode.initLanguage(language);
}
} else if (VmModifier.isAbstract(modifiers)) {
bodyNode =
@@ -1046,15 +1046,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
checkSpaceSeparatedObjectMembers(ctx);
for (var memberCtx : objectMemberCtx) {
if (memberCtx instanceof ObjectPropertyContext) {
var propertyCtx = (ObjectPropertyContext) memberCtx;
if (memberCtx instanceof ObjectPropertyContext propertyCtx) {
addProperty(members, doVisitObjectProperty(propertyCtx));
continue;
}
if (memberCtx instanceof ObjectEntryContext) {
var entryCtx = (ObjectEntryContext) memberCtx;
if (memberCtx instanceof ObjectEntryContext entryCtx) {
var keyAndValue = doVisitObjectEntry(entryCtx);
var key = keyAndValue.first;
keyNodes.add(key);
@@ -1063,15 +1060,13 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
continue;
}
if (memberCtx instanceof ObjectElementContext) {
var elementCtx = (ObjectElementContext) memberCtx;
if (memberCtx instanceof ObjectElementContext elementCtx) {
var element = doVisitObjectElement(elementCtx);
elements.add(element);
continue;
}
if (memberCtx instanceof ObjectMethodContext) {
var methodCtx = (ObjectMethodContext) memberCtx;
if (memberCtx instanceof ObjectMethodContext methodCtx) {
addProperty(members, doVisitObjectMethod(methodCtx));
continue;
}
@@ -1191,8 +1186,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
null,
scope.getQualifiedName());
if (elementNode instanceof ConstantNode) {
member.initConstantValue((ConstantNode) elementNode);
if (elementNode instanceof ConstantNode constantNode) {
member.initConstantValue(constantNode);
} else {
member.initMemberNode(
new UntypedObjectMemberNode(
@@ -1248,8 +1243,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
if (valueCtx != null) { // ["key"] = value
var valueNode = visitExpr(valueCtx);
if (valueNode instanceof ConstantNode) {
member.initConstantValue((ConstantNode) valueNode);
if (valueNode instanceof ConstantNode constantNode) {
member.initConstantValue(constantNode);
} else {
member.initMemberNode(
new UntypedObjectMemberNode(
@@ -1297,24 +1292,16 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
@Override
public Integer visitModifier(ModifierContext ctx) {
switch (ctx.t.getType()) {
case PklLexer.EXTERNAL:
return VmModifier.EXTERNAL;
case PklLexer.ABSTRACT:
return VmModifier.ABSTRACT;
case PklLexer.OPEN:
return VmModifier.OPEN;
case PklLexer.LOCAL:
return VmModifier.LOCAL;
case PklLexer.HIDDEN_:
return VmModifier.HIDDEN;
case PklLexer.FIXED:
return VmModifier.FIXED;
case PklLexer.CONST:
return VmModifier.CONST;
default:
throw createUnexpectedTokenError(ctx.t);
}
return switch (ctx.t.getType()) {
case PklLexer.EXTERNAL -> VmModifier.EXTERNAL;
case PklLexer.ABSTRACT -> VmModifier.ABSTRACT;
case PklLexer.OPEN -> VmModifier.OPEN;
case PklLexer.LOCAL -> VmModifier.LOCAL;
case PklLexer.HIDDEN_ -> VmModifier.HIDDEN;
case PklLexer.FIXED -> VmModifier.FIXED;
case PklLexer.CONST -> VmModifier.CONST;
default -> throw createUnexpectedTokenError(ctx.t);
};
}
private int doVisitModifiers(
@@ -1410,8 +1397,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
bodyNode =
externalMemberRegistry.getFunctionBody(
scope.getQualifiedName(), headerSection, paramCount);
if (bodyNode instanceof LanguageAwareNode) {
((LanguageAwareNode) bodyNode).initLanguage(language);
if (bodyNode instanceof LanguageAwareNode languageAwareNode) {
languageAwareNode.initLanguage(language);
}
} else if (VmModifier.isAbstract(modifiers)) {
bodyNode =
@@ -1730,33 +1717,30 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
@Override
public Object visitComparisonExpr(ComparisonExprContext ctx) {
switch (ctx.t.getType()) {
case PklLexer.LT:
return LessThanNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.GT:
return GreaterThanNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.LTE:
return LessThanOrEqualNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.GTE:
return GreaterThanOrEqualNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default:
throw createUnexpectedTokenError(ctx.t);
}
return switch (ctx.t.getType()) {
case PklLexer.LT ->
LessThanNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.GT ->
GreaterThanNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.LTE ->
LessThanOrEqualNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.GTE ->
GreaterThanOrEqualNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default -> throw createUnexpectedTokenError(ctx.t);
};
}
@Override
public Object visitEqualityExpr(EqualityExprContext ctx) {
switch (ctx.t.getType()) {
case PklLexer.EQUAL:
return EqualNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.NOT_EQUAL:
return NotEqualNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default:
throw createUnexpectedTokenError(ctx.t);
}
return switch (ctx.t.getType()) {
case PklLexer.EQUAL ->
EqualNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.NOT_EQUAL ->
NotEqualNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default -> throw createUnexpectedTokenError(ctx.t);
};
}
@Override
@@ -1879,34 +1863,30 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
@Override
public ExpressionNode visitAdditiveExpr(AdditiveExprContext ctx) {
switch (ctx.t.getType()) {
case PklLexer.PLUS:
return AdditionNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.MINUS:
return SubtractionNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default:
throw createUnexpectedTokenError(ctx.t);
}
return switch (ctx.t.getType()) {
case PklLexer.PLUS ->
AdditionNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.MINUS ->
SubtractionNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default -> throw createUnexpectedTokenError(ctx.t);
};
}
@Override
public ExpressionNode visitMultiplicativeExpr(MultiplicativeExprContext ctx) {
switch (ctx.t.getType()) {
case PklLexer.STAR:
return MultiplicationNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.DIV:
return DivisionNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.INT_DIV:
return TruncatingDivisionNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.MOD:
return RemainderNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default:
throw createUnexpectedTokenError(ctx.t);
}
return switch (ctx.t.getType()) {
case PklLexer.STAR ->
MultiplicationNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.DIV ->
DivisionNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.INT_DIV ->
TruncatingDivisionNodeGen.create(
createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
case PklLexer.MOD ->
RemainderNodeGen.create(createSourceSection(ctx), visitExpr(ctx.l), visitExpr(ctx.r));
default -> throw createUnexpectedTokenError(ctx.t);
};
}
@Override
@@ -1951,14 +1931,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
if (receiver instanceof OuterNode) {
var outerScope = getParentLexicalScope();
if (outerScope != null) {
switch (constLevel) {
case MODULE:
needsConst = outerScope.isModuleScope();
break;
case ALL:
needsConst = outerScope.getConstLevel() != ConstLevel.ALL;
break;
}
needsConst =
switch (constLevel) {
case MODULE -> outerScope.isModuleScope();
case ALL -> outerScope.getConstLevel() != ConstLevel.ALL;
case NONE -> false;
};
}
} else if (receiver instanceof GetModuleNode) {
needsConst = constLevel != ConstLevel.NONE;
@@ -1998,13 +1976,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
var propertyName = toIdentifier(ctx.Identifier());
var receiver = visitExpr(ctx.expr());
if (receiver instanceof IntLiteralNode) {
if (receiver instanceof IntLiteralNode intLiteralNode) {
var durationUnit = VmDuration.toUnit(propertyName);
if (durationUnit != null) {
//noinspection ConstantConditions
return new ConstantValueNode(
sourceSection,
new VmDuration(((IntLiteralNode) receiver).executeInt(null), durationUnit));
sourceSection, new VmDuration(intLiteralNode.executeInt(null), durationUnit));
}
var dataSizeUnit = VmDataSize.toUnit(propertyName);
if (dataSizeUnit != null) {
@@ -2015,13 +1992,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
}
}
if (receiver instanceof FloatLiteralNode) {
if (receiver instanceof FloatLiteralNode floatLiteralNode) {
var durationUnit = VmDuration.toUnit(propertyName);
if (durationUnit != null) {
//noinspection ConstantConditions
return new ConstantValueNode(
sourceSection,
new VmDuration(((FloatLiteralNode) receiver).executeFloat(null), durationUnit));
sourceSection, new VmDuration(floatLiteralNode.executeFloat(null), durationUnit));
}
var dataSizeUnit = VmDataSize.toUnit(propertyName);
if (dataSizeUnit != null) {
@@ -2037,14 +2013,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
if (receiver instanceof OuterNode) {
var outerScope = getParentLexicalScope();
if (outerScope != null) {
switch (constLevel) {
case MODULE:
needsConst = outerScope.isModuleScope();
break;
case ALL:
needsConst = outerScope.getConstLevel() != ConstLevel.ALL;
break;
}
needsConst =
switch (constLevel) {
case MODULE -> outerScope.isModuleScope();
case ALL -> outerScope.getConstLevel() != ConstLevel.ALL;
case NONE -> false;
};
}
} else if (receiver instanceof GetModuleNode) {
needsConst = constLevel != ConstLevel.NONE;
@@ -2482,13 +2456,12 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
while (!list.isEmpty()) {
var current = list.removeFirst();
if (current instanceof UnionTypeContext) {
var union = (UnionTypeContext) current;
list.addFirst(union.r);
list.addFirst(union.l);
if (current instanceof UnionTypeContext unionType) {
list.addFirst(unionType.r);
list.addFirst(unionType.l);
continue;
}
if (current instanceof DefaultUnionTypeContext) {
if (current instanceof DefaultUnionTypeContext defaultUnionType) {
if (defaultIndex == -1) {
defaultIndex = index;
} else {
@@ -2497,10 +2470,9 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
.withSourceSection(createSourceSection(ctx))
.build();
}
var def = (DefaultUnionTypeContext) current;
isUnionOfStringLiterals =
isUnionOfStringLiterals && def.type() instanceof StringLiteralTypeContext;
collector.add(def.type());
isUnionOfStringLiterals && defaultUnionType.type() instanceof StringLiteralTypeContext;
collector.add(defaultUnionType.type());
} else {
isUnionOfStringLiterals =
isUnionOfStringLiterals && current instanceof StringLiteralTypeContext;
@@ -2735,7 +2707,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
}
var tokens = lastPart.ts;
assert tokens.size() >= 1;
assert !tokens.isEmpty();
var lastToken = tokens.get(tokens.size() - 1);
if (lastToken.getType() == PklLexer.MLNewline) {
@@ -2759,13 +2731,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
var text = token.getText();
for (var i = 0; i < text.length(); i++) {
switch (text.charAt(i)) {
case ' ':
case '\t':
continue;
default:
return false;
}
var ch = text.charAt(i);
if (ch != ' ' && ch != '\t') return false;
}
return true;
@@ -2775,12 +2742,9 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
var text = token.getText();
for (var i = 0; i < text.length(); i++) {
switch (text.charAt(i)) {
case ' ':
case '\t':
continue;
default:
return text.substring(0, i);
var ch = text.charAt(i);
if (ch != ' ' && ch != '\t') {
return text.substring(0, i);
}
}
@@ -2829,11 +2793,11 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
Token token = tokens.get(i);
switch (token.getType()) {
case PklLexer.MLNewline:
case PklLexer.MLNewline -> {
builder.append('\n');
isLineStart = true;
break;
case PklLexer.MLCharacters:
}
case PklLexer.MLCharacters -> {
var text = token.getText();
if (isLineStart) {
if (text.startsWith(commonIndent)) {
@@ -2852,8 +2816,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
builder.append(text);
}
isLineStart = false;
break;
case PklLexer.MLCharacterEscape:
}
case PklLexer.MLCharacterEscape -> {
if (isLineStart && !commonIndent.isEmpty()) {
throw exceptionBuilder()
.evalError("stringIndentationMustMatchLastLine")
@@ -2862,8 +2826,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
}
builder.append(parseCharacterEscapeSequence(token));
isLineStart = false;
break;
case PklLexer.MLUnicodeEscape:
}
case PklLexer.MLUnicodeEscape -> {
if (isLineStart && !commonIndent.isEmpty()) {
throw exceptionBuilder()
.evalError("stringIndentationMustMatchLastLine")
@@ -2872,9 +2836,8 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
}
builder.appendCodePoint(parseUnicodeEscapeSequence(token));
isLineStart = false;
break;
default:
throw exceptionBuilder().unreachableCode().build();
}
default -> throw exceptionBuilder().unreachableCode().build();
}
}
@@ -2883,26 +2846,28 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
private ResolveDeclaredTypeNode doVisitTypeName(QualifiedIdentifierContext ctx) {
var tokens = ctx.ts;
switch (tokens.size()) {
case 1:
return switch (tokens.size()) {
case 1 -> {
var token = tokens.get(0);
return new ResolveSimpleDeclaredTypeNode(
yield new ResolveSimpleDeclaredTypeNode(
createSourceSection(token), Identifier.get(token.getText()), isBaseModule);
case 2:
}
case 2 -> {
var token1 = tokens.get(0);
var token2 = tokens.get(1);
return new ResolveQualifiedDeclaredTypeNode(
yield new ResolveQualifiedDeclaredTypeNode(
createSourceSection(ctx),
createSourceSection(token1),
createSourceSection(token2),
Identifier.localProperty(token1.getText()),
Identifier.get(token2.getText()));
default:
throw exceptionBuilder()
.evalError("invalidTypeName", ctx.getText())
.withSourceSection(createSourceSection(ctx))
.build();
}
}
default ->
throw exceptionBuilder()
.evalError("invalidTypeName", ctx.getText())
.withSourceSection(createSourceSection(ctx))
.build();
};
}
private void checkCommaSeparatedElements(
@@ -2918,11 +2883,11 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
var index = elements.indexOf(child);
if (index > 0) { // 0 rather than -1 because no separator is expected before first element
assert prevChild != null;
if (!(prevChild instanceof TerminalNode)
|| !separators.contains(((TerminalNode) prevChild).getSymbol())) {
if (!(prevChild instanceof TerminalNode terminalNode)
|| !separators.contains(terminalNode.getSymbol())) {
var prevToken =
prevChild instanceof TerminalNode
? ((TerminalNode) prevChild).getSymbol()
prevChild instanceof TerminalNode terminalNode
? terminalNode.getSymbol()
: ((ParserRuleContext) prevChild).getStop();
throw exceptionBuilder()
.evalError("missingCommaSeparator")

View File

@@ -93,11 +93,10 @@ public class ImportsAndReadsParser
@Override
public List<Pair<String, SourceSection>> visitReadExpr(ReadExprContext ctx) {
var expr = ctx.expr();
if (!(expr instanceof SingleLineStringLiteralContext)) {
if (!(expr instanceof SingleLineStringLiteralContext slCtx)) {
return Collections.emptyList();
}
// best-effort approach; only collect read expressions that are string constants.
var slCtx = (SingleLineStringLiteralContext) expr;
var singleParts = slCtx.singleLineStringPart();
String importString;
if (singleParts.isEmpty()) {

View File

@@ -284,8 +284,8 @@ public final class SymbolTable {
}
private String getNextEntryName(@Nullable ExpressionNode keyNode) {
if (keyNode instanceof ConstantNode) {
var value = ((ConstantNode) keyNode).getValue();
if (keyNode instanceof ConstantNode constantNode) {
var value = constantNode.getValue();
if (value instanceof String) {
return "[\"" + value + "\"]";
}

View File

@@ -90,7 +90,7 @@ public abstract class EqualNode extends ExpressionNode {
protected static @Nullable Class<? extends VmValue> getVmValueJavaClassOrNull(Object value) {
// OK to perform slow cast here (not a guard)
return value instanceof VmValue ? ((VmValue) value).getClass() : null;
return value instanceof VmValue vmValue ? vmValue.getClass() : null;
}
// covers all remaining cases (else it's a bug)

View File

@@ -90,7 +90,7 @@ public abstract class NotEqualNode extends ExpressionNode {
protected static @Nullable Class<? extends VmValue> getVmValueJavaClassOrNull(Object value) {
// OK to perform slow cast here (not a guard)
return value instanceof VmValue ? ((VmValue) value).getClass() : null;
return value instanceof VmValue vmValue ? vmValue.getClass() : null;
}
// covers all remaining cases (else it's a bug)

View File

@@ -161,7 +161,7 @@ public abstract class GeneratorObjectLiteralNode extends ObjectLiteralNode {
@TruffleBoundary
protected void fallback(Object parent) {
VmUtils.checkIsInstantiable(
parent instanceof VmClass ? (VmClass) parent : VmUtils.getClass(parent), getParentNode());
parent instanceof VmClass vmClass ? vmClass : VmUtils.getClass(parent), getParentNode());
throw exceptionBuilder().unreachableCode().build();
}

View File

@@ -167,7 +167,7 @@ public abstract class GeneratorSpreadNode extends GeneratorMemberNode {
.evalError("cannotIterateOverThisValue", VmUtils.getClass(iterable))
.withLocation(iterableNode)
.withProgramValue("Value", iterable);
if (iterable instanceof VmObject && ((VmObject) iterable).isTyped()) {
if (iterable instanceof VmObject vmObject && vmObject.isTyped()) {
builder.withHint(
"`Typed` values are not iterable. If you mean to spread its members, convert it to `Dynamic` using `toDynamic()`.");
}

View File

@@ -187,7 +187,7 @@ public final class AmendFunctionNode extends PklNode {
System.arraycopy(frameArguments, 2, arguments, 2, frameArguments.length - 2);
var valueToAmend = callNode.call(functionToAmend.getCallTarget(), arguments);
if (!(valueToAmend instanceof VmFunction)) {
if (!(valueToAmend instanceof VmFunction newFunctionToAmend)) {
var materializedFrame = context.frame;
if (materializedFrame != null) {
for (var slot : parameterSlots) {
@@ -199,7 +199,6 @@ public final class AmendFunctionNode extends PklNode {
return amendObjectNode.executeGeneric(frame);
}
var newFunctionToAmend = (VmFunction) valueToAmend;
return currentFunction.copy(
newFunctionToAmend.getParameterCount(),
nextFunctionRootNode,

View File

@@ -70,7 +70,7 @@ public abstract class SpecializedObjectLiteralNode extends ObjectLiteralNode {
@TruffleBoundary
@Idempotent
protected boolean checkIsValidTypedAmendment(Object parent) {
var parentClass = parent instanceof VmClass ? (VmClass) parent : VmUtils.getClass(parent);
var parentClass = parent instanceof VmClass vmClass ? vmClass : VmUtils.getClass(parent);
VmUtils.checkIsInstantiable(parentClass, getParentNode());
for (var member : EconomicMaps.getValues(members)) {

View File

@@ -92,7 +92,7 @@ public abstract class ReadPropertyNode extends ExpressionNode {
protected static @Nullable Class<? extends VmObjectLike> getVmObjectSubclassOrNull(Object value) {
// OK to perform slow cast here (not a guard)
return value instanceof VmObjectLike ? ((VmObjectLike) value).getClass() : null;
return value instanceof VmObjectLike objectLike ? objectLike.getClass() : null;
}
protected ClassProperty resolveProperty(Object value) {

View File

@@ -168,15 +168,12 @@ public final class ResolveMethodNode extends ExpressionNode {
return;
}
var memberIsOutsideConstScope = levelsUp > constDepth;
var invalid = false;
switch (constLevel) {
case ALL:
invalid = memberIsOutsideConstScope && !method.isConst();
break;
case MODULE:
invalid = currOwner.isModuleObject() && !method.isConst();
break;
}
var invalid =
switch (constLevel) {
case ALL -> memberIsOutsideConstScope && !method.isConst();
case MODULE -> currOwner.isModuleObject() && !method.isConst();
default -> false;
};
if (invalid) {
throw exceptionBuilder().evalError("methodMustBeConst", methodName.toString()).build();
}

View File

@@ -226,15 +226,12 @@ public final class ResolveVariableNode extends ExpressionNode {
return;
}
var memberIsOutsideConstScope = levelsUp > constDepth;
var invalid = false;
switch (constLevel) {
case ALL:
invalid = memberIsOutsideConstScope && !member.isConst();
break;
case MODULE:
invalid = currOwner.isModuleObject() && !member.isConst();
break;
}
var invalid =
switch (constLevel) {
case ALL -> memberIsOutsideConstScope && !member.isConst();
case MODULE -> currOwner.isModuleObject() && !member.isConst();
default -> false;
};
if (invalid) {
throw exceptionBuilder().evalError("propertyMustBeConst", variableName.toString()).build();
}

View File

@@ -40,9 +40,9 @@ public final class TraceNode extends ExpressionNode {
@TruffleBoundary
private void doTrace(Object value, VmContext context) {
if (value instanceof VmObjectLike) {
if (value instanceof VmObjectLike objectLike) {
try {
((VmObjectLike) value).force(true, true);
objectLike.force(true, true);
} catch (VmException ignored) {
}
}

View File

@@ -39,7 +39,7 @@ public abstract class ApplyVmFunction1Node extends ExpressionNode {
public final boolean executeBoolean(VmFunction function, Object arg1) {
var result = execute(function, arg1);
if (result instanceof Boolean) return (Boolean) result;
if (result instanceof Boolean b) return b;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getBooleanClass()).build();
@@ -47,7 +47,7 @@ public abstract class ApplyVmFunction1Node extends ExpressionNode {
public final String executeString(VmFunction function, Object arg1) {
var result = execute(function, arg1);
if (result instanceof String) return (String) result;
if (result instanceof String string) return string;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getStringClass()).build();
@@ -55,7 +55,7 @@ public abstract class ApplyVmFunction1Node extends ExpressionNode {
public final Long executeInt(VmFunction function, Object arg1) {
var result = execute(function, arg1);
if (result instanceof Long) return (Long) result;
if (result instanceof Long l) return l;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getIntClass()).build();
@@ -63,7 +63,7 @@ public abstract class ApplyVmFunction1Node extends ExpressionNode {
public final VmCollection executeCollection(VmFunction function, Object arg1) {
var result = execute(function, arg1);
if (result instanceof VmCollection) return (VmCollection) result;
if (result instanceof VmCollection collection) return collection;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getCollectionClass()).build();

View File

@@ -29,7 +29,7 @@ public abstract class ApplyVmFunction2Node extends PklNode {
public final boolean executeBoolean(VmFunction function, Object arg1, Object arg2) {
var result = execute(function, arg1, arg2);
if (result instanceof Boolean) return (Boolean) result;
if (result instanceof Boolean b) return b;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getBooleanClass()).build();
@@ -37,7 +37,7 @@ public abstract class ApplyVmFunction2Node extends PklNode {
public final VmCollection executeCollection(VmFunction function, Object arg1, Object arg2) {
var result = execute(function, arg1, arg2);
if (result instanceof VmCollection) return (VmCollection) result;
if (result instanceof VmCollection collection) return collection;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getCollectionClass()).build();
@@ -45,7 +45,7 @@ public abstract class ApplyVmFunction2Node extends PklNode {
public final VmMap executeMap(VmFunction function, Object arg1, Object arg2) {
var result = execute(function, arg1, arg2);
if (result instanceof VmMap) return (VmMap) result;
if (result instanceof VmMap map) return map;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getMapClass()).build();
@@ -53,7 +53,7 @@ public abstract class ApplyVmFunction2Node extends PklNode {
public final Long executeInt(VmFunction function, Object arg1, Object arg2) {
var result = execute(function, arg1, arg2);
if (result instanceof Long) return (Long) result;
if (result instanceof Long l) return l;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getIntClass()).build();
@@ -61,9 +61,7 @@ public abstract class ApplyVmFunction2Node extends PklNode {
public final VmPair executePair(VmFunction function, Object arg1, Object arg2) {
var result = execute(function, arg1, arg2);
if (result instanceof VmPair) {
return (VmPair) result;
}
if (result instanceof VmPair pair) return pair;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder().typeMismatch(result, BaseModule.getPairClass()).build();

View File

@@ -54,8 +54,8 @@ public final class ModuleNode extends PklRootNode {
@Override
public Object execute(VirtualFrame frame) {
var module = executeBody(frame, moduleNode);
if (module instanceof VmClass) {
return ((VmClass) module).getPrototype();
if (module instanceof VmClass vmClass) {
return vmClass.getPrototype();
}
assert module instanceof VmTyped;

View File

@@ -106,8 +106,8 @@ public final class ObjectMember extends Member {
public @Nullable Object getLocalPropertyDefaultValue() {
assert isProp() && isLocal();
return getMemberNode() instanceof LocalTypedPropertyNode
? ((LocalTypedPropertyNode) getMemberNode()).getDefaultValue()
return getMemberNode() instanceof LocalTypedPropertyNode propertyNode
? propertyNode.getDefaultValue()
: VmDynamic.empty();
}

View File

@@ -97,7 +97,7 @@ public final class UnresolvedMethodNode extends UnresolvedClassMemberNode {
for (var annotation : annotations) {
if (annotation.getVmClass() == BaseModule.getDeprecatedClass()) {
var messageObj = VmUtils.readMemberOrNull(annotation, Identifier.MESSAGE);
deprecation = messageObj instanceof String ? (String) messageObj : "";
deprecation = messageObj instanceof String string ? string : "";
break;
}
}

View File

@@ -310,7 +310,7 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof VmTyped && ((VmTyped) value).getVmClass() == moduleClass) return;
if (value instanceof VmTyped typed && typed.getVmClass() == moduleClass) return;
throw typeMismatch(value, moduleClass);
}
@@ -346,8 +346,8 @@ public abstract class TypeNode extends PklNode {
public void execute(VirtualFrame frame, Object value) {
var moduleClass = ((VmTyped) getModuleNode.executeGeneric(frame)).getVmClass();
if (value instanceof VmTyped) {
var valueClass = ((VmTyped) value).getVmClass();
if (value instanceof VmTyped typed) {
var valueClass = typed.getVmClass();
if (moduleClass.isSuperclassOf(valueClass)) return;
}
@@ -465,7 +465,7 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof VmValue && clazz == ((VmValue) value).getVmClass()) return;
if (value instanceof VmValue vmValue && clazz == vmValue.getVmClass()) return;
throw typeMismatch(value, clazz);
}
@@ -1431,9 +1431,8 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof Long) {
var v = (long) value;
if ((v & mask) == v) return;
if (value instanceof Long l) {
if ((l & mask) == l) return;
throw new VmTypeMismatchException.Constraint(typeAlias.getConstraintSection(), value);
}
@@ -1465,9 +1464,8 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof Long) {
var v = (long) value;
if (v == (byte) v) return;
if (value instanceof Long l) {
if (l == l.byteValue()) return;
throw new VmTypeMismatchException.Constraint(
BaseModule.getInt8TypeAlias().getConstraintSection(), value);
@@ -1500,9 +1498,8 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof Long) {
var v = (long) value;
if (v == (short) v) return;
if (value instanceof Long l) {
if (l == l.shortValue()) return;
throw new VmTypeMismatchException.Constraint(
BaseModule.getInt16TypeAlias().getConstraintSection(), value);
@@ -1535,9 +1532,8 @@ public abstract class TypeNode extends PklNode {
@Override
public void execute(VirtualFrame frame, Object value) {
if (value instanceof Long) {
var v = (long) value;
if (v == (int) v) return;
if (value instanceof Long l) {
if (l == l.intValue()) return;
throw new VmTypeMismatchException.Constraint(
BaseModule.getInt32TypeAlias().getConstraintSection(), value);
@@ -1836,21 +1832,21 @@ public abstract class TypeNode extends PklNode {
@Override
public void executeAndSet(VirtualFrame frame, Object value) {
var kind = frame.getFrameDescriptor().getSlotKind(slot);
if (value instanceof Long) {
if (value instanceof Long l) {
if (kind == FrameSlotKind.Double || kind == FrameSlotKind.Object) {
frame.getFrameDescriptor().setSlotKind(slot, FrameSlotKind.Object);
frame.setObject(slot, value);
frame.setObject(slot, l);
} else {
frame.getFrameDescriptor().setSlotKind(slot, FrameSlotKind.Long);
frame.setLong(slot, (long) value);
frame.setLong(slot, l);
}
} else if (value instanceof Double) {
} else if (value instanceof Double d) {
if (kind == FrameSlotKind.Long || kind == FrameSlotKind.Object) {
frame.getFrameDescriptor().setSlotKind(slot, FrameSlotKind.Object);
frame.setObject(slot, value);
frame.setObject(slot, d);
} else {
frame.getFrameDescriptor().setSlotKind(slot, FrameSlotKind.Double);
frame.setDouble(slot, (double) value);
frame.setDouble(slot, d);
}
} else {
throw typeMismatch(value, BaseModule.getNumberClass());

View File

@@ -133,9 +133,7 @@ public abstract class UnresolvedTypeNode extends PklNode {
var type = resolveTypeNode.executeGeneric(frame);
if (type instanceof VmClass) {
VmClass clazz = (VmClass) type;
if (type instanceof VmClass clazz) {
// Note: FinalClassTypeNode and NonFinalClassTypeNode assume that
// String/Boolean/Int/Float and their supertypes are handled separately.
@@ -163,9 +161,7 @@ public abstract class UnresolvedTypeNode extends PklNode {
return TypeNode.forClass(sourceSection, clazz);
}
if (type instanceof VmTypeAlias) {
var alias = (VmTypeAlias) type;
if (type instanceof VmTypeAlias alias) {
if (alias.getModuleName().equals("pkl.base")) {
switch (alias.getSimpleName()) {
case "NonNull":
@@ -219,8 +215,7 @@ public abstract class UnresolvedTypeNode extends PklNode {
var baseType = resolveTypeNode.executeGeneric(frame);
if (baseType instanceof VmClass) {
var clazz = (VmClass) baseType;
if (baseType instanceof VmClass clazz) {
checkNumberOfTypeArguments(clazz);
if (clazz.isCollectionClass()) {
@@ -289,8 +284,7 @@ public abstract class UnresolvedTypeNode extends PklNode {
.build();
}
if (baseType instanceof VmTypeAlias) {
var typeAlias = (VmTypeAlias) baseType;
if (baseType instanceof VmTypeAlias typeAlias) {
var argLength = typeArgumentNodes.length;
var resolvedTypeArgumentNodes = new TypeNode[argLength];
for (var i = 0; i < argLength; i++) {

View File

@@ -66,9 +66,9 @@ public abstract class VmTypeMismatchException extends ControlFlowException {
public void describe(StringBuilder builder, String indent) {
String renderedType;
var valueFormatter = ValueFormatter.basic();
if (expectedType instanceof String) {
if (expectedType instanceof String string) {
// string literal type
renderedType = valueFormatter.formatStringValue((String) expectedType, "");
renderedType = valueFormatter.formatStringValue(string, "");
} else if (expectedType instanceof Set) {
// union of string literal types
@SuppressWarnings("unchecked")
@@ -90,10 +90,9 @@ public abstract class VmTypeMismatchException extends ControlFlowException {
}
// give better error than "expected foo.Bar, but got foo.Bar" in case of naming conflict
if (actualValue instanceof VmTyped && expectedType instanceof VmClass) {
var actualObj = (VmTyped) actualValue;
if (actualValue instanceof VmTyped actualObj
&& expectedType instanceof VmClass expectedClass) {
var actualClass = actualObj.getVmClass();
var expectedClass = (VmClass) expectedType;
if (actualClass.getQualifiedName().equals(expectedClass.getQualifiedName())) {
var actualModuleUri = actualClass.getModule().getModuleInfo().getModuleKey().getUri();
var expectedModuleUri = expectedClass.getModule().getModuleInfo().getModuleKey().getUri();

View File

@@ -90,14 +90,9 @@ final class RequestRewritingClient implements HttpClient {
publisher -> builder.method(method, publisher),
() -> {
switch (method) {
case "GET":
builder.GET();
break;
case "DELETE":
builder.DELETE();
break;
default:
builder.method(method, HttpRequest.BodyPublishers.noBody());
case "GET" -> builder.GET();
case "DELETE" -> builder.DELETE();
default -> builder.method(method, HttpRequest.BodyPublishers.noBody());
}
});

View File

@@ -673,11 +673,11 @@ public final class ModuleKeys {
}
private @Nullable Path getLocalPath(Dependency dependency) {
if (!(dependency instanceof LocalDependency)) {
if (!(dependency instanceof LocalDependency localDependency)) {
return null;
}
return ((LocalDependency) dependency)
.resolveAssetPath(getProjectDepsResolver().getProjectDir(), packageAssetUri);
return localDependency.resolveAssetPath(
getProjectDepsResolver().getProjectDir(), packageAssetUri);
}
@Override

View File

@@ -64,15 +64,10 @@ public class PathElement {
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PathElement)) {
return false;
}
PathElement that = (PathElement) o;
return isDirectory == that.isDirectory && name.equals(that.name);
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof PathElement other)) return false;
return isDirectory == other.isDirectory && name.equals(other.name);
}
@Override

View File

@@ -107,20 +107,18 @@ public class DependencyMetadata {
private static Map<String, RemoteDependency> parseDependencies(Object deps)
throws JsonParseException {
if (!(deps instanceof JsObject)) {
if (!(deps instanceof JsObject dependencies)) {
throw new FormatException("object", deps.getClass());
}
var dependencies = (JsObject) deps;
var ret = new HashMap<String, RemoteDependency>(dependencies.size());
for (var key : dependencies.keySet()) {
var remoteDependency =
dependencies.get(
key,
(dep) -> {
if (!(dep instanceof JsObject)) {
if (!(dep instanceof JsObject obj)) {
throw new FormatException("object", dep.getClass());
}
var obj = (JsObject) dep;
var checksums = obj.get("checksums", DependencyMetadata::parseChecksums);
var packageUri = obj.get("uri", PackageUtils::parsePackageUriWithoutChecksums);
return new RemoteDependency(packageUri, checksums);
@@ -131,25 +129,23 @@ public class DependencyMetadata {
}
public static Checksums parseChecksums(Object obj) throws JsonParseException {
if (!(obj instanceof JsObject)) {
if (!(obj instanceof JsObject jsObj)) {
throw new FormatException("object", obj.getClass());
}
var jsObj = (JsObject) obj;
var sha256 = jsObj.getString("sha256");
return new Checksums(sha256);
}
public static List<String> parseAuthors(Object obj) throws JsonParseException {
if (!(obj instanceof JsArray)) {
if (!(obj instanceof JsArray arr)) {
throw new FormatException("array", obj.getClass());
}
var arr = (JsArray) obj;
var ret = new ArrayList<String>(arr.size());
for (var elem : arr) {
if (!(elem instanceof String)) {
if (!(elem instanceof String string)) {
throw new FormatException("string", elem.getClass());
}
ret.add((String) elem);
ret.add(string);
}
return ret;
}

View File

@@ -23,10 +23,10 @@ import org.pkl.core.util.json.Json.JsonParseException;
public class PackageUtils {
public static PackageUri parsePackageUriWithoutChecksums(Object obj)
throws JsonParseException, URISyntaxException {
if (!(obj instanceof String)) {
if (!(obj instanceof String string)) {
throw new FormatException("string", obj.getClass());
}
var packageUri = new PackageUri((String) obj);
var packageUri = new PackageUri(string);
checkHasNoChecksumComponent(packageUri);
return packageUri;
}

View File

@@ -125,48 +125,48 @@ public class Parser {
var curr = ctx.getChild(ctx.getChildCount() - 2); // last child before EOF
while (curr.getChildCount() > 0) {
if (curr instanceof ClassBodyContext) {
if (((ClassBodyContext) curr).err == null) throw incompleteInput(curr, "}");
if (curr instanceof ClassBodyContext classBody) {
if (classBody.err == null) throw incompleteInput(curr, "}");
else return;
}
if (curr instanceof ParameterListContext) {
if (((ParameterListContext) curr).err == null) throw incompleteInput(curr, ")");
if (curr instanceof ParameterListContext parameterList) {
if (parameterList.err == null) throw incompleteInput(curr, ")");
else return;
}
if (curr instanceof ArgumentListContext) {
if (((ArgumentListContext) curr).err == null) throw incompleteInput(curr, ")");
if (curr instanceof ArgumentListContext argumentList) {
if (argumentList.err == null) throw incompleteInput(curr, ")");
else return;
}
if (curr instanceof TypeParameterListContext) {
if (((TypeParameterListContext) curr).err == null) throw incompleteInput(curr, ">");
if (curr instanceof TypeParameterListContext typeParameterList) {
if (typeParameterList.err == null) throw incompleteInput(curr, ">");
else return;
}
if (curr instanceof TypeArgumentListContext) {
if (((TypeArgumentListContext) curr).err == null) throw incompleteInput(curr, ">");
if (curr instanceof TypeArgumentListContext typeArgumentList) {
if (typeArgumentList.err == null) throw incompleteInput(curr, ">");
else return;
}
if (curr instanceof ParenthesizedTypeContext) {
if (((ParenthesizedTypeContext) curr).err == null) throw incompleteInput(curr, ")");
if (curr instanceof ParenthesizedTypeContext parenthesizedType) {
if (parenthesizedType.err == null) throw incompleteInput(curr, ")");
else return;
}
if (curr instanceof ConstrainedTypeContext) {
if (((ConstrainedTypeContext) curr).err == null) throw incompleteInput(curr, ")");
if (curr instanceof ConstrainedTypeContext constrainedType) {
if (constrainedType.err == null) throw incompleteInput(curr, ")");
else return;
}
if (curr instanceof ParenthesizedExprContext) {
if (((ParenthesizedExprContext) curr).err == null) throw incompleteInput(curr, ")");
if (curr instanceof ParenthesizedExprContext parenthesizedExpr) {
if (parenthesizedExpr.err == null) throw incompleteInput(curr, ")");
else return;
}
if (curr instanceof SuperSubscriptExprContext) {
if (((SuperSubscriptExprContext) curr).err == null) throw incompleteInput(curr, "]");
if (curr instanceof SuperSubscriptExprContext superSubscriptExpr) {
if (superSubscriptExpr.err == null) throw incompleteInput(curr, "]");
else return;
}
if (curr instanceof SubscriptExprContext) {
if (((SubscriptExprContext) curr).err == null) throw incompleteInput(curr, "]");
if (curr instanceof SubscriptExprContext subscriptExpr) {
if (subscriptExpr.err == null) throw incompleteInput(curr, "]");
else return;
}
if (curr instanceof ObjectBodyContext) {
if (((ObjectBodyContext) curr).err == null) throw incompleteInput(curr, "}");
if (curr instanceof ObjectBodyContext objectBody) {
if (objectBody.err == null) throw incompleteInput(curr, "}");
else return;
}
curr = curr.getChild(curr.getChildCount() - 1);

View File

@@ -131,8 +131,8 @@ public final class Project {
PackageUtils.checkHasNoChecksumComponent(packageUri);
var objChecksum = object.getProperty("checksums");
Checksums checksums = null;
if (objChecksum instanceof PObject) {
var sha256 = (String) ((PObject) objChecksum).get("sha256");
if (objChecksum instanceof PObject pObject) {
var sha256 = (String) pObject.get("sha256");
assert sha256 != null;
checksums = new Checksums(sha256);
}

View File

@@ -99,10 +99,9 @@ public class ProjectDeps {
private static EconomicMap<CanonicalPackageUri, Dependency> parseResolvedDependencies(
Object object) throws JsonParseException, URISyntaxException {
if (!(object instanceof JsObject)) {
if (!(object instanceof JsObject jsObj)) {
throw new FormatException("resolvedDependencies", "object", object.getClass());
}
var jsObj = (JsObject) object;
var ret = EconomicMaps.<CanonicalPackageUri, Dependency>create(jsObj.size());
for (var entry : jsObj.entrySet()) {
Dependency resolvedDependency = parseResolvedDependency(entry);
@@ -115,10 +114,9 @@ public class ProjectDeps {
private static Dependency parseResolvedDependency(Entry<String, Object> entry)
throws JsonParseException {
var input = entry.getValue();
if (!(input instanceof JsObject)) {
if (!(input instanceof JsObject obj)) {
throw new VmExceptionBuilder().evalError("invalid object").build();
}
var obj = (JsObject) input;
var type = obj.getString("type");
var uri = obj.get("uri", PackageUtils::parsePackageUriWithoutChecksums);
if (type.equals("remote")) {
@@ -211,8 +209,8 @@ public class ProjectDeps {
while (cursor.advance()) {
jsonWriter.name(cursor.getKey().toString());
var dependency = cursor.getValue();
if (dependency instanceof LocalDependency) {
writeLocalDependency((LocalDependency) dependency);
if (dependency instanceof LocalDependency localDependency) {
writeLocalDependency(localDependency);
} else {
writeRemoteDependency((RemoteDependency) dependency);
}

View File

@@ -116,16 +116,16 @@ public class ReplServer implements AutoCloseable {
public List<ReplResponse> handleRequest(ReplRequest request) {
polyglotContext.enter();
try {
if (request instanceof Eval) {
return handleEval((Eval) request);
if (request instanceof Eval eval) {
return handleEval(eval);
}
if (request instanceof Load) {
return handleLoad((Load) request);
if (request instanceof Load load) {
return handleLoad(load);
}
if (request instanceof ReplRequest.Completion) {
return handleCompletion((ReplRequest.Completion) request);
if (request instanceof ReplRequest.Completion completion) {
return handleCompletion(completion);
}
if (request instanceof Reset) {
@@ -157,8 +157,8 @@ public class ReplServer implements AutoCloseable {
return results.stream()
.map(
result ->
result instanceof ReplResponse
? (ReplResponse) result
result instanceof ReplResponse response
? response
: new EvalSuccess(render(result)))
.collect(Collectors.toList());
}
@@ -210,20 +210,20 @@ public class ReplServer implements AutoCloseable {
if (tree instanceof ExprContext) {
var exprNode = (ExpressionNode) tree.accept(builder);
evaluateExpr(replState, exprNode, forceResults, results);
} else if (tree instanceof ImportClauseContext) {
addStaticModuleProperty(builder.visitImportClause((ImportClauseContext) tree));
} else if (tree instanceof ClassPropertyContext) {
var propertyNode = builder.visitClassProperty((ClassPropertyContext) tree);
} else if (tree instanceof ImportClauseContext importClause) {
addStaticModuleProperty(builder.visitImportClause(importClause));
} else if (tree instanceof ClassPropertyContext classProperty) {
var propertyNode = builder.visitClassProperty(classProperty);
var property = addModuleProperty(propertyNode);
if (evalDefinitions) {
evaluateMemberDef(replState, property, forceResults, results);
}
} else if (tree instanceof ClazzContext) {
addStaticModuleProperty(builder.visitClazz((ClazzContext) tree));
} else if (tree instanceof TypeAliasContext) {
addStaticModuleProperty(builder.visitTypeAlias((TypeAliasContext) tree));
} else if (tree instanceof ClassMethodContext) {
addModuleMethodDef(builder.visitClassMethod((ClassMethodContext) tree));
} else if (tree instanceof ClazzContext clazz) {
addStaticModuleProperty(builder.visitClazz(clazz));
} else if (tree instanceof TypeAliasContext typeAlias) {
addStaticModuleProperty(builder.visitTypeAlias(typeAlias));
} else if (tree instanceof ClassMethodContext classMethod) {
addModuleMethodDef(builder.visitClassMethod(classMethod));
} else if (tree instanceof ModuleDeclContext) {
// do nothing for now
} else if (tree instanceof TerminalNode && tree.toString().equals(",")) {
@@ -360,8 +360,8 @@ public class ReplServer implements AutoCloseable {
assert !(lastResult instanceof ReplResponse);
VmObjectLike composite;
if (lastResult instanceof VmObjectLike) {
composite = (VmObjectLike) lastResult;
if (lastResult instanceof VmObjectLike objectLike) {
composite = objectLike;
} else {
composite = VmUtils.getClass(lastResult).getPrototype();
}

View File

@@ -556,11 +556,11 @@ public final class ResourceReaders {
}
private @Nullable Path getLocalPath(Dependency dependency, PackageAssetUri packageAssetUri) {
if (!(dependency instanceof LocalDependency)) {
if (!(dependency instanceof LocalDependency localDependency)) {
return null;
}
return ((LocalDependency) dependency)
.resolveAssetPath(getProjectDepsResolver().getProjectDir(), packageAssetUri);
return localDependency.resolveAssetPath(
getProjectDepsResolver().getProjectDir(), packageAssetUri);
}
}

View File

@@ -136,24 +136,19 @@ public final class BaseModule extends StdLibModule {
}
public static VmClass getFunctionNClass(int paramCount) {
switch (paramCount) {
case 0:
return getFunction0Class();
case 1:
return getFunction1Class();
case 2:
return getFunction2Class();
case 3:
return getFunction3Class();
case 4:
return getFunction4Class();
case 5:
return getFunction5Class();
default:
return switch (paramCount) {
case 0 -> getFunction0Class();
case 1 -> getFunction1Class();
case 2 -> getFunction2Class();
case 3 -> getFunction3Class();
case 4 -> getFunction4Class();
case 5 -> getFunction5Class();
default -> {
CompilerDirectives.transferToInterpreter();
throw new IllegalArgumentException(
String.format("Class `Function%d` does not exist.", paramCount));
}
}
};
}
public static VmClass getFunction0Class() {

View File

@@ -33,8 +33,7 @@ public class KeyLookupSuggestions {
map.forEach(
entry -> {
if (!(entry.getKey() instanceof String)) return;
var entryKey = (String) entry.getKey();
if (!(entry.getKey() instanceof String entryKey)) return;
var similarity = STRING_SIMILARITY.similarity(entryKey, key);
if (similarity >= SIMILARITY_THRESHOLD) {
candidates.add(new Candidate(entryKey, similarity));
@@ -50,8 +49,7 @@ public class KeyLookupSuggestions {
object.iterateMemberValues(
(memberKey, member, value) -> {
if (!(memberKey instanceof String)) return true;
var stringKey = (String) memberKey;
if (!(memberKey instanceof String stringKey)) return true;
var similarity = STRING_SIMILARITY.similarity(stringKey, key);
if (similarity >= SIMILARITY_THRESHOLD) {
candidates.add(new Candidate(stringKey, similarity));
@@ -80,7 +78,7 @@ public class KeyLookupSuggestions {
@Override
public boolean equals(@Nullable Object obj) {
return (obj instanceof Candidate && ((Candidate) obj).key.equals(key));
return (obj instanceof Candidate candidate && candidate.key.equals(key));
}
@Override

View File

@@ -144,9 +144,7 @@ public class MemberLookupSuggestions {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Candidate)) return false;
var other = (Candidate) obj;
if (!(obj instanceof Candidate other)) return false;
// member lookup is name rather than signature based (but distinguishes kind)
return kind == other.kind && name.equals(other.name);
}

View File

@@ -45,9 +45,9 @@ final class MinPklVersionChecker {
}
static void check(String moduleName, @Nullable ParserRuleContext ctx, @Nullable Node importNode) {
if (!(ctx instanceof ModuleContext)) return;
if (!(ctx instanceof ModuleContext moduleCtx)) return;
var moduleDeclCtx = ((ModuleContext) ctx).moduleDecl();
var moduleDeclCtx = moduleCtx.moduleDecl();
if (moduleDeclCtx == null) return;
for (var annCtx : moduleDeclCtx.annotation()) {
@@ -57,9 +57,8 @@ final class MinPklVersionChecker {
if (objectBodyCtx == null) continue;
for (var memberCtx : objectBodyCtx.objectMember()) {
if (!(memberCtx instanceof ObjectPropertyContext)) continue;
if (!(memberCtx instanceof ObjectPropertyContext propertyCtx)) continue;
var propertyCtx = (ObjectPropertyContext) memberCtx;
if (!Identifier.MIN_PKL_VERSION.toString().equals(getText(propertyCtx.Identifier())))
continue;
@@ -84,8 +83,7 @@ final class MinPklVersionChecker {
}
private static @Nullable String getLastIdText(@Nullable TypeContext typeCtx) {
if (!(typeCtx instanceof DeclaredTypeContext)) return null;
var declCtx = (DeclaredTypeContext) typeCtx;
if (!(typeCtx instanceof DeclaredTypeContext declCtx)) return null;
var token = declCtx.qualifiedIdentifier().Identifier;
return token == null ? null : token.getText();
}

View File

@@ -203,16 +203,12 @@ public final class MirrorFactories {
.addStringProperty("name", TypeParameter::getName)
.addProperty(
"variance",
typeParameter -> {
switch (typeParameter.getVariance()) {
case COVARIANT:
return "out";
case CONTRAVARIANT:
return "in";
default:
return VmNull.withoutDefault();
}
});
typeParameter ->
switch (typeParameter.getVariance()) {
case COVARIANT -> "out";
case CONTRAVARIANT -> "in";
default -> VmNull.withoutDefault();
});
classTypeFactory
.addTypedProperty(

View File

@@ -135,7 +135,7 @@ public final class ModuleCache {
var module1 = modulesByOriginalUri.get(moduleKey.getUri());
if (module1 != null) {
if (module1 instanceof VmTyped) return (VmTyped) module1;
if (module1 instanceof VmTyped typed) return typed;
assert module1 instanceof RuntimeException;
// would be more accurate/safe to throw a clone with adapted Pkl stack trace
@@ -145,7 +145,7 @@ public final class ModuleCache {
var resolvedKey = resolve(moduleKey, securityManager, importNode);
var module2 = modulesByResolvedUri.get(resolvedKey.getUri());
if (module2 != null) {
if (module2 instanceof VmTyped) return (VmTyped) module2;
if (module2 instanceof VmTyped typed) return typed;
assert module2 instanceof RuntimeException;
// would be more accurate/safe to throw a clone with adapted Pkl stack trace

View File

@@ -160,8 +160,8 @@ public final class ResourceManager {
var res = resource.get();
if (res instanceof String) return resource;
if (res instanceof Resource) {
return Optional.of(resourceFactory.create((Resource) res));
if (res instanceof Resource r) {
return Optional.of(resourceFactory.create(r));
}
throw new VmExceptionBuilder()

View File

@@ -66,12 +66,12 @@ class StackTraceGenerator {
for (Node current = callNode; current != null; current = current.getParent()) {
if (current.getSourceSection() != null) {
return current instanceof MemberNode
return current instanceof MemberNode memberNode
// Always display the member body's source section instead of the member
// (root) node's source section (which includes doc comment etc.), even
// if `callNode` is a child of root node rather than body node.
// This improves stack trace output for failed property type checks.
? ((MemberNode) current).getBodySection()
? memberNode.getBodySection()
: current.getSourceSection();
}
}

View File

@@ -41,8 +41,7 @@ public class StackTraceRenderer {
String leftMargin,
boolean isFirstElement) {
for (var frame : frames) {
if (frame instanceof StackFrameLoop) {
var loop = (StackFrameLoop) frame;
if (frame instanceof StackFrameLoop loop) {
// ensure a cycle of length 1 doesn't get rendered as a loop
if (loop.count == 1) {
doRender(loop.frames, null, builder, leftMargin, isFirstElement);

View File

@@ -129,10 +129,9 @@ public abstract class VmCollection extends VmValue implements Iterable<Object> {
public final VmCollection flatten() {
var builder = builder();
for (var elem : this) {
if (elem instanceof Iterable) {
builder.addAll((Iterable<?>) elem);
} else if (elem instanceof VmListing) {
var listing = (VmListing) elem;
if (elem instanceof Iterable<?> iterable) {
builder.addAll(iterable);
} else if (elem instanceof VmListing listing) {
listing.forceAndIterateMemberValues(
(key, member, value) -> {
builder.add(value);

View File

@@ -144,9 +144,7 @@ public final class VmDataSize extends VmValue implements Comparable<VmDataSize>
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmDataSize)) return false;
var other = (VmDataSize) obj;
if (!(obj instanceof VmDataSize other)) return false;
// converting to a fixed unit guarantees that equals() is commutative and consistent with
// hashCode()
return convertValueTo(DataSizeUnit.BYTES) == other.convertValueTo(DataSizeUnit.BYTES);

View File

@@ -140,9 +140,7 @@ public final class VmDuration extends VmValue implements Comparable<VmDuration>
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmDuration)) return false;
var other = (VmDuration) obj;
if (!(obj instanceof VmDuration other)) return false;
// converting to a fixed unit guarantees that equals() is commutative and consistent with
// hashCode()
return getValue(DurationUnit.NANOS) == other.getValue(DurationUnit.NANOS);

View File

@@ -101,9 +101,8 @@ public final class VmDynamic extends VmObject {
@TruffleBoundary
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmDynamic)) return false;
if (!(obj instanceof VmDynamic other)) return false;
var other = (VmDynamic) obj;
// could use shallow force, but deep force is cached
force(false);
other.force(false);

View File

@@ -127,11 +127,11 @@ public class VmExceptionBuilder {
}
public VmExceptionBuilder cannotFindMember(VmObjectLike receiver, Object memberKey) {
if (memberKey instanceof Identifier) {
return cannotFindProperty(receiver, (Identifier) memberKey, true, false);
if (memberKey instanceof Identifier identifier) {
return cannotFindProperty(receiver, identifier, true, false);
}
if (memberKey instanceof String) {
var candidates = KeyLookupSuggestions.forObject(receiver, (String) memberKey);
if (memberKey instanceof String string) {
var candidates = KeyLookupSuggestions.forObject(receiver, string);
if (!candidates.isEmpty()) {
return evalError(
"cannotFindKeyListCandidates",
@@ -245,8 +245,8 @@ public class VmExceptionBuilder {
}
public VmExceptionBuilder cannotFindKey(VmMap map, Object key) {
if (key instanceof String) {
var candidates = KeyLookupSuggestions.forMap(map, (String) key);
if (key instanceof String string) {
var candidates = KeyLookupSuggestions.forMap(map, string);
if (!candidates.isEmpty()) {
return evalError(
"cannotFindKeyListCandidates",
@@ -334,44 +334,42 @@ public class VmExceptionBuilder {
throw new IllegalStateException("No message set.");
}
switch (kind) {
case EVAL_ERROR:
return new VmEvalException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint);
case UNDEFINED_VALUE:
return new VmUndefinedValueException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint,
receiver);
case BUG:
return new VmBugException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint);
default:
throw unreachableCode().build();
}
return switch (kind) {
case EVAL_ERROR ->
new VmEvalException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint);
case UNDEFINED_VALUE ->
new VmUndefinedValueException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint,
receiver);
case BUG ->
new VmBugException(
message,
cause,
isExternalMessage,
messageArguments,
programValues,
location,
sourceSection,
memberName,
hint);
};
}
private List<Identifier> collectPropertyNames(VmObjectLike object, boolean isRead) {

View File

@@ -43,8 +43,8 @@ public class VmExceptionRenderer {
}
private void render(VmException exception, StringBuilder builder) {
if (exception instanceof VmBugException) {
renderBugException((VmBugException) exception, builder);
if (exception instanceof VmBugException bugException) {
renderBugException(bugException, builder);
} else {
renderException(exception, builder);
}

View File

@@ -60,7 +60,7 @@ public final class VmFunction extends VmObjectLike {
public String applyString(Object arg1) {
var result = apply(arg1);
if (result instanceof String) return (String) result;
if (result instanceof String string) return string;
CompilerDirectives.transferToInterpreter();
throw new VmExceptionBuilder().typeMismatch(result, BaseModule.getStringClass()).build();

View File

@@ -107,9 +107,7 @@ public final class VmIntSeq extends VmValue implements Iterable<Long> {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmIntSeq)) return false;
var other = (VmIntSeq) obj;
if (!(obj instanceof VmIntSeq other)) return false;
return isEmpty()
? other.isEmpty()
: start == other.start && last == other.last && step == other.step;

View File

@@ -424,8 +424,8 @@ public final class VmList extends VmCollection {
public boolean equals(@Nullable Object other) {
if (this == other) return true;
//noinspection SimplifiableIfStatement
if (!(other instanceof VmList)) return false;
return rrbt.equals(((VmList) other).rrbt);
if (!(other instanceof VmList list)) return false;
return rrbt.equals(list.rrbt);
}
@Override

View File

@@ -104,9 +104,8 @@ public final class VmListing extends VmObject {
@TruffleBoundary
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmListing)) return false;
if (!(obj instanceof VmListing other)) return false;
var other = (VmListing) obj;
if (length != other.length) return false;
// could use shallow force, but deep force is cached
force(false);

View File

@@ -245,8 +245,8 @@ public final class VmMap extends VmValue implements Iterable<Map.Entry<Object, O
public boolean equals(@Nullable Object other) {
if (this == other) return true;
//noinspection SimplifiableIfStatement
if (!(other instanceof VmMap)) return false;
return map.equals(((VmMap) other).map);
if (!(other instanceof VmMap vmMap)) return false;
return map.equals(vmMap.map);
}
@Override

View File

@@ -68,8 +68,7 @@ public final class VmMapping extends VmObject {
synchronized (this) {
if (__allKeys == null) {
// building upon parent's `getAllKeys()` should improve at least worst case efficiency
var parentKeys =
parent instanceof VmMapping ? ((VmMapping) parent).getAllKeys() : VmSet.EMPTY;
var parentKeys = parent instanceof VmMapping mapping ? mapping.getAllKeys() : VmSet.EMPTY;
var builder = VmSet.builder(parentKeys);
for (var cursor = members.getEntries(); cursor.advance(); ) {
var member = cursor.getValue();
@@ -127,9 +126,8 @@ public final class VmMapping extends VmObject {
@TruffleBoundary
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmMapping)) return false;
if (!(obj instanceof VmMapping other)) return false;
var other = (VmMapping) obj;
// could use shallow force, but deep force is cached
force(false);
other.force(false);

View File

@@ -54,14 +54,11 @@ public final class VmPair extends VmValue implements Iterable<Object> {
@Override
public Object next() {
switch (pos++) {
case 0:
return first;
case 1:
return second;
default:
throw new NoSuchElementException("VmPair only has two elements.");
}
return switch (pos++) {
case 0 -> first;
case 1 -> second;
default -> throw new NoSuchElementException("VmPair only has two elements.");
};
}
};
}
@@ -105,9 +102,7 @@ public final class VmPair extends VmValue implements Iterable<Object> {
@TruffleBoundary
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmPair)) return false;
var other = (VmPair) obj;
if (!(obj instanceof VmPair other)) return false;
return first.equals(other.first) && second.equals(other.second);
}

View File

@@ -67,9 +67,7 @@ public final class VmRegex extends VmValue {
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmRegex)) return false;
var other = (VmRegex) obj;
if (!(obj instanceof VmRegex other)) return false;
return pattern.pattern().equals(other.pattern.pattern());
}

View File

@@ -324,8 +324,8 @@ public final class VmSet extends VmCollection {
public boolean equals(@Nullable Object other) {
if (this == other) return true;
//noinspection SimplifiableIfStatement
if (!(other instanceof VmSet)) return false;
return set.equals(((VmSet) other).set);
if (!(other instanceof VmSet vmSet)) return false;
return set.equals(vmSet.set);
}
@Override

View File

@@ -98,8 +98,8 @@ public final class VmTypeAlias extends VmValue {
*/
@TruffleBoundary
public SourceSection getBaseTypeSection() {
if (typeNode instanceof ConstrainedTypeNode) {
return ((ConstrainedTypeNode) typeNode).getBaseTypeSection();
if (typeNode instanceof ConstrainedTypeNode constrainedTypeNode) {
return constrainedTypeNode.getBaseTypeSection();
}
throw new VmExceptionBuilder()
@@ -176,8 +176,7 @@ public final class VmTypeAlias extends VmValue {
clone.accept(
node -> {
if (node instanceof TypeVariableNode) {
var typeVarNode = (TypeVariableNode) node;
if (node instanceof TypeVariableNode typeVarNode) {
int index = typeVarNode.getTypeParameterIndex();
// should not need to clone type argument node because it is not used by its original
// root node

View File

@@ -177,9 +177,8 @@ public final class VmTyped extends VmObject {
@TruffleBoundary
public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof VmTyped)) return false;
if (!(obj instanceof VmTyped other)) return false;
var other = (VmTyped) obj;
if (clazz != other.clazz) return false;
// could use shallow force, but deep force is cached
force(false);

View File

@@ -60,11 +60,10 @@ public final class VmUndefinedValueException extends VmEvalException {
renderPath(builder, path);
builder.append('`');
path.pop();
if (topLevelValue instanceof VmTyped && ((VmTyped) topLevelValue).isModuleObject()) {
var modl = (VmTyped) topLevelValue;
if (topLevelValue instanceof VmTyped typed && typed.isModuleObject()) {
builder
.append(" of module `")
.append(modl.getModuleInfo().getModuleSchema(modl).getModuleUri())
.append(typed.getModuleInfo().getModuleSchema(typed).getModuleUri())
.append('`');
}
builder.append('.');

View File

@@ -233,7 +233,7 @@ public final class VmUtils {
@TruffleBoundary
public static @Nullable Object readMemberOrNull(
VmObjectLike receiver, Object memberKey, boolean checkType, IndirectCallNode callNode) {
assert (!(memberKey instanceof Identifier) || !((Identifier) memberKey).isLocalProp())
assert (!(memberKey instanceof Identifier identifier) || !identifier.isLocalProp())
: "Must use ReadLocalPropertyNode for local properties.";
final var cachedValue = receiver.getCachedValue(memberKey);
@@ -329,12 +329,12 @@ public final class VmUtils {
}
public static boolean isRenderDirective(Object value) {
return value instanceof VmTyped && isRenderDirective((VmTyped) value);
return value instanceof VmTyped typed && isRenderDirective(typed);
}
public static boolean isPcfRenderDirective(Object value) {
return value instanceof VmTyped
&& ((VmTyped) value).getVmClass().getPClassInfo() == PClassInfo.PcfRenderDirective;
return value instanceof VmTyped typed
&& typed.getVmClass().getPClassInfo() == PClassInfo.PcfRenderDirective;
}
@TruffleBoundary
@@ -348,8 +348,8 @@ public final class VmUtils {
// implements same behavior as AnyNodes#getClass
public static VmClass getClass(Object value) {
if (value instanceof VmValue) {
return ((VmValue) value).getVmClass();
if (value instanceof VmValue vmValue) {
return vmValue.getVmClass();
}
if (value instanceof String) {
return BaseModule.getStringClass();
@@ -627,8 +627,8 @@ public final class VmUtils {
// because constant type check wouldn't find the property (type)
var isLocalTyped = property.isLocal() && typeNode != null;
if (bodyNode instanceof ConstantNode && !isLocalTyped) {
property.initConstantValue((ConstantNode) bodyNode);
if (bodyNode instanceof ConstantNode constantNode && !isLocalTyped) {
property.initConstantValue(constantNode);
return property;
}
@@ -661,8 +661,8 @@ public final class VmUtils {
// because constant type check wouldn't find the property (type)
var isLocalTyped = property.isLocal() && typeNode != null;
if (bodyNode instanceof ConstantNode && !isLocalTyped) {
property.initConstantValue((ConstantNode) bodyNode);
if (bodyNode instanceof ConstantNode constantNode && !isLocalTyped) {
property.initConstantValue(constantNode);
return property;
}

View File

@@ -63,8 +63,8 @@ public abstract class VmValue {
/** Forces recursive (deep) evaluation of the given value. */
public static void force(Object value, boolean allowUndefinedValues) {
if (value instanceof VmValue) {
((VmValue) value).force(allowUndefinedValues);
if (value instanceof VmValue vmValue) {
vmValue.force(allowUndefinedValues);
}
}
@@ -73,16 +73,16 @@ public abstract class VmValue {
* be `VmNull`).
*/
public static Object export(Object value) {
if (value instanceof VmValue) {
return ((VmValue) value).export();
if (value instanceof VmValue vmValue) {
return vmValue.export();
}
return value;
}
/** Used to export object member values. Such values are `null` if they haven't been forced. */
public static @Nullable Object exportNullable(@Nullable Object value) {
if (value instanceof VmValue) {
return ((VmValue) value).export();
if (value instanceof VmValue vmValue) {
return vmValue.export();
}
return value;
}

View File

@@ -81,20 +81,20 @@ public interface VmValueConverter<T> {
T convertFunction(VmFunction value, Iterable<Object> path);
default T convert(Object value, Iterable<Object> path) {
if (value instanceof VmValue) {
return ((VmValue) value).accept(this, path);
if (value instanceof VmValue vmValue) {
return vmValue.accept(this, path);
}
if (value instanceof String) {
return convertString((String) value, path);
if (value instanceof String string) {
return convertString(string, path);
}
if (value instanceof Boolean) {
return convertBoolean((Boolean) value, path);
if (value instanceof Boolean b) {
return convertBoolean(b, path);
}
if (value instanceof Long) {
return convertInt((Long) value, path);
if (value instanceof Long l) {
return convertInt(l, path);
}
if (value instanceof Double) {
return convertFloat((Double) value, path);
if (value instanceof Double d) {
return convertFloat(d, path);
}
throw new IllegalArgumentException("Cannot convert VM value with unexpected type: " + value);

View File

@@ -61,16 +61,16 @@ public interface VmValueVisitor {
default void visit(Object value) {
Objects.requireNonNull(value, "Value to be visited must be non-null.");
if (value instanceof VmValue) {
((VmValue) value).accept(this);
} else if (value instanceof String) {
visitString((String) value);
} else if (value instanceof Boolean) {
visitBoolean((Boolean) value);
} else if (value instanceof Long) {
visitInt((Long) value);
} else if (value instanceof Double) {
visitFloat((Double) value);
if (value instanceof VmValue vmValue) {
vmValue.accept(this);
} else if (value instanceof String string) {
visitString(string);
} else if (value instanceof Boolean b) {
visitBoolean(b);
} else if (value instanceof Long l) {
visitInt(l);
} else if (value instanceof Double d) {
visitFloat(d);
} else {
throw new IllegalArgumentException("Unknown VM value type: " + value.getClass().getName());
}

View File

@@ -134,8 +134,7 @@ public class ExecutorSpiImpl implements ExecutorSpi {
List<URI> certificateUris;
int testPort;
try {
if (options instanceof ExecutorSpiOptions2) {
var options2 = (ExecutorSpiOptions2) options;
if (options instanceof ExecutorSpiOptions2 options2) {
certificateFiles = options2.getCertificateFiles();
certificateUris = options2.getCertificateUris();
testPort = options2.getTestPort();

View File

@@ -82,14 +82,14 @@ public final class PklSettings {
throws VmEvalException {
// can't use object mapping in pkl-core, so map manually
var editor = module.getPropertyOrNull("editor");
if (!(editor instanceof PObject)) {
if (!(editor instanceof PObject pObject)) {
throw new VmExceptionBuilder().evalError("invalidSettingsFile", location.getUri()).build();
}
var urlScheme = ((PObject) editor).getPropertyOrNull("urlScheme");
if (!(urlScheme instanceof String)) {
var urlScheme = pObject.getPropertyOrNull("urlScheme");
if (!(urlScheme instanceof String string)) {
throw new VmExceptionBuilder().evalError("invalidSettingsFile", location.getUri()).build();
}
return new PklSettings(new Editor((String) urlScheme));
return new PklSettings(new Editor(string));
}
/** Returns the editor for viewing and editing Pkl files. */

View File

@@ -46,99 +46,85 @@ final class PathSpecParser {
var codePoints = pathSpec.codePoints().toArray();
for (var idx = 0; idx < codePoints.length; idx++) {
switch (codePoints[idx]) {
case '^':
case '^' -> {
if (idx != 0) throw invalidPattern(pathSpec);
result.add(VmValueConverter.TOP_LEVEL_VALUE);
partStartIdx = 1;
break;
case '.':
}
case '.' -> {
switch (state) {
case 1:
case 1 -> {
int count = idx - partStartIdx;
if (count == 0) throw invalidPattern(pathSpec);
result.add(Identifier.get(new String(codePoints, partStartIdx, count)));
break;
case 3:
case 4:
break;
default:
throw invalidPattern(pathSpec);
}
case 3, 4 -> {}
default -> throw invalidPattern(pathSpec);
}
partStartIdx = idx + 1;
state = 1;
break;
case '[':
}
case '[' -> {
switch (state) {
case 1:
case 1 -> {
int count = idx - partStartIdx;
if (count == 0) throw invalidPattern(pathSpec);
result.add(Identifier.get(new String(codePoints, partStartIdx, count)));
break;
case 0:
case 3:
case 4:
break;
default:
throw invalidPattern(pathSpec);
}
case 0, 3, 4 -> {}
default -> throw invalidPattern(pathSpec);
}
partStartIdx = idx + 1;
state = 2;
break;
case ']':
}
case ']' -> {
switch (state) {
case 2:
case 2 -> {
int count = idx - partStartIdx;
if (count == 0) throw invalidPattern(pathSpec);
result.add(new String(codePoints, partStartIdx, count));
break;
case 5:
break;
default:
throw invalidPattern(pathSpec);
}
case 5 -> {}
default -> throw invalidPattern(pathSpec);
}
state = 3;
break;
case '*':
switch (state) {
case 0:
case 1:
if (partStartIdx != idx) throw invalidPattern(pathSpec);
result.add(VmValueConverter.WILDCARD_PROPERTY);
state = 4;
break;
case 2:
if (partStartIdx != idx) throw invalidPattern(pathSpec);
result.add(VmValueConverter.WILDCARD_ELEMENT);
state = 5;
break;
default:
throw invalidPattern(pathSpec);
}
break;
default:
}
case '*' ->
state =
switch (state) {
case 0, 1 -> {
if (partStartIdx != idx) throw invalidPattern(pathSpec);
result.add(VmValueConverter.WILDCARD_PROPERTY);
yield 4;
}
case 2 -> {
if (partStartIdx != idx) throw invalidPattern(pathSpec);
result.add(VmValueConverter.WILDCARD_ELEMENT);
yield 5;
}
default -> throw invalidPattern(pathSpec);
};
default -> {
if (state > 2) throw invalidPattern(pathSpec);
if (state == 0) state = 1;
break;
}
}
}
switch (state) {
case 0:
case 0 -> {
if (result.isEmpty()) {
// "" matches top-level value (deprecated in 0.15, use "^" instead)
result.add(VmValueConverter.TOP_LEVEL_VALUE);
}
break;
case 1:
}
case 1 -> {
var count = codePoints.length - partStartIdx;
if (count == 0) throw invalidPattern(pathSpec);
result.add(Identifier.get(new String(codePoints, partStartIdx, count)));
break;
case 3:
case 4:
break;
default:
throw invalidPattern(pathSpec);
}
case 3, 4 -> {}
default -> throw invalidPattern(pathSpec);
}
Collections.reverse(result);

View File

@@ -175,8 +175,8 @@ public final class PklConverter implements VmValueConverter<Object> {
converters.iterateMemberValues(
(key, member, value) -> {
assert value != null; // forced in ctor
if (key instanceof VmClass) {
result.put((VmClass) key, (VmFunction) value);
if (key instanceof VmClass vmClass) {
result.put(vmClass, (VmFunction) value);
}
return true;
});
@@ -190,8 +190,8 @@ public final class PklConverter implements VmValueConverter<Object> {
converters.iterateMemberValues(
(key, member, value) -> {
assert value != null; // forced in ctor
if (key instanceof String) {
result.add(Pair.of(parser.parse((String) key), (VmFunction) value));
if (key instanceof String string) {
result.add(Pair.of(parser.parse(string), (VmFunction) value));
}
return true;
});

View File

@@ -73,10 +73,10 @@ public final class CollectionNodes {
assert comparator != null;
var result = applyLambdaNode.execute(comparator, left, right);
if (result instanceof Boolean) return (Boolean) result;
if (result instanceof Boolean b) return b;
// deprecated
if (result instanceof Long) return (long) result < 0;
if (result instanceof Long l) return l < 0;
CompilerDirectives.transferToInterpreter();
throw exceptionBuilder()

View File

@@ -88,40 +88,28 @@ public final class DataSizeNodes {
public abstract static class toBinaryUnit extends ExternalMethod0Node {
@Specialization
protected VmDataSize eval(VmDataSize self) {
switch (self.getUnit()) {
case KILOBYTES:
return self.convertTo(DataSizeUnit.KIBIBYTES);
case MEGABYTES:
return self.convertTo(DataSizeUnit.MEBIBYTES);
case GIGABYTES:
return self.convertTo(DataSizeUnit.GIBIBYTES);
case TERABYTES:
return self.convertTo(DataSizeUnit.TEBIBYTES);
case PETABYTES:
return self.convertTo(DataSizeUnit.PEBIBYTES);
default:
return self;
}
return switch (self.getUnit()) {
case KILOBYTES -> self.convertTo(DataSizeUnit.KIBIBYTES);
case MEGABYTES -> self.convertTo(DataSizeUnit.MEBIBYTES);
case GIGABYTES -> self.convertTo(DataSizeUnit.GIBIBYTES);
case TERABYTES -> self.convertTo(DataSizeUnit.TEBIBYTES);
case PETABYTES -> self.convertTo(DataSizeUnit.PEBIBYTES);
default -> self;
};
}
}
public abstract static class toDecimalUnit extends ExternalMethod0Node {
@Specialization
protected VmDataSize eval(VmDataSize self) {
switch (self.getUnit()) {
case KIBIBYTES:
return self.convertTo(DataSizeUnit.KILOBYTES);
case MEBIBYTES:
return self.convertTo(DataSizeUnit.MEGABYTES);
case GIBIBYTES:
return self.convertTo(DataSizeUnit.GIGABYTES);
case TEBIBYTES:
return self.convertTo(DataSizeUnit.TERABYTES);
case PEBIBYTES:
return self.convertTo(DataSizeUnit.PETABYTES);
default:
return self;
}
return switch (self.getUnit()) {
case KIBIBYTES -> self.convertTo(DataSizeUnit.KILOBYTES);
case MEBIBYTES -> self.convertTo(DataSizeUnit.MEGABYTES);
case GIBIBYTES -> self.convertTo(DataSizeUnit.GIGABYTES);
case TEBIBYTES -> self.convertTo(DataSizeUnit.TERABYTES);
case PEBIBYTES -> self.convertTo(DataSizeUnit.PETABYTES);
default -> self;
};
}
}
}

View File

@@ -201,8 +201,8 @@ public final class JsonRendererNodes {
if (!isFirst) builder.append(',');
startNewLine();
if (key instanceof String) {
visitString((String) key);
if (key instanceof String string) {
visitString(string);
builder.append(separator);
return;
}

View File

@@ -243,8 +243,8 @@ public final class MapNodes {
for (var entry : self) {
var key = VmUtils.getKey(entry);
if (key instanceof String) {
var name = Identifier.get((String) key);
if (key instanceof String string) {
var name = Identifier.get(string);
EconomicMaps.put(
members,
name,

View File

@@ -239,11 +239,11 @@ public final class PListRendererNodes {
key = VmUtils.readTextProperty(key);
}
if (key instanceof String) {
if (key instanceof String string) {
builder
.append(currIndent)
.append("<key>")
.append(charEscaper.escape((String) key))
.append(charEscaper.escape(string))
.append("</key>")
.append(LINE_BREAK)
.append(currIndent);

Some files were not shown because too many files have changed in this diff Show More