Migrate to Java 16 Records (part 1) (#82338)

Try to represent immutable data with Java records introduced in [JEP 395](https://openjdk.java.net/jeps/395)
This commit is contained in:
Artem Prigoda 2022-01-18 17:53:06 +01:00 committed by GitHub
parent bc91cd0316
commit fc5a820da9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
200 changed files with 1491 additions and 3285 deletions

View File

@ -70,7 +70,7 @@ public class BwcSetupExtension {
@Override
public void execute(Task t) {
// Execution time so that the checkouts are available
String compilerVersionInfoPath = minimumCompilerVersionPath(unreleasedVersionInfo.get().version);
String compilerVersionInfoPath = minimumCompilerVersionPath(unreleasedVersionInfo.get().version());
String minimumCompilerVersion = readFromFile(new File(checkoutDir.get(), compilerVersionInfoPath));
loggedExec.environment("JAVA_HOME", getJavaHome(Integer.parseInt(minimumCompilerVersion)));
}
@ -108,8 +108,8 @@ public class BwcSetupExtension {
if (project.getGradle().getStartParameter().isParallelProjectExecutionEnabled()) {
loggedExec.args("--parallel");
}
loggedExec.setStandardOutput(new IndentingOutputStream(System.out, unreleasedVersionInfo.get().version));
loggedExec.setErrorOutput(new IndentingOutputStream(System.err, unreleasedVersionInfo.get().version));
loggedExec.setStandardOutput(new IndentingOutputStream(System.out, unreleasedVersionInfo.get().version()));
loggedExec.setErrorOutput(new IndentingOutputStream(System.err, unreleasedVersionInfo.get().version()));
configAction.execute(loggedExec);
});
}

View File

@ -18,7 +18,6 @@ import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
@ -280,39 +279,9 @@ public class BwcVersions {
return MINIMUM_WIRE_COMPATIBLE_VERSION;
}
public static class UnreleasedVersionInfo {
public final Version version;
public final String branch;
public final String gradleProjectPath;
public record UnreleasedVersionInfo(Version version, String branch, String gradleProjectPath) {}
public UnreleasedVersionInfo(Version version, String branch, String gradleProjectPath) {
this.version = version;
this.branch = branch;
this.gradleProjectPath = gradleProjectPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UnreleasedVersionInfo that = (UnreleasedVersionInfo) o;
return version.equals(that.version) && branch.equals(that.branch) && gradleProjectPath.equals(that.gradleProjectPath);
}
@Override
public int hashCode() {
return Objects.hash(version, branch, gradleProjectPath);
}
}
public static class VersionPair implements Comparable<VersionPair> {
public final Version elasticsearch;
public final Version lucene;
public VersionPair(Version elasticsearch, Version lucene) {
this.elasticsearch = elasticsearch;
this.lucene = lucene;
}
public record VersionPair(Version elasticsearch, Version lucene) implements Comparable<VersionPair> {
@Override
public int compareTo(@NotNull VersionPair o) {

View File

@ -181,20 +181,20 @@ public class DependenciesInfoTask extends ConventionTask {
String licenseType;
final LicenseAnalyzer.LicenseInfo licenseInfo = LicenseAnalyzer.licenseType(license);
if (licenseInfo.isSpdxLicense() == false) {
if (licenseInfo.spdxLicense() == false) {
// License has not be identified as SPDX.
// As we have the license file, we create a Custom entry with the URL to this license file.
final String gitBranch = System.getProperty("build.branch", "master");
final String githubBaseURL = "https://raw.githubusercontent.com/elastic/elasticsearch/" + gitBranch + "/";
licenseType = licenseInfo.getIdentifier()
licenseType = licenseInfo.identifier()
+ ";"
+ license.getCanonicalPath().replaceFirst(".*/elasticsearch/", githubBaseURL)
+ ",";
} else {
licenseType = licenseInfo.getIdentifier() + ",";
licenseType = licenseInfo.identifier() + ",";
}
if (licenseInfo.isSourceRedistributionRequired()) {
if (licenseInfo.sourceRedistributionRequired()) {
final File sources = getDependencyInfoFile(group, name, "SOURCES");
licenseType += Files.readString(sources.toPath()).trim();
}

View File

@ -59,7 +59,7 @@ public class InternalDistributionBwcSetupPlugin implements InternalPlugin {
BuildParams.getBwcVersions()
.forPreviousUnreleased(
(BwcVersions.UnreleasedVersionInfo unreleasedVersion) -> {
configureBwcProject(project.project(unreleasedVersion.gradleProjectPath), unreleasedVersion, bwcTaskThrottleProvider);
configureBwcProject(project.project(unreleasedVersion.gradleProjectPath()), unreleasedVersion, bwcTaskThrottleProvider);
}
);
}
@ -70,13 +70,13 @@ public class InternalDistributionBwcSetupPlugin implements InternalPlugin {
Provider<BwcTaskThrottle> bwcTaskThrottleProvider
) {
Provider<BwcVersions.UnreleasedVersionInfo> versionInfoProvider = providerFactory.provider(() -> versionInfo);
Provider<File> checkoutDir = versionInfoProvider.map(info -> new File(project.getBuildDir(), "bwc/checkout-" + info.branch));
Provider<File> checkoutDir = versionInfoProvider.map(info -> new File(project.getBuildDir(), "bwc/checkout-" + info.branch()));
BwcSetupExtension bwcSetupExtension = project.getExtensions()
.create("bwcSetup", BwcSetupExtension.class, project, versionInfoProvider, bwcTaskThrottleProvider, checkoutDir);
BwcGitExtension gitExtension = project.getPlugins().apply(InternalBwcGitPlugin.class).getGitExtension();
Provider<Version> bwcVersion = versionInfoProvider.map(info -> info.version);
gitExtension.setBwcVersion(versionInfoProvider.map(info -> info.version));
gitExtension.setBwcBranch(versionInfoProvider.map(info -> info.branch));
Provider<Version> bwcVersion = versionInfoProvider.map(info -> info.version());
gitExtension.setBwcVersion(versionInfoProvider.map(info -> info.version()));
gitExtension.setBwcBranch(versionInfoProvider.map(info -> info.branch()));
gitExtension.getCheckoutDir().set(checkoutDir);
// we want basic lifecycle tasks like `clean` here.

View File

@ -50,7 +50,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin {
DockerSupportPlugin.DOCKER_SUPPORT_SERVICE_NAME
);
distributionDownloadPlugin.setDockerAvailability(
dockerSupport.map(dockerSupportService -> dockerSupportService.getDockerAvailability().isAvailable)
dockerSupport.map(dockerSupportService -> dockerSupportService.getDockerAvailability().isAvailable())
);
registerInternalDistributionResolutions(DistributionDownloadPlugin.getRegistrationsContainer(project));
}
@ -88,7 +88,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin {
}
String projectConfig = getProjectConfig(distribution, unreleasedInfo);
return new ProjectBasedDistributionDependency(
(config) -> projectDependency(project, unreleasedInfo.gradleProjectPath, projectConfig)
(config) -> projectDependency(project, unreleasedInfo.gradleProjectPath(), projectConfig)
);
}
return null;
@ -107,7 +107,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin {
private static String getProjectConfig(ElasticsearchDistribution distribution, BwcVersions.UnreleasedVersionInfo info) {
String distributionProjectName = distributionProjectName(distribution);
if (distribution.getType().shouldExtract()) {
return (info.gradleProjectPath.equals(":distribution") || info.version.before("7.10.0"))
return (info.gradleProjectPath().equals(":distribution") || info.version().before("7.10.0"))
? distributionProjectName
: "expanded-" + distributionProjectName;
} else {

View File

@ -308,8 +308,8 @@ public abstract class DockerSupportService implements BuildService<DockerSupport
/**
* An immutable class that represents the results of a Docker search from {@link #getDockerAvailability()}}.
*/
public static class DockerAvailability {
/**
public record DockerAvailability(
/*
* Indicates whether Docker is available and meets the required criteria.
* True if, and only if, Docker is:
* <ul>
@ -319,71 +319,32 @@ public abstract class DockerSupportService implements BuildService<DockerSupport
* <li>Can execute a command that requires privileges</li>
* </ul>
*/
public final boolean isAvailable;
boolean isAvailable,
/**
* True if docker-compose is available.
*/
public final boolean isComposeAvailable;
// True if docker-compose is available.
boolean isComposeAvailable,
/**
* True if the installed Docker version is &gt;= 17.05
*/
public final boolean isVersionHighEnough;
// True if the installed Docker version is &gt,= 17.05
boolean isVersionHighEnough,
/**
* The path to the Docker CLI, or null
*/
public final String path;
// The path to the Docker CLI, or null
String path,
/**
* The installed Docker version, or null
*/
public final Version version;
// The installed Docker version, or null
Version version,
/**
* Information about the last command executes while probing Docker, or null.
*/
final Result lastCommand;
DockerAvailability(
boolean isAvailable,
boolean isComposeAvailable,
boolean isVersionHighEnough,
String path,
Version version,
Result lastCommand
) {
this.isAvailable = isAvailable;
this.isComposeAvailable = isComposeAvailable;
this.isVersionHighEnough = isVersionHighEnough;
this.path = path;
this.version = version;
this.lastCommand = lastCommand;
}
}
// Information about the last command executes while probing Docker, or null.
Result lastCommand
) {}
/**
* This class models the result of running a command. It captures the exit code, standard output and standard error.
*/
private static class Result {
final int exitCode;
final String stdout;
final String stderr;
Result(int exitCode, String stdout, String stderr) {
this.exitCode = exitCode;
this.stdout = stdout;
this.stderr = stderr;
}
private record Result(int exitCode, String stdout, String stderr) {
boolean isSuccess() {
return exitCode == 0;
}
public String toString() {
return "exitCode = [" + exitCode + "] " + "stdout = [" + stdout.trim() + "] " + "stderr = [" + stderr.trim() + "]";
}
}
interface Parameters extends BuildServiceParameters {

View File

@ -266,7 +266,7 @@ public class DependencyLicensesTask extends DefaultTask {
File licenseFile = new File(licensesDir, getFileName(dependencyName, licenses, "LICENSE"));
LicenseInfo licenseInfo = LicenseAnalyzer.licenseType(licenseFile);
if (licenseInfo.isSourceRedistributionRequired()) {
if (licenseInfo.sourceRedistributionRequired()) {
checkFile(dependencyName, jarName, sources, "SOURCES");
}
}

View File

@ -147,53 +147,16 @@ public class LicenseAnalyzer {
for (LicenseMatcher matcher : matchers) {
boolean matches = matcher.matches(licenseFile);
if (matches) {
return new LicenseInfo(matcher.getIdentifier(), matcher.spdxLicense, matcher.sourceRedistributionRequired);
return new LicenseInfo(matcher.identifier(), matcher.spdxLicense, matcher.sourceRedistributionRequired);
}
}
throw new IllegalStateException("Unknown license for license file: " + licenseFile);
}
public static class LicenseInfo {
private final String identifier;
private final boolean spdxLicense;
private final boolean sourceRedistributionRequired;
public record LicenseInfo(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired) {}
public LicenseInfo(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired) {
this.identifier = identifier;
this.spdxLicense = spdxLicense;
this.sourceRedistributionRequired = sourceRedistributionRequired;
}
public String getIdentifier() {
return identifier;
}
public boolean isSpdxLicense() {
return spdxLicense;
}
public boolean isSourceRedistributionRequired() {
return sourceRedistributionRequired;
}
}
private static class LicenseMatcher {
private final String identifier;
private final boolean spdxLicense;
private final boolean sourceRedistributionRequired;
private final Pattern pattern;
LicenseMatcher(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired, Pattern pattern) {
this.identifier = identifier;
this.spdxLicense = spdxLicense;
this.sourceRedistributionRequired = sourceRedistributionRequired;
this.pattern = pattern;
}
public String getIdentifier() {
return identifier;
}
private record LicenseMatcher(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired, Pattern pattern) {
public boolean matches(File licenseFile) {
try {

View File

@ -125,9 +125,9 @@ public class BreakingChangesGenerator {
bindings.put("breakingIncludeList", breakingIncludeList);
bindings.put("deprecationsByArea", deprecationsByArea);
bindings.put("isElasticsearchSnapshot", version.isSnapshot());
bindings.put("majorDotMinor", version.getMajor() + "." + version.getMinor());
bindings.put("majorMinor", String.valueOf(version.getMajor()) + version.getMinor());
bindings.put("nextMajor", (version.getMajor() + 1) + ".0");
bindings.put("majorDotMinor", version.major() + "." + version.minor());
bindings.put("majorMinor", String.valueOf(version.major()) + version.minor());
bindings.put("nextMajor", (version.major() + 1) + ".0");
bindings.put("version", version);
return TemplateUtils.render(template, bindings);
@ -152,7 +152,7 @@ public class BreakingChangesGenerator {
bindings.put("breakingArea", breakingArea);
bindings.put("breakingEntriesByNotability", breakingEntriesByNotability);
bindings.put("breakingAreaAnchor", breakingArea.toLowerCase(Locale.ROOT).replaceFirst(" and", "").replaceAll(" ", "_"));
bindings.put("majorMinor", String.valueOf(version.getMajor()) + version.getMinor());
bindings.put("majorMinor", String.valueOf(version.major()) + version.minor());
return TemplateUtils.render(template, bindings);
}

View File

@ -152,7 +152,7 @@ public class GenerateReleaseNotesTask extends DefaultTask {
@VisibleForTesting
static Set<QualifiedVersion> getVersions(GitWrapper gitWrapper, String currentVersion) {
QualifiedVersion v = QualifiedVersion.of(currentVersion);
Set<QualifiedVersion> versions = gitWrapper.listVersions("v" + v.getMajor() + '.' + v.getMinor() + ".*").collect(toSet());
Set<QualifiedVersion> versions = gitWrapper.listVersions("v" + v.major() + '.' + v.minor() + ".*").collect(toSet());
versions.add(v);
return versions;
}
@ -183,7 +183,7 @@ public class GenerateReleaseNotesTask extends DefaultTask {
QualifiedVersion currentVersion = QualifiedVersion.of(versionString);
// Find all tags for this minor series, using a wildcard tag pattern.
String tagWildcard = "v%d.%d*".formatted(currentVersion.getMajor(), currentVersion.getMinor());
String tagWildcard = "v%d.%d*".formatted(currentVersion.major(), currentVersion.minor());
final List<QualifiedVersion> earlierVersions = gitWrapper.listVersions(tagWildcard)
// Only keep earlier versions, and if `currentVersion` is a prerelease, then only prereleases too.

View File

@ -162,7 +162,7 @@ public class PruneChangelogsTask extends DefaultTask {
*/
@VisibleForTesting
static Stream<QualifiedVersion> findPreviousVersion(GitWrapper gitWrapper, QualifiedVersion version) {
final int majorSeries = version.getMinor() == 0 && version.getRevision() == 0 ? version.getMajor() - 1 : version.getMajor();
final int majorSeries = version.minor() == 0 && version.revision() == 0 ? version.major() - 1 : version.major();
final String tagPattern = "v" + majorSeries + ".*";
return gitWrapper.listVersions(tagPattern).filter(v -> v.isBefore(version));

View File

@ -21,26 +21,21 @@ import java.util.regex.Pattern;
* with how {@link Version} is used in the build. It also retains any qualifier (prerelease) information, and uses
* that information when comparing instances.
*/
public final class QualifiedVersion implements Comparable<QualifiedVersion> {
private final int major;
private final int minor;
private final int revision;
private final Qualifier qualifier;
public record QualifiedVersion(
int major,
int minor,
int revision,
org.elasticsearch.gradle.internal.release.QualifiedVersion.Qualifier qualifier
) implements Comparable<QualifiedVersion> {
private static final Pattern pattern = Pattern.compile(
"^v? (\\d+) \\. (\\d+) \\. (\\d+) (?: - (alpha\\d+ | beta\\d+ | rc\\d+ | SNAPSHOT ) )? $",
Pattern.COMMENTS
);
private QualifiedVersion(int major, int minor, int revision, String qualifier) {
this.major = major;
this.minor = minor;
this.revision = revision;
this.qualifier = qualifier == null ? null : Qualifier.of(qualifier);
}
/**
* Parses the supplied string into an object.
*
* @param s a version string in strict semver
* @return a new instance
*/
@ -55,7 +50,7 @@ public final class QualifiedVersion implements Comparable<QualifiedVersion> {
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
matcher.group(4)
matcher.group(4) == null ? null : Qualifier.of(matcher.group(4))
);
}
@ -64,42 +59,10 @@ public final class QualifiedVersion implements Comparable<QualifiedVersion> {
return "%d.%d.%d%s".formatted(major, minor, revision, qualifier == null ? "" : "-" + qualifier);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QualifiedVersion version = (QualifiedVersion) o;
return major == version.major
&& minor == version.minor
&& revision == version.revision
&& Objects.equals(qualifier, version.qualifier);
}
@Override
public int hashCode() {
return Objects.hash(major, minor, revision, qualifier);
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getRevision() {
return revision;
}
public boolean hasQualifier() {
return qualifier != null;
}
public Qualifier getQualifier() {
return qualifier;
}
public boolean isSnapshot() {
return this.qualifier != null && this.qualifier.level == QualifierLevel.SNAPSHOT;
}
@ -129,22 +92,10 @@ public final class QualifiedVersion implements Comparable<QualifiedVersion> {
SNAPSHOT
}
private static class Qualifier implements Comparable<Qualifier> {
private final QualifierLevel level;
private final int number;
private Qualifier(QualifierLevel level, int number) {
this.level = level;
this.number = number;
}
private record Qualifier(QualifierLevel level, int number) implements Comparable<Qualifier> {
private static final Comparator<Qualifier> COMPARATOR = Comparator.comparing((Qualifier p) -> p.level).thenComparing(p -> p.number);
@Override
public int compareTo(Qualifier other) {
return COMPARATOR.compare(this, other);
}
private static Qualifier of(String qualifier) {
if ("SNAPSHOT".equals(qualifier)) {
return new Qualifier(QualifierLevel.SNAPSHOT, 0);
@ -162,21 +113,14 @@ public final class QualifiedVersion implements Comparable<QualifiedVersion> {
}
}
@Override
public int compareTo(Qualifier other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return level == QualifierLevel.SNAPSHOT ? level.name() : level.name() + number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Qualifier that = (Qualifier) o;
return number == that.number && level == that.level;
}
@Override
public int hashCode() {
return Objects.hash(level, number);
}
}
}

View File

@ -39,9 +39,9 @@ public class ReleaseHighlightsGenerator {
static String generateFile(QualifiedVersion version, String template, List<ChangelogEntry> entries) throws IOException {
final List<String> priorVersions = new ArrayList<>();
if (version.getMinor() > 0) {
final int major = version.getMajor();
for (int minor = version.getMinor(); minor >= 0; minor--) {
if (version.minor() > 0) {
final int major = version.major();
for (int minor = version.minor(); minor >= 0; minor--) {
String majorMinor = major + "." + minor;
String fileSuffix = "";
if (major == 7 && minor < 7) {

View File

@ -43,7 +43,7 @@ public class ReleaseNotesIndexGenerator {
versionsSet.stream().map(v -> v.isSnapshot() ? v.withoutQualifier() : v).forEach(versions::add);
final List<String> includeVersions = versions.stream()
.map(v -> v.hasQualifier() ? v.toString() : v.getMajor() + "." + v.getMinor())
.map(v -> v.hasQualifier() ? v.toString() : v.major() + "." + v.minor())
.distinct()
.collect(Collectors.toList());

View File

@ -117,7 +117,7 @@ public class DistroTestPlugin implements Plugin<Project> {
depsTask.configure(t -> t.dependsOn(examplePlugin.getDependencies()));
depsTasks.put(taskname, depsTask);
TaskProvider<Test> destructiveTask = configureTestTask(project, taskname, distribution, t -> {
t.onlyIf(t2 -> distribution.isDocker() == false || dockerSupport.get().getDockerAvailability().isAvailable);
t.onlyIf(t2 -> distribution.isDocker() == false || dockerSupport.get().getDockerAvailability().isAvailable());
addDistributionSysprop(t, DISTRIBUTION_SYSPROP, distribution::getFilepath);
addDistributionSysprop(t, EXAMPLE_PLUGIN_SYSPROP, () -> examplePlugin.getSingleFile().toString());
t.exclude("**/PackageUpgradeTests.class");

View File

@ -32,7 +32,6 @@ import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ -184,41 +183,15 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe
* use this a the key for our HashMap, it's best to control the implementation as there's no guarantee that Gradle's
* various {@link TestDescriptor} implementations reliably implement equals and hashCode.
*/
public static class Descriptor {
private final String name;
private final String className;
private final String parent;
private Descriptor(String name, String className, String parent) {
this.name = name;
this.className = className;
this.parent = parent;
}
public record Descriptor(String name, String className, String parent) {
public static Descriptor of(TestDescriptor d) {
return new Descriptor(d.getName(), d.getClassName(), d.getParent() == null ? null : d.getParent().toString());
}
public String getClassName() {
return className;
}
public String getFullName() {
return className + "." + name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Descriptor that = (Descriptor) o;
return Objects.equals(name, that.name) && Objects.equals(className, that.className) && Objects.equals(parent, that.parent);
}
@Override
public int hashCode() {
return Objects.hash(name, className, parent);
}
}
private class EventWriter implements Closeable {
@ -226,7 +199,7 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe
private final Writer writer;
EventWriter(Descriptor descriptor) {
this.outputFile = new File(outputDirectory, descriptor.getClassName() + ".out");
this.outputFile = new File(outputDirectory, descriptor.className() + ".out");
FileOutputStream fos;
try {

View File

@ -54,7 +54,7 @@ public abstract class ReplaceByKey implements RestTestTransformByParentObject {
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.getTestName().equals(testName);
return testName == null || testContext.testName().equals(testName);
}
@Input

View File

@ -11,15 +11,4 @@ package org.elasticsearch.gradle.internal.test.rest.transform;
/**
* A place to stash information about a test that is being transformed.
*/
public class RestTestContext {
private final String testName;
public RestTestContext(String testName) {
this.testName = testName;
}
public String getTestName() {
return testName;
}
}
public record RestTestContext(String testName) {}

View File

@ -37,7 +37,7 @@ public class AddMatch implements RestTestTransformByParentArray {
@Override
public boolean shouldApply(RestTestContext testContext) {
return testContext.getTestName().equals(testName);
return testContext.testName().equals(testName);
}
@Override

View File

@ -47,7 +47,7 @@ public class RemoveMatch implements RestTestTransformByParentObject {
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.getTestName().equals(testName);
return testName == null || testContext.testName().equals(testName);
}
@Override

View File

@ -54,7 +54,7 @@ public class ReplaceTextual implements RestTestTransformByParentObject {
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.getTestName().equals(testName);
return testName == null || testContext.testName().equals(testName);
}
@Override

View File

@ -88,7 +88,7 @@ public class InjectAllowedWarnings extends FeatureInjector implements RestTestTr
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.getTestName().equals(testName);
return testName == null || testContext.testName().equals(testName);
}
@Input

View File

@ -76,7 +76,7 @@ public class InjectWarnings extends FeatureInjector implements RestTestTransform
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName.equals(testContext.getTestName());
return testName.equals(testContext.testName());
}
@Input

View File

@ -82,7 +82,7 @@ public class RemoveWarnings implements RestTestTransformByParentObject {
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.getTestName().equals(testName);
return testName == null || testContext.testName().equals(testName);
}
@Input

View File

@ -169,7 +169,7 @@ public class TestFixturesPlugin implements Plugin<Project> {
private void maybeSkipTask(Provider<DockerSupportService> dockerSupport, Task task) {
task.onlyIf(spec -> {
boolean isComposeAvailable = dockerSupport.get().getDockerAvailability().isComposeAvailable;
boolean isComposeAvailable = dockerSupport.get().getDockerAvailability().isComposeAvailable();
if (isComposeAvailable == false) {
LOGGER.info("Task {} requires docker-compose but it is unavailable. Task will be skipped.", task.getPath());
}

View File

@ -31,19 +31,19 @@ public class AbstractDistributionDownloadPluginTests extends GradleUnitTestCase
protected static final VersionPair BWC_MAINTENANCE_VERSION = new VersionPair(Version.fromString("0.90.1"), Version.fromString("1.1.3"));
protected static final BwcVersions BWC_MINOR = new BwcVersions(
BWC_MAJOR_VERSION.elasticsearch,
BWC_MAJOR_VERSION.elasticsearch(),
Arrays.asList(BWC_BUGFIX_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION)
);
protected static final BwcVersions BWC_STAGED = new BwcVersions(
BWC_MAJOR_VERSION.elasticsearch,
BWC_MAJOR_VERSION.elasticsearch(),
Arrays.asList(BWC_MAINTENANCE_VERSION, BWC_STAGED_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION)
);
protected static final BwcVersions BWC_BUGFIX = new BwcVersions(
BWC_MAJOR_VERSION.elasticsearch,
BWC_MAJOR_VERSION.elasticsearch(),
Arrays.asList(BWC_BUGFIX_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION)
);
protected static final BwcVersions BWC_MAINTENANCE = new BwcVersions(
BWC_MINOR_VERSION.elasticsearch,
BWC_MINOR_VERSION.elasticsearch(),
Arrays.asList(BWC_MAINTENANCE_VERSION, BWC_BUGFIX_VERSION, BWC_MINOR_VERSION)
);

View File

@ -132,10 +132,10 @@ public class DistributionDownloadPluginTests extends AbstractDistributionDownloa
String configName = projectName(platform.toString(), true);
configName += (platform == Platform.WINDOWS ? "-zip" : "-tar");
ElasticsearchDistributionType archiveType = ElasticsearchDistributionTypes.ARCHIVE;
checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch, archiveType, platform, BWC_MINOR);
checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch, archiveType, platform, BWC_STAGED);
checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch, archiveType, platform, BWC_BUGFIX);
checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch, archiveType, platform, BWC_MAINTENANCE);
checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch(), archiveType, platform, BWC_MINOR);
checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch(), archiveType, platform, BWC_STAGED);
checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch(), archiveType, platform, BWC_BUGFIX);
checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch(), archiveType, platform, BWC_MAINTENANCE);
}
}

View File

@ -38,10 +38,10 @@ public class InternalDistributionDownloadPluginTests extends AbstractDistributio
for (ElasticsearchDistributionType packageType : types) {
// note: no non bundled jdk for bwc
String configName = projectName(packageType.toString(), true);
checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch, packageType, null, BWC_MINOR);
checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch, packageType, null, BWC_STAGED);
checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch, packageType, null, BWC_BUGFIX);
checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch, packageType, null, BWC_MAINTENANCE);
checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch(), packageType, null, BWC_MINOR);
checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch(), packageType, null, BWC_STAGED);
checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch(), packageType, null, BWC_BUGFIX);
checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch(), packageType, null, BWC_MAINTENANCE);
}
}
}

View File

@ -8,24 +8,9 @@
package org.elasticsearch.gradle.util;
public class Pair<L, R> {
private final L left;
private final R right;
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
public record Pair<L, R> (L left, R right) {
public static <L, R> Pair<L, R> of(L left, R right) {
return new Pair<>(left, right);
}
public L left() {
return left;
}
public R right() {
return right;
}
}

View File

@ -57,26 +57,26 @@ public final class BenchmarkRunner {
}
for (Metrics metrics : summaryMetrics) {
String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput);
String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput());
String serviceTimes = String.format(
Locale.ROOT,
"Service time [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f",
metrics.serviceTimeP50,
metrics.serviceTimeP90,
metrics.serviceTimeP95,
metrics.serviceTimeP99,
metrics.serviceTimeP999,
metrics.serviceTimeP9999
metrics.serviceTimeP50(),
metrics.serviceTimeP90(),
metrics.serviceTimeP95(),
metrics.serviceTimeP99(),
metrics.serviceTimeP999(),
metrics.serviceTimeP9999()
);
String latencies = String.format(
Locale.ROOT,
"Latency [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f",
metrics.latencyP50,
metrics.latencyP90,
metrics.latencyP95,
metrics.latencyP99,
metrics.latencyP999,
metrics.latencyP9999
metrics.latencyP50(),
metrics.latencyP90(),
metrics.latencyP95(),
metrics.latencyP99(),
metrics.latencyP999(),
metrics.latencyP9999()
);
int lineLength = Math.max(serviceTimes.length(), latencies.length());
@ -85,7 +85,7 @@ public final class BenchmarkRunner {
System.out.println(throughput);
System.out.println(serviceTimes);
System.out.println(latencies);
System.out.printf("success count = %d, error count = %d%n", metrics.successCount, metrics.errorCount);
System.out.printf("success count = %d, error count = %d%n", metrics.successCount(), metrics.errorCount());
System.out.println(repeat(lineLength, '-'));
}
}

View File

@ -7,57 +7,21 @@
*/
package org.elasticsearch.client.benchmark.metrics;
public final class Metrics {
public final String operation;
public final long successCount;
public final long errorCount;
public final double throughput;
public final double serviceTimeP50;
public final double serviceTimeP90;
public final double serviceTimeP95;
public final double serviceTimeP99;
public final double serviceTimeP999;
public final double serviceTimeP9999;
public final double latencyP50;
public final double latencyP90;
public final double latencyP95;
public final double latencyP99;
public final double latencyP999;
public final double latencyP9999;
public Metrics(
String operation,
long successCount,
long errorCount,
double throughput,
double serviceTimeP50,
double serviceTimeP90,
double serviceTimeP95,
double serviceTimeP99,
double serviceTimeP999,
double serviceTimeP9999,
double latencyP50,
double latencyP90,
double latencyP95,
double latencyP99,
double latencyP999,
double latencyP9999
) {
this.operation = operation;
this.successCount = successCount;
this.errorCount = errorCount;
this.throughput = throughput;
this.serviceTimeP50 = serviceTimeP50;
this.serviceTimeP90 = serviceTimeP90;
this.serviceTimeP95 = serviceTimeP95;
this.serviceTimeP99 = serviceTimeP99;
this.serviceTimeP999 = serviceTimeP999;
this.serviceTimeP9999 = serviceTimeP9999;
this.latencyP50 = latencyP50;
this.latencyP90 = latencyP90;
this.latencyP95 = latencyP95;
this.latencyP99 = latencyP99;
this.latencyP999 = latencyP999;
this.latencyP9999 = latencyP9999;
}
}
public record Metrics(
String operation,
long successCount,
long errorCount,
double throughput,
double serviceTimeP50,
double serviceTimeP90,
double serviceTimeP95,
double serviceTimeP99,
double serviceTimeP999,
double serviceTimeP9999,
double latencyP50,
double latencyP90,
double latencyP95,
double latencyP99,
double latencyP999,
double latencyP9999
) {}

View File

@ -7,20 +7,7 @@
*/
package org.elasticsearch.client.benchmark.metrics;
public final class Sample {
private final String operation;
private final long expectedStartTimestamp;
private final long startTimestamp;
private final long stopTimestamp;
private final boolean success;
public Sample(String operation, long expectedStartTimestamp, long startTimestamp, long stopTimestamp, boolean success) {
this.operation = operation;
this.expectedStartTimestamp = expectedStartTimestamp;
this.startTimestamp = startTimestamp;
this.stopTimestamp = stopTimestamp;
this.success = success;
}
public record Sample(String operation, long expectedStartTimestamp, long startTimestamp, long stopTimestamp, boolean success) {
public String getOperation() {
return operation;

View File

@ -99,13 +99,5 @@ public class BootstrapJvmOptions {
}
// package-private for testing
static class PluginInfo {
public final List<String> jarFiles;
public final Properties properties;
PluginInfo(List<String> jarFiles, Properties properties) {
this.jarFiles = jarFiles;
this.properties = properties;
}
}
record PluginInfo(List<String> jarFiles, Properties properties) {}
}

View File

@ -28,11 +28,19 @@ import javax.net.ssl.X509ExtendedTrustManager;
/**
* A object encapsulating all necessary configuration for an SSL context (client or server).
* The configuration itself is immutable, but the {@link #getKeyConfig() key config} and
* {@link #getTrustConfig() trust config} may depend on reading key and certificate material
* The configuration itself is immutable, but the {@link #keyConfig() key config} and
* {@link #trustConfig() trust config} may depend on reading key and certificate material
* from files (see {@link #getDependentFiles()}, and the content of those files may change.
*/
public class SslConfiguration {
public record SslConfiguration(
boolean explicitlyConfigured,
SslTrustConfig trustConfig,
SslKeyConfig keyConfig,
SslVerificationMode verificationMode,
SslClientAuthenticationMode clientAuth,
List<String> ciphers,
List<String> supportedProtocols
) {
/**
* An ordered map of protocol algorithms to SSLContext algorithms. The map is ordered from most
@ -41,6 +49,7 @@ public class SslConfiguration {
* Java Security Standard Algorithm Names Documentation for Java 11</a>.
*/
static final Map<String, String> ORDERED_PROTOCOL_ALGORITHM_MAP;
static {
LinkedHashMap<String, String> protocolAlgorithmMap = new LinkedHashMap<>();
try {
@ -58,14 +67,6 @@ public class SslConfiguration {
ORDERED_PROTOCOL_ALGORITHM_MAP = Collections.unmodifiableMap(protocolAlgorithmMap);
}
private final boolean explicitlyConfigured;
private final SslTrustConfig trustConfig;
private final SslKeyConfig keyConfig;
private final SslVerificationMode verificationMode;
private final SslClientAuthenticationMode clientAuth;
private final List<String> ciphers;
private final List<String> supportedProtocols;
public SslConfiguration(
boolean explicitlyConfigured,
SslTrustConfig trustConfig,
@ -90,30 +91,10 @@ public class SslConfiguration {
this.supportedProtocols = Collections.unmodifiableList(supportedProtocols);
}
public SslTrustConfig getTrustConfig() {
return trustConfig;
}
public SslKeyConfig getKeyConfig() {
return keyConfig;
}
public SslVerificationMode getVerificationMode() {
return verificationMode;
}
public SslClientAuthenticationMode getClientAuth() {
return clientAuth;
}
public List<String> getCipherSuites() {
return ciphers;
}
public List<String> getSupportedProtocols() {
return supportedProtocols;
}
/**
* @return A collection of files that are used by this SSL configuration. If the contents of these files change, then any
* subsequent call to {@link #createSslContext()} (or similar methods) may create a context with different behaviour.
@ -139,7 +120,7 @@ public class SslConfiguration {
/**
* Dynamically create a new SSL context based on the current state of the configuration.
* Because the {@link #getKeyConfig() key config} and {@link #getTrustConfig() trust config} may change based on the
* Because the {@link #keyConfig() key config} and {@link #trustConfig() trust config} may change based on the
* contents of their referenced files (see {@link #getDependentFiles()}, consecutive calls to this method may
* return ssl-contexts with different configurations.
*/
@ -157,7 +138,7 @@ public class SslConfiguration {
/**
* Picks the best (highest security / most recent standard) SSL/TLS protocol (/version) that is supported by the
* {@link #getSupportedProtocols() configured protocols}.
* {@link #supportedProtocols() configured protocols}.
*/
private String contextProtocol() {
if (supportedProtocols.isEmpty()) {
@ -173,25 +154,7 @@ public class SslConfiguration {
);
}
@Override
public String toString() {
return getClass().getSimpleName()
+ '{'
+ "trustConfig="
+ trustConfig
+ ", keyConfig="
+ keyConfig
+ ", verificationMode="
+ verificationMode
+ ", clientAuth="
+ clientAuth
+ ", ciphers="
+ ciphers
+ ", supportedProtocols="
+ supportedProtocols
+ '}';
}
// TODO Add explicitlyConfigured to equals&hashCode?
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -210,7 +173,4 @@ public class SslConfiguration {
return Objects.hash(trustConfig, keyConfig, verificationMode, clientAuth, ciphers, supportedProtocols);
}
public boolean isExplicitlyConfigured() {
return explicitlyConfigured;
}
}

View File

@ -252,7 +252,7 @@ public abstract class SslConfigurationLoader {
/**
* Clients of this class should implement this method to determine whether there are any settings for a given prefix.
* This is used to populate {@link SslConfiguration#isExplicitlyConfigured()}.
* This is used to populate {@link SslConfiguration#explicitlyConfigured()}.
*/
protected abstract boolean hasSettings(String prefix);

View File

@ -61,14 +61,7 @@ public class SslDiagnostics {
SERVER
}
private static class IssuerTrust {
private final List<X509Certificate> issuerCerts;
private final boolean verified;
private IssuerTrust(List<X509Certificate> issuerCerts, boolean verified) {
this.issuerCerts = issuerCerts;
this.verified = verified;
}
private record IssuerTrust(List<X509Certificate> issuerCerts, boolean verified) {
private static IssuerTrust noMatchingCertificate() {
return new IssuerTrust(null, false);

View File

@ -17,64 +17,15 @@ import java.util.Objects;
* Information about a certificate that is locally stored.It includes a reference to the {@link X509Certificate} itself,
* as well as information about where it was loaded from.
*/
public final class StoredCertificate {
private final X509Certificate certificate;
@Nullable
// Will be null in PKCS#11
private final String path;
private final String format;
@Nullable
// Will be null in PEM
private final String alias;
private final boolean hasPrivateKey;
public StoredCertificate(X509Certificate certificate, String path, String format, String alias, boolean hasPrivateKey) {
this.certificate = Objects.requireNonNull(certificate, "Certificate may not be null");
this.path = path;
this.format = Objects.requireNonNull(format, "Format may not be null");
this.alias = alias;
this.hasPrivateKey = hasPrivateKey;
}
public X509Certificate getCertificate() {
return certificate;
}
public String getPath() {
return path;
}
public String getFormat() {
return format;
}
public String getAlias() {
return alias;
}
public boolean hasPrivateKey() {
return hasPrivateKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StoredCertificate that = (StoredCertificate) o;
return hasPrivateKey == that.hasPrivateKey
&& certificate.equals(that.certificate)
&& Objects.equals(path, that.path)
&& format.equals(that.format)
&& Objects.equals(alias, that.alias);
}
@Override
public int hashCode() {
return Objects.hash(certificate, path, format, alias, hasPrivateKey);
public record StoredCertificate(
X509Certificate certificate,
@Nullable String path,
String format,
@Nullable String alias,
boolean hasPrivateKey
) {
public StoredCertificate {
Objects.requireNonNull(certificate, "Certificate may not be null");
Objects.requireNonNull(format, "Format may not be null");
}
}

View File

@ -102,17 +102,17 @@ public class PemKeyConfigTests extends ESTestCase {
StoredCertificate c1 = iterator.next();
StoredCertificate c2 = iterator.next();
assertThat(c1.getCertificate().getSubjectDN().toString(), equalTo("CN=cert1"));
assertThat(c1.certificate().getSubjectDN().toString(), equalTo("CN=cert1"));
assertThat(c1.hasPrivateKey(), equalTo(true));
assertThat(c1.getAlias(), nullValue());
assertThat(c1.getFormat(), equalTo("PEM"));
assertThat(c1.getPath(), equalTo(chain.toString()));
assertThat(c1.alias(), nullValue());
assertThat(c1.format(), equalTo("PEM"));
assertThat(c1.path(), equalTo(chain.toString()));
assertThat(c2.getCertificate().getSubjectDN().toString(), equalTo("CN=Test CA 1"));
assertThat(c2.certificate().getSubjectDN().toString(), equalTo("CN=Test CA 1"));
assertThat(c2.hasPrivateKey(), equalTo(false));
assertThat(c2.getAlias(), nullValue());
assertThat(c2.getFormat(), equalTo("PEM"));
assertThat(c2.getPath(), equalTo(chain.toString()));
assertThat(c2.alias(), nullValue());
assertThat(c2.format(), equalTo("PEM"));
assertThat(c2.path(), equalTo(chain.toString()));
final List<Tuple<PrivateKey, X509Certificate>> keys = keyConfig.getKeys();
assertThat(keys, iterableWithSize(1));

View File

@ -75,12 +75,12 @@ public class SslConfigurationLoaderTests extends ESTestCase {
.putList("test.ssl.supported_protocols", protocols)
.build();
final SslConfiguration configuration = loader.load(certRoot);
assertThat(configuration.getClientAuth(), is(clientAuth));
assertThat(configuration.getVerificationMode(), is(verificationMode));
assertThat(configuration.clientAuth(), is(clientAuth));
assertThat(configuration.verificationMode(), is(verificationMode));
assertThat(configuration.getCipherSuites(), equalTo(Arrays.asList(ciphers)));
assertThat(configuration.getSupportedProtocols(), equalTo(Arrays.asList(protocols)));
assertThat(configuration.supportedProtocols(), equalTo(Arrays.asList(protocols)));
if (verificationMode == SslVerificationMode.NONE) {
final SslTrustConfig trustConfig = configuration.getTrustConfig();
final SslTrustConfig trustConfig = configuration.trustConfig();
assertThat(trustConfig, instanceOf(TrustEverythingConfig.class));
}
}
@ -88,7 +88,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
public void testLoadTrustFromPemCAs() {
settings = Settings.builder().putList("test.ssl.certificate_authorities", "ca1/ca.crt", "ca2/ca.crt", "ca3/ca.crt").build();
final SslConfiguration configuration = loader.load(certRoot);
final SslTrustConfig trustConfig = configuration.getTrustConfig();
final SslTrustConfig trustConfig = configuration.trustConfig();
assertThat(trustConfig, instanceOf(PemTrustConfig.class));
assertThat(
trustConfig.getDependentFiles(),
@ -114,7 +114,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
}
settings = builder.build();
final SslConfiguration configuration = loader.load(certRoot);
final SslTrustConfig trustConfig = configuration.getTrustConfig();
final SslTrustConfig trustConfig = configuration.trustConfig();
assertThat(trustConfig, instanceOf(StoreTrustConfig.class));
assertThat(trustConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/ca-all/ca.p12")));
assertThat(trustConfig.createTrustManager(), notNullValue());
@ -137,7 +137,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
}
settings = builder.build();
final SslConfiguration configuration = loader.load(certRoot);
final SslTrustConfig trustConfig = configuration.getTrustConfig();
final SslTrustConfig trustConfig = configuration.trustConfig();
assertThat(trustConfig, instanceOf(StoreTrustConfig.class));
assertThat(trustConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/ca-all/ca.jks")));
assertThat(trustConfig.createTrustManager(), notNullValue());
@ -159,7 +159,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
}
settings = builder.build();
final SslConfiguration configuration = loader.load(certRoot);
final SslKeyConfig keyConfig = configuration.getKeyConfig();
final SslKeyConfig keyConfig = configuration.keyConfig();
assertThat(keyConfig, instanceOf(PemKeyConfig.class));
assertThat(
keyConfig.getDependentFiles(),
@ -188,7 +188,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
}
settings = builder.build();
final SslConfiguration configuration = loader.load(certRoot);
final SslKeyConfig keyConfig = configuration.getKeyConfig();
final SslKeyConfig keyConfig = configuration.keyConfig();
assertThat(keyConfig, instanceOf(StoreKeyConfig.class));
assertThat(keyConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/cert-all/certs.p12")));
assertThat(keyConfig.createKeyManager(), notNullValue());
@ -216,7 +216,7 @@ public class SslConfigurationLoaderTests extends ESTestCase {
}
settings = builder.build();
final SslConfiguration configuration = loader.load(certRoot);
final SslKeyConfig keyConfig = configuration.getKeyConfig();
final SslKeyConfig keyConfig = configuration.keyConfig();
assertThat(keyConfig, instanceOf(StoreKeyConfig.class));
assertThat(keyConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/cert-all/certs.jks")));
assertThat(keyConfig.createKeyManager(), notNullValue());

View File

@ -48,12 +48,12 @@ public class SslConfigurationTests extends ESTestCase {
protocols
);
assertThat(configuration.getTrustConfig(), is(trustConfig));
assertThat(configuration.getKeyConfig(), is(keyConfig));
assertThat(configuration.getVerificationMode(), is(verificationMode));
assertThat(configuration.getClientAuth(), is(clientAuth));
assertThat(configuration.trustConfig(), is(trustConfig));
assertThat(configuration.keyConfig(), is(keyConfig));
assertThat(configuration.verificationMode(), is(verificationMode));
assertThat(configuration.clientAuth(), is(clientAuth));
assertThat(configuration.getCipherSuites(), is(ciphers));
assertThat(configuration.getSupportedProtocols(), is(protocols));
assertThat(configuration.supportedProtocols(), is(protocols));
assertThat(configuration.toString(), containsString("TEST-TRUST"));
assertThat(configuration.toString(), containsString("TEST-KEY"));
@ -84,12 +84,12 @@ public class SslConfigurationTests extends ESTestCase {
configuration,
orig -> new SslConfiguration(
true,
orig.getTrustConfig(),
orig.getKeyConfig(),
orig.getVerificationMode(),
orig.getClientAuth(),
orig.trustConfig(),
orig.keyConfig(),
orig.verificationMode(),
orig.clientAuth(),
orig.getCipherSuites(),
orig.getSupportedProtocols()
orig.supportedProtocols()
),
this::mutateSslConfiguration
);
@ -99,37 +99,37 @@ public class SslConfigurationTests extends ESTestCase {
return switch (randomIntBetween(1, 4)) {
case 1 -> new SslConfiguration(
true,
orig.getTrustConfig(),
orig.getKeyConfig(),
randomValueOtherThan(orig.getVerificationMode(), () -> randomFrom(SslVerificationMode.values())),
orig.getClientAuth(),
orig.trustConfig(),
orig.keyConfig(),
randomValueOtherThan(orig.verificationMode(), () -> randomFrom(SslVerificationMode.values())),
orig.clientAuth(),
orig.getCipherSuites(),
orig.getSupportedProtocols()
orig.supportedProtocols()
);
case 2 -> new SslConfiguration(
true,
orig.getTrustConfig(),
orig.getKeyConfig(),
orig.getVerificationMode(),
randomValueOtherThan(orig.getClientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())),
orig.trustConfig(),
orig.keyConfig(),
orig.verificationMode(),
randomValueOtherThan(orig.clientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())),
orig.getCipherSuites(),
orig.getSupportedProtocols()
orig.supportedProtocols()
);
case 3 -> new SslConfiguration(
true,
orig.getTrustConfig(),
orig.getKeyConfig(),
orig.getVerificationMode(),
orig.getClientAuth(),
orig.trustConfig(),
orig.keyConfig(),
orig.verificationMode(),
orig.clientAuth(),
DEFAULT_CIPHERS,
orig.getSupportedProtocols()
orig.supportedProtocols()
);
default -> new SslConfiguration(
true,
orig.getTrustConfig(),
orig.getKeyConfig(),
orig.getVerificationMode(),
orig.getClientAuth(),
orig.trustConfig(),
orig.keyConfig(),
orig.verificationMode(),
orig.clientAuth(),
orig.getCipherSuites(),
Arrays.asList(VALID_PROTOCOLS)
);

View File

@ -14,19 +14,10 @@ package org.elasticsearch.xcontent;
* position of a parsing error to end users and consequently have line and
* column numbers starting from 1.
*/
public final class XContentLocation {
public record XContentLocation(int lineNumber, int columnNumber) {
public static final XContentLocation UNKNOWN = new XContentLocation(-1, -1);
public final int lineNumber;
public final int columnNumber;
public XContentLocation(int lineNumber, int columnNumber) {
super();
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
}
@Override
public String toString() {
return lineNumber + ":" + columnNumber;

View File

@ -34,11 +34,11 @@ public class XContentParseException extends IllegalArgumentException {
}
public int getLineNumber() {
return location.map(l -> l.lineNumber).orElse(-1);
return location.map(l -> l.lineNumber()).orElse(-1);
}
public int getColumnNumber() {
return location.map(l -> l.columnNumber).orElse(-1);
return location.map(l -> l.columnNumber()).orElse(-1);
}
@Nullable

View File

@ -8,10 +8,7 @@
package org.elasticsearch.xcontent;
import org.elasticsearch.common.Strings;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg;
@ -19,7 +16,7 @@ import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg
* Simple structure with 3 fields: int, double and String.
* Used for testing parsers.
*/
class SimpleStruct implements ToXContentObject {
record SimpleStruct(int i, double d, String s) implements ToXContentObject {
static SimpleStruct fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
@ -42,16 +39,6 @@ class SimpleStruct implements ToXContentObject {
PARSER.declareString(constructorArg(), S);
}
private final int i;
private final double d;
private final String s;
SimpleStruct(int i, double d, String s) {
this.i = i;
this.d = d;
this.s = s;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject()
@ -60,22 +47,4 @@ class SimpleStruct implements ToXContentObject {
.field(S.getPreferredName(), s)
.endObject();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SimpleStruct other = (SimpleStruct) o;
return i == other.i && d == other.d && Objects.equals(s, other.s);
}
@Override
public int hashCode() {
return Objects.hash(i, d, s);
}
@Override
public String toString() {
return Strings.toString(this);
}
}

View File

@ -217,14 +217,14 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
public void testUpdatedTimestamp() throws Exception {
assumeTrue("only test with fixture to have stable results", ENDPOINT != null);
testGeoIpDatabasesDownload();
long lastCheck = getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").getLastCheck();
long lastCheck = getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").lastCheck();
ClusterUpdateSettingsResponse settingsResponse = client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().put(GeoIpDownloader.POLL_INTERVAL_SETTING.getKey(), TimeValue.timeValueDays(2)))
.get();
assertTrue(settingsResponse.isAcknowledged());
assertBusy(() -> assertNotEquals(lastCheck, getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").getLastCheck()));
assertBusy(() -> assertNotEquals(lastCheck, getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").lastCheck()));
testGeoIpDatabasesDownload();
}
@ -247,8 +247,8 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
assertEquals(Set.of("GeoLite2-ASN.mmdb", "GeoLite2-City.mmdb", "GeoLite2-Country.mmdb"), state.getDatabases().keySet());
GeoIpTaskState.Metadata metadata = state.get(id);
BoolQueryBuilder queryBuilder = new BoolQueryBuilder().filter(new MatchQueryBuilder("name", id))
.filter(new RangeQueryBuilder("chunk").from(metadata.getFirstChunk()).to(metadata.getLastChunk(), true));
int size = metadata.getLastChunk() - metadata.getFirstChunk() + 1;
.filter(new RangeQueryBuilder("chunk").from(metadata.firstChunk()).to(metadata.lastChunk(), true));
int size = metadata.lastChunk() - metadata.firstChunk() + 1;
SearchResponse res = client().prepareSearch(GeoIpDownloader.DATABASES_INDEX)
.setSize(size)
.setQuery(queryBuilder)
@ -268,7 +268,7 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
TarInputStream stream = new TarInputStream(new GZIPInputStream(new MultiByteArrayInputStream(data)));
TarInputStream.TarEntry entry;
while ((entry = stream.getNextEntry()) != null) {
if (entry.getName().endsWith(".mmdb")) {
if (entry.name().endsWith(".mmdb")) {
break;
}
}

View File

@ -207,7 +207,7 @@ public final class DatabaseNodeService implements Closeable {
String name = e.getKey();
GeoIpTaskState.Metadata metadata = e.getValue();
DatabaseReaderLazyLoader reference = databases.get(name);
String remoteMd5 = metadata.getMd5();
String remoteMd5 = metadata.md5();
String localMd5 = reference != null ? reference.getMd5() : null;
if (Objects.equals(localMd5, remoteMd5)) {
LOGGER.debug("Current reference of [{}] is up to date [{}] with was recorded in CS [{}]", name, localMd5, remoteMd5);
@ -234,7 +234,7 @@ public final class DatabaseNodeService implements Closeable {
}
void retrieveAndUpdateDatabase(String databaseName, GeoIpTaskState.Metadata metadata) throws IOException {
final String recordedMd5 = metadata.getMd5();
final String recordedMd5 = metadata.md5();
// This acts as a lock, if this method for a specific db is executed later and downloaded for this db is still ongoing then
// FileAlreadyExistsException is thrown and this method silently returns.
@ -281,11 +281,11 @@ public final class DatabaseNodeService implements Closeable {
TarInputStream.TarEntry entry;
while ((entry = is.getNextEntry()) != null) {
// there might be ./ entry in tar, we should skip it
if (entry.isNotFile()) {
if (entry.notFile()) {
continue;
}
// flatten structure, remove any directories present from the path (should be ./ only)
String name = entry.getName().substring(entry.getName().lastIndexOf('/') + 1);
String name = entry.name().substring(entry.name().lastIndexOf('/') + 1);
if (name.startsWith(databaseName)) {
Files.copy(is, databaseTmpFile, StandardCopyOption.REPLACE_EXISTING);
} else {
@ -378,15 +378,15 @@ public final class DatabaseNodeService implements Closeable {
// Need to run the search from a different thread, since this is executed from cluster state applier thread:
genericExecutor.accept(() -> {
MessageDigest md = MessageDigests.md5();
int firstChunk = metadata.getFirstChunk();
int lastChunk = metadata.getLastChunk();
int firstChunk = metadata.firstChunk();
int lastChunk = metadata.lastChunk();
try {
// TODO: invoke open point in time api when this api is moved from xpack core to server module.
// (so that we have a consistent view of the chunk documents while doing the lookups)
// (the chance that the documents change is rare, given the low frequency of the updates for these databases)
for (int chunk = firstChunk; chunk <= lastChunk; chunk++) {
SearchRequest searchRequest = new SearchRequest(GeoIpDownloader.DATABASES_INDEX);
String id = String.format(Locale.ROOT, "%s_%d_%d", databaseName, chunk, metadata.getLastUpdate());
String id = String.format(Locale.ROOT, "%s_%d_%d", databaseName, chunk, metadata.lastUpdate());
searchRequest.source().query(new TermQueryBuilder("_id", id));
// At most once a day a few searches may be executed to fetch the new files,

View File

@ -147,7 +147,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask {
void processDatabase(Map<String, Object> databaseInfo) {
String name = databaseInfo.get("name").toString().replace(".tgz", "") + ".mmdb";
String md5 = (String) databaseInfo.get("md5_hash");
if (state.contains(name) && Objects.equals(md5, state.get(name).getMd5())) {
if (state.contains(name) && Objects.equals(md5, state.get(name).md5())) {
updateTimestamp(name, state.get(name));
return;
}
@ -160,7 +160,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask {
}
long start = System.currentTimeMillis();
try (InputStream is = httpClient.get(url)) {
int firstChunk = state.contains(name) ? state.get(name).getLastChunk() + 1 : 0;
int firstChunk = state.contains(name) ? state.get(name).lastChunk() + 1 : 0;
int lastChunk = indexChunks(name, is, firstChunk, md5, start);
if (lastChunk > firstChunk) {
state = state.put(name, new Metadata(start, firstChunk, lastChunk - 1, md5, start));
@ -192,10 +192,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask {
// visible for testing
protected void updateTimestamp(String name, Metadata old) {
logger.debug("geoip database [{}] is up to date, updated timestamp", name);
state = state.put(
name,
new Metadata(old.getLastUpdate(), old.getFirstChunk(), old.getLastChunk(), old.getMd5(), System.currentTimeMillis())
);
state = state.put(name, new Metadata(old.lastUpdate(), old.firstChunk(), old.lastChunk(), old.md5(), System.currentTimeMillis()));
stats = stats.skippedDownload();
updateTaskState();
}
@ -279,10 +276,10 @@ public class GeoIpDownloader extends AllocatedPersistentTask {
.peek(e -> {
String name = e.getKey();
Metadata meta = e.getValue();
deleteOldChunks(name, meta.getLastChunk() + 1);
deleteOldChunks(name, meta.lastChunk() + 1);
state = state.put(
name,
new Metadata(meta.getLastUpdate(), meta.getFirstChunk(), meta.getLastChunk(), meta.getMd5(), meta.getLastCheck() - 1)
new Metadata(meta.lastUpdate(), meta.firstChunk(), meta.lastChunk(), meta.md5(), meta.lastCheck() - 1)
);
updateTaskState();
})

View File

@ -139,7 +139,7 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable {
});
}
static class Metadata implements ToXContentObject {
record Metadata(long lastUpdate, int firstChunk, int lastChunk, String md5, long lastCheck) implements ToXContentObject {
static final String NAME = GEOIP_DOWNLOADER + "-metadata";
private static final ParseField LAST_CHECK = new ParseField("last_check");
@ -176,22 +176,8 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable {
}
}
private final long lastUpdate;
private final int firstChunk;
private final int lastChunk;
private final String md5;
private final long lastCheck;
Metadata(long lastUpdate, int firstChunk, int lastChunk, String md5, long lastCheck) {
this.lastUpdate = lastUpdate;
this.firstChunk = firstChunk;
this.lastChunk = lastChunk;
this.md5 = Objects.requireNonNull(md5);
this.lastCheck = lastCheck;
}
public long getLastUpdate() {
return lastUpdate;
Metadata {
Objects.requireNonNull(md5);
}
public boolean isCloseToExpiration() {
@ -203,39 +189,6 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable {
return Instant.ofEpochMilli(lastCheck).isAfter(Instant.now().minus(valid.getMillis(), ChronoUnit.MILLIS));
}
public int getFirstChunk() {
return firstChunk;
}
public int getLastChunk() {
return lastChunk;
}
public String getMd5() {
return md5;
}
public long getLastCheck() {
return lastCheck;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Metadata metadata = (Metadata) o;
return lastUpdate == metadata.lastUpdate
&& firstChunk == metadata.firstChunk
&& lastChunk == metadata.lastChunk
&& lastCheck == metadata.lastCheck
&& md5.equals(metadata.md5);
}
@Override
public int hashCode() {
return Objects.hash(lastUpdate, firstChunk, lastChunk, md5, lastCheck);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();

View File

@ -103,21 +103,5 @@ class TarInputStream extends FilterInputStream {
}
}
static class TarEntry {
private final String name;
private final boolean notFile;
TarEntry(String name, boolean notFile) {
this.name = name;
this.notFile = notFile;
}
public String getName() {
return name;
}
public boolean isNotFile() {
return notFile;
}
}
record TarEntry(String name, boolean notFile) {}
}

View File

@ -249,8 +249,8 @@ public class GeoIpDownloaderTests extends ESTestCase {
) {
@Override
void updateTaskState() {
assertEquals(0, state.get("test").getFirstChunk());
assertEquals(10, state.get("test").getLastChunk());
assertEquals(0, state.get("test").firstChunk());
assertEquals(10, state.get("test").lastChunk());
}
@Override
@ -295,8 +295,8 @@ public class GeoIpDownloaderTests extends ESTestCase {
) {
@Override
void updateTaskState() {
assertEquals(9, state.get("test.mmdb").getFirstChunk());
assertEquals(10, state.get("test.mmdb").getLastChunk());
assertEquals(9, state.get("test.mmdb").firstChunk());
assertEquals(10, state.get("test.mmdb").lastChunk());
}
@Override

View File

@ -36,11 +36,11 @@ public class TarInputStreamTests extends ESTestCase {
assertNotNull(is);
for (Entry entry : entries) {
TarInputStream.TarEntry tarEntry = tis.getNextEntry();
assertEquals(entry.name, tarEntry.getName());
assertEquals(entry.name, tarEntry.name());
if (entry.notFile == false) {
assertEquals(entry.data, new String(tis.readAllBytes(), StandardCharsets.UTF_8));
}
assertEquals(entry.notFile, tarEntry.isNotFile());
assertEquals(entry.notFile, tarEntry.notFile());
}
assertNull(tis.getNextEntry());
}

View File

@ -92,18 +92,18 @@ public class DeviceTypeParser {
String deviceType = null;
switch (patternKey) {
case OS_PARSERS:
if (os != null && os.name != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), os.name);
if (os != null && os.name() != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), os.name());
}
break;
case BROWSER_PARSER:
if (userAgent != null && userAgent.name != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), userAgent.name);
if (userAgent != null && userAgent.name() != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), userAgent.name());
}
break;
case DEVICE_PARSER:
if (device != null && device.name != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), device.name);
if (device != null && device.name() != null) {
deviceType = findMatch(deviceTypePatterns.get(patternKey), device.name());
}
break;
default:

View File

@ -12,8 +12,6 @@ import org.elasticsearch.common.cache.Cache;
import org.elasticsearch.common.cache.CacheBuilder;
import org.elasticsearch.ingest.useragent.UserAgentParser.Details;
import java.util.Objects;
class UserAgentCache {
private final Cache<CompositeCacheKey, Details> cache;
@ -29,26 +27,5 @@ class UserAgentCache {
cache.put(new CompositeCacheKey(parserName, userAgent), details);
}
private static final class CompositeCacheKey {
private final String parserName;
private final String userAgent;
CompositeCacheKey(String parserName, String userAgent) {
this.parserName = parserName;
this.userAgent = userAgent;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CompositeCacheKey cck) {
return parserName.equals(cck.parserName) && userAgent.equals(cck.userAgent);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(parserName, userAgent);
}
}
private record CompositeCacheKey(String parserName, String userAgent) {}
}

View File

@ -202,58 +202,21 @@ final class UserAgentParser {
return null;
}
static final class Details {
public final VersionedName userAgent;
public final VersionedName operatingSystem;
public final VersionedName device;
public final String deviceType;
record Details(VersionedName userAgent, VersionedName operatingSystem, VersionedName device, String deviceType) {}
Details(VersionedName userAgent, VersionedName operatingSystem, VersionedName device, String deviceType) {
this.userAgent = userAgent;
this.operatingSystem = operatingSystem;
this.device = device;
this.deviceType = deviceType;
}
}
static final class VersionedName {
public final String name;
public final String major;
public final String minor;
public final String patch;
public final String build;
VersionedName(String name, String major, String minor, String patch, String build) {
this.name = name;
this.major = major;
this.minor = minor;
this.patch = patch;
this.build = build;
}
}
record VersionedName(String name, String major, String minor, String patch, String build) {}
/**
* One of: user agent, operating system, device
*/
static final class UserAgentSubpattern {
private final Pattern pattern;
private final String nameReplacement, v1Replacement, v2Replacement, v3Replacement, v4Replacement;
UserAgentSubpattern(
Pattern pattern,
String nameReplacement,
String v1Replacement,
String v2Replacement,
String v3Replacement,
String v4Replacement
) {
this.pattern = pattern;
this.nameReplacement = nameReplacement;
this.v1Replacement = v1Replacement;
this.v2Replacement = v2Replacement;
this.v3Replacement = v3Replacement;
this.v4Replacement = v4Replacement;
}
record UserAgentSubpattern(
Pattern pattern,
String nameReplacement,
String v1Replacement,
String v2Replacement,
String v3Replacement,
String v4Replacement
) {
public VersionedName match(String agentString) {
String name = null, major = null, minor = null, patch = null, build = null;

View File

@ -89,22 +89,22 @@ public class UserAgentProcessor extends AbstractProcessor {
uaDetails.put("original", userAgent);
break;
case NAME:
if (uaClient.userAgent != null && uaClient.userAgent.name != null) {
uaDetails.put("name", uaClient.userAgent.name);
if (uaClient.userAgent() != null && uaClient.userAgent().name() != null) {
uaDetails.put("name", uaClient.userAgent().name());
} else {
uaDetails.put("name", "Other");
}
break;
case VERSION:
StringBuilder version = new StringBuilder();
if (uaClient.userAgent != null && uaClient.userAgent.major != null) {
version.append(uaClient.userAgent.major);
if (uaClient.userAgent.minor != null) {
version.append(".").append(uaClient.userAgent.minor);
if (uaClient.userAgent.patch != null) {
version.append(".").append(uaClient.userAgent.patch);
if (uaClient.userAgent.build != null) {
version.append(".").append(uaClient.userAgent.build);
if (uaClient.userAgent() != null && uaClient.userAgent().major() != null) {
version.append(uaClient.userAgent().major());
if (uaClient.userAgent().minor() != null) {
version.append(".").append(uaClient.userAgent().minor());
if (uaClient.userAgent().patch() != null) {
version.append(".").append(uaClient.userAgent().patch());
if (uaClient.userAgent().build() != null) {
version.append(".").append(uaClient.userAgent().build());
}
}
}
@ -112,24 +112,24 @@ public class UserAgentProcessor extends AbstractProcessor {
}
break;
case OS:
if (uaClient.operatingSystem != null) {
if (uaClient.operatingSystem() != null) {
Map<String, String> osDetails = new HashMap<>(3);
if (uaClient.operatingSystem.name != null) {
osDetails.put("name", uaClient.operatingSystem.name);
if (uaClient.operatingSystem().name() != null) {
osDetails.put("name", uaClient.operatingSystem().name());
StringBuilder sb = new StringBuilder();
if (uaClient.operatingSystem.major != null) {
sb.append(uaClient.operatingSystem.major);
if (uaClient.operatingSystem.minor != null) {
sb.append(".").append(uaClient.operatingSystem.minor);
if (uaClient.operatingSystem.patch != null) {
sb.append(".").append(uaClient.operatingSystem.patch);
if (uaClient.operatingSystem.build != null) {
sb.append(".").append(uaClient.operatingSystem.build);
if (uaClient.operatingSystem().major() != null) {
sb.append(uaClient.operatingSystem().major());
if (uaClient.operatingSystem().minor() != null) {
sb.append(".").append(uaClient.operatingSystem().minor());
if (uaClient.operatingSystem().patch() != null) {
sb.append(".").append(uaClient.operatingSystem().patch());
if (uaClient.operatingSystem().build() != null) {
sb.append(".").append(uaClient.operatingSystem().build());
}
}
}
osDetails.put("version", sb.toString());
osDetails.put("full", uaClient.operatingSystem.name + " " + sb.toString());
osDetails.put("full", uaClient.operatingSystem().name() + " " + sb.toString());
}
uaDetails.put("os", osDetails);
}
@ -137,16 +137,16 @@ public class UserAgentProcessor extends AbstractProcessor {
break;
case DEVICE:
Map<String, String> deviceDetails = new HashMap<>(1);
if (uaClient.device != null && uaClient.device.name != null) {
deviceDetails.put("name", uaClient.device.name);
if (uaClient.device() != null && uaClient.device().name() != null) {
deviceDetails.put("name", uaClient.device().name());
if (extractDeviceType) {
deviceDetails.put("type", uaClient.deviceType);
deviceDetails.put("type", uaClient.deviceType());
}
} else {
deviceDetails.put("name", "Other");
if (extractDeviceType) {
if (uaClient.deviceType != null) {
deviceDetails.put("type", uaClient.deviceType);
if (uaClient.deviceType() != null) {
deviceDetails.put("type", uaClient.deviceType());
} else {
deviceDetails.put("type", "Other");
}

View File

@ -37,17 +37,6 @@ package org.elasticsearch.painless.spi.annotation;
* ...
* }
*/
public class AugmentedAnnotation {
public record AugmentedAnnotation(String augmentedCanonicalClassName) {
public static final String NAME = "augmented";
private final String augmentedCanonicalClassName;
public AugmentedAnnotation(String augmentedCanonicalClassName) {
this.augmentedCanonicalClassName = augmentedCanonicalClassName;
}
public String getAugmentedCanonicalClassName() {
return augmentedCanonicalClassName;
}
}

View File

@ -8,17 +8,6 @@
package org.elasticsearch.painless.spi.annotation;
public class DeprecatedAnnotation {
public record DeprecatedAnnotation(String message) {
public static final String NAME = "deprecated";
private final String message;
public DeprecatedAnnotation(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}

View File

@ -16,9 +16,8 @@ import java.util.List;
* Format: {@code inject_constant["1=foo_compiler_setting", 2="bar_compiler_setting"]} injects "foo_compiler_setting and
* "bar_compiler_setting" as the first two arguments (other than receiver reference for instance methods) to the annotated method.
*/
public class InjectConstantAnnotation {
public record InjectConstantAnnotation(List<String> injects) {
public static final String NAME = "inject_constant";
public final List<String> injects;
public InjectConstantAnnotation(List<String> injects) {
this.injects = Collections.unmodifiableList(injects);

View File

@ -14,31 +14,8 @@ import java.util.Map;
public class AnnotationTestObject {
public static class TestAnnotation {
public record TestAnnotation(String one, String two, String three) {
public static final String NAME = "test_annotation";
private final String one;
private final String two;
private final String three;
public TestAnnotation(String one, String two, String three) {
this.one = one;
this.two = two;
this.three = three;
}
public String getOne() {
return one;
}
public String getTwo() {
return two;
}
public String getThree() {
return three;
}
}
public static class TestAnnotationParser implements WhitelistAnnotationParser {

View File

@ -68,7 +68,7 @@ public class WhitelistLoaderTests extends ESTestCase {
if ("deprecatedMethod".equals(whitelistMethod.methodName)) {
assertEquals(
"use another method",
((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).getMessage()
((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).message()
);
assertEquals(1, whitelistMethod.painlessAnnotations.size());
++count;
@ -78,9 +78,9 @@ public class WhitelistLoaderTests extends ESTestCase {
AnnotationTestObject.TestAnnotation ta = ((AnnotationTestObject.TestAnnotation) whitelistMethod.painlessAnnotations.get(
AnnotationTestObject.TestAnnotation.class
));
assertEquals("one", ta.getOne());
assertEquals("two", ta.getTwo());
assertEquals("three", ta.getThree());
assertEquals("one", ta.one());
assertEquals("two", ta.two());
assertEquals("three", ta.three());
assertEquals(1, whitelistMethod.painlessAnnotations.size());
++count;
}
@ -88,14 +88,14 @@ public class WhitelistLoaderTests extends ESTestCase {
if ("annotatedMultipleMethod".equals(whitelistMethod.methodName)) {
assertEquals(
"test",
((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).getMessage()
((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).message()
);
AnnotationTestObject.TestAnnotation ta = ((AnnotationTestObject.TestAnnotation) whitelistMethod.painlessAnnotations.get(
AnnotationTestObject.TestAnnotation.class
));
assertEquals("one", ta.getOne());
assertEquals("two", ta.getTwo());
assertEquals("three", ta.getThree());
assertEquals("one", ta.one());
assertEquals("two", ta.two());
assertEquals("three", ta.three());
assertEquals(2, whitelistMethod.painlessAnnotations.size());
++count;
}

View File

@ -35,7 +35,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ -193,14 +192,7 @@ public class JavadocExtractor {
return type;
}
public static class MethodSignature {
public final String name;
public final List<String> parameterTypes;
public MethodSignature(String name, List<String> parameterTypes) {
this.name = name;
this.parameterTypes = parameterTypes;
}
public record MethodSignature(String name, List<String> parameterTypes) {
public static MethodSignature fromDeclaration(MethodDeclaration declaration) {
return new MethodSignature(
@ -208,29 +200,9 @@ public class JavadocExtractor {
declaration.getParameters().stream().map(p -> stripTypeParameters(p.getType().asString())).collect(Collectors.toList())
);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if ((o instanceof MethodSignature) == false) return false;
MethodSignature that = (MethodSignature) o;
return Objects.equals(name, that.name) && Objects.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
return Objects.hash(name, parameterTypes);
}
}
public static class ParsedMethod {
public final ParsedJavadoc javadoc;
public final List<String> parameterNames;
public ParsedMethod(ParsedJavadoc javadoc, List<String> parameterNames) {
this.javadoc = javadoc;
this.parameterNames = parameterNames;
}
public record ParsedMethod(ParsedJavadoc javadoc, List<String> parameterNames) {
public ParsedMethod asAugmented() {
if (parameterNames.size() == 0) {

View File

@ -232,8 +232,8 @@ public class PainlessInfoJson {
}
}
if (parsedMethod != null) {
javadoc = parsedMethod.javadoc;
parameterNames = parsedMethod.parameterNames;
javadoc = parsedMethod.javadoc();
parameterNames = parsedMethod.parameterNames();
}
methods.add(
@ -317,8 +317,8 @@ public class PainlessInfoJson {
parsedMethod = extractor.parseClass(info.getDeclaring()).getConstructor(parameterTypes);
}
if (parsedMethod != null) {
parameterNames = parsedMethod.parameterNames;
javadoc = parsedMethod.javadoc;
parameterNames = parsedMethod.parameterNames();
javadoc = parsedMethod.javadoc();
}
constructors.add(new Constructor(info.getDeclaring(), parameterTypes, parameterNames, javadoc));

View File

@ -214,7 +214,7 @@ final class Compiler {
new PainlessSemanticHeaderPhase().visitClass(root, scriptScope);
new PainlessSemanticAnalysisPhase().visitClass(root, scriptScope);
new PainlessUserTreeToIRTreePhase().visitClass(root, scriptScope);
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode();
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode();
new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null);
new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null);
new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope);
@ -249,7 +249,7 @@ final class Compiler {
new PainlessSemanticHeaderPhase().visitClass(root, scriptScope);
new PainlessSemanticAnalysisPhase().visitClass(root, scriptScope);
new PainlessUserTreeToIRTreePhase().visitClass(root, scriptScope);
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode();
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode();
new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null);
new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null);
new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope);
@ -287,7 +287,7 @@ final class Compiler {
irPhaseVisitor.visitClass(root, scriptScope);
}
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode();
ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode();
new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null);
new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null);
new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope);

View File

@ -256,7 +256,7 @@ public final class Def {
);
}
MethodHandle handle = painlessMethod.methodHandle;
MethodHandle handle = painlessMethod.methodHandle();
Object[] injections = PainlessLookupUtility.buildInjections(painlessMethod, constants);
if (injections.length > 0) {
@ -298,7 +298,7 @@ public final class Def {
);
}
MethodHandle handle = method.methodHandle;
MethodHandle handle = method.methodHandle();
Object[] injections = PainlessLookupUtility.buildInjections(method, constants);
if (injections.length > 0) {
@ -313,7 +313,7 @@ public final class Def {
if (lambdaArgs.get(i - 1)) {
Def.Encoding defEncoding = new Encoding((String) args[upTo++]);
MethodHandle filter;
Class<?> interfaceType = method.typeParameters.get(i - 1 - replaced - (defEncoding.needsInstance ? 1 : 0));
Class<?> interfaceType = method.typeParameters().get(i - 1 - replaced - (defEncoding.needsInstance ? 1 : 0));
if (defEncoding.isStatic) {
// the implementation is strongly typed, now that we know the interface type,
// we have everything.
@ -385,7 +385,7 @@ public final class Def {
if (interfaceMethod == null) {
throw new IllegalArgumentException("Class [" + interfaceClass + "] is not a functional interface");
}
int arity = interfaceMethod.typeParameters.size();
int arity = interfaceMethod.typeParameters().size();
PainlessMethod implMethod = painlessLookup.lookupRuntimePainlessMethod(receiverClass, name, arity);
if (implMethod == null) {
throw new IllegalArgumentException(
@ -399,8 +399,8 @@ public final class Def {
constants,
methodHandlesLookup,
interfaceType,
PainlessLookupUtility.typeToCanonicalTypeName(implMethod.targetClass),
implMethod.javaMethod.getName(),
PainlessLookupUtility.typeToCanonicalTypeName(implMethod.targetClass()),
implMethod.javaMethod().getName(),
1,
false
);

View File

@ -84,8 +84,8 @@ public class FunctionRef {
);
}
String interfaceMethodName = interfaceMethod.javaMethod.getName();
MethodType interfaceMethodType = interfaceMethod.methodType.dropParameterTypes(0, 1);
String interfaceMethodName = interfaceMethod.javaMethod().getName();
MethodType interfaceMethodType = interfaceMethod.methodType().dropParameterTypes(0, 1);
String delegateClassName;
boolean isDelegateInterface;
boolean isDelegateAugmented;
@ -96,7 +96,7 @@ public class FunctionRef {
Class<?> delegateMethodReturnType;
List<Class<?>> delegateMethodParameters;
int interfaceTypeParametersSize = interfaceMethod.typeParameters.size();
int interfaceTypeParametersSize = interfaceMethod.typeParameters().size();
if ("this".equals(typeName)) {
Objects.requireNonNull(functionTable);
@ -160,16 +160,16 @@ public class FunctionRef {
);
}
delegateClassName = painlessConstructor.javaConstructor.getDeclaringClass().getName();
delegateClassName = painlessConstructor.javaConstructor().getDeclaringClass().getName();
isDelegateInterface = false;
isDelegateAugmented = false;
delegateInvokeType = H_NEWINVOKESPECIAL;
delegateMethodName = PainlessLookupUtility.CONSTRUCTOR_NAME;
delegateMethodType = painlessConstructor.methodType;
delegateMethodType = painlessConstructor.methodType();
delegateInjections = new Object[0];
delegateMethodReturnType = painlessConstructor.javaConstructor.getDeclaringClass();
delegateMethodParameters = painlessConstructor.typeParameters;
delegateMethodReturnType = painlessConstructor.javaConstructor().getDeclaringClass();
delegateMethodParameters = painlessConstructor.typeParameters();
} else {
if (numberOfCaptures != 0 && numberOfCaptures != 1) {
throw new IllegalStateException("internal error");
@ -225,11 +225,11 @@ public class FunctionRef {
);
}
delegateClassName = painlessMethod.javaMethod.getDeclaringClass().getName();
isDelegateInterface = painlessMethod.javaMethod.getDeclaringClass().isInterface();
isDelegateAugmented = painlessMethod.javaMethod.getDeclaringClass() != painlessMethod.targetClass;
delegateClassName = painlessMethod.javaMethod().getDeclaringClass().getName();
isDelegateInterface = painlessMethod.javaMethod().getDeclaringClass().isInterface();
isDelegateAugmented = painlessMethod.javaMethod().getDeclaringClass() != painlessMethod.targetClass();
if (Modifier.isStatic(painlessMethod.javaMethod.getModifiers())) {
if (Modifier.isStatic(painlessMethod.javaMethod().getModifiers())) {
delegateInvokeType = H_INVOKESTATIC;
} else if (isDelegateInterface) {
delegateInvokeType = H_INVOKEINTERFACE;
@ -237,43 +237,43 @@ public class FunctionRef {
delegateInvokeType = H_INVOKEVIRTUAL;
}
delegateMethodName = painlessMethod.javaMethod.getName();
delegateMethodType = painlessMethod.methodType;
delegateMethodName = painlessMethod.javaMethod().getName();
delegateMethodType = painlessMethod.methodType();
// interfaces that override a method from Object receive the method handle for
// Object rather than for the interface; we change the first parameter to match
// the interface type so the constant interface method reference is correctly
// written to the constant pool
if (delegateInvokeType != H_INVOKESTATIC
&& painlessMethod.javaMethod.getDeclaringClass() != painlessMethod.methodType.parameterType(0)) {
if (painlessMethod.methodType.parameterType(0) != Object.class) {
&& painlessMethod.javaMethod().getDeclaringClass() != painlessMethod.methodType().parameterType(0)) {
if (painlessMethod.methodType().parameterType(0) != Object.class) {
throw new IllegalStateException("internal error");
}
delegateMethodType = delegateMethodType.changeParameterType(0, painlessMethod.javaMethod.getDeclaringClass());
delegateMethodType = delegateMethodType.changeParameterType(0, painlessMethod.javaMethod().getDeclaringClass());
}
delegateInjections = PainlessLookupUtility.buildInjections(painlessMethod, constants);
delegateMethodReturnType = painlessMethod.returnType;
delegateMethodReturnType = painlessMethod.returnType();
if (delegateMethodType.parameterList().size() > painlessMethod.typeParameters.size()) {
delegateMethodParameters = new ArrayList<>(painlessMethod.typeParameters);
if (delegateMethodType.parameterList().size() > painlessMethod.typeParameters().size()) {
delegateMethodParameters = new ArrayList<>(painlessMethod.typeParameters());
delegateMethodParameters.add(0, delegateMethodType.parameterType(0));
} else {
delegateMethodParameters = painlessMethod.typeParameters;
delegateMethodParameters = painlessMethod.typeParameters();
}
}
if (location != null) {
for (int typeParameter = 0; typeParameter < interfaceTypeParametersSize; ++typeParameter) {
Class<?> from = interfaceMethod.typeParameters.get(typeParameter);
Class<?> from = interfaceMethod.typeParameters().get(typeParameter);
Class<?> to = delegateMethodParameters.get(numberOfCaptures + typeParameter);
AnalyzerCaster.getLegalCast(location, from, to, false, true);
}
if (interfaceMethod.returnType != void.class) {
AnalyzerCaster.getLegalCast(location, delegateMethodReturnType, interfaceMethod.returnType, false, true);
if (interfaceMethod.returnType() != void.class) {
AnalyzerCaster.getLegalCast(location, delegateMethodReturnType, interfaceMethod.returnType(), false, true);
}
}

View File

@ -440,26 +440,26 @@ public final class MethodWriter extends GeneratorAdapter {
}
public void invokeMethodCall(PainlessMethod painlessMethod) {
Type type = Type.getType(painlessMethod.javaMethod.getDeclaringClass());
Method method = Method.getMethod(painlessMethod.javaMethod);
Type type = Type.getType(painlessMethod.javaMethod().getDeclaringClass());
Method method = Method.getMethod(painlessMethod.javaMethod());
if (Modifier.isStatic(painlessMethod.javaMethod.getModifiers())) {
if (Modifier.isStatic(painlessMethod.javaMethod().getModifiers())) {
// invokeStatic assumes that the owner class is not an interface, so this is a
// special case for interfaces where the interface method boolean needs to be set to
// true to reference the appropriate class constant when calling a static interface
// method since java 8 did not check, but java 9 and 10 do
if (painlessMethod.javaMethod.getDeclaringClass().isInterface()) {
if (painlessMethod.javaMethod().getDeclaringClass().isInterface()) {
visitMethodInsn(
Opcodes.INVOKESTATIC,
type.getInternalName(),
painlessMethod.javaMethod.getName(),
painlessMethod.javaMethod().getName(),
method.getDescriptor(),
true
);
} else {
invokeStatic(type, method);
}
} else if (painlessMethod.javaMethod.getDeclaringClass().isInterface()) {
} else if (painlessMethod.javaMethod().getDeclaringClass().isInterface()) {
invokeInterface(type, method);
} else {
invokeVirtual(type, method);

View File

@ -56,11 +56,11 @@ public class PainlessContextClassBindingInfo implements Writeable, ToXContentObj
public PainlessContextClassBindingInfo(PainlessClassBinding painlessClassBinding) {
this(
painlessClassBinding.javaMethod.getDeclaringClass().getName(),
painlessClassBinding.javaMethod.getName(),
painlessClassBinding.returnType.getName(),
painlessClassBinding.javaConstructor.getParameterCount(),
painlessClassBinding.typeParameters.stream().map(Class::getName).collect(Collectors.toList())
painlessClassBinding.javaMethod().getDeclaringClass().getName(),
painlessClassBinding.javaMethod().getName(),
painlessClassBinding.returnType().getName(),
painlessClassBinding.javaConstructor().getParameterCount(),
painlessClassBinding.typeParameters().stream().map(Class::getName).collect(Collectors.toList())
);
}

View File

@ -47,8 +47,11 @@ public class PainlessContextConstructorInfo implements Writeable, ToXContentObje
public PainlessContextConstructorInfo(PainlessConstructor painlessConstructor) {
this(
painlessConstructor.javaConstructor.getDeclaringClass().getName(),
painlessConstructor.typeParameters.stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList())
painlessConstructor.javaConstructor().getDeclaringClass().getName(),
painlessConstructor.typeParameters()
.stream()
.map(c -> PainlessContextTypeInfo.getType(c.getName()))
.collect(Collectors.toList())
);
}

View File

@ -45,9 +45,9 @@ public class PainlessContextFieldInfo implements Writeable, ToXContentObject {
public PainlessContextFieldInfo(PainlessField painlessField) {
this(
painlessField.javaField.getDeclaringClass().getName(),
painlessField.javaField.getName(),
PainlessContextTypeInfo.getType(painlessField.typeParameter.getName())
painlessField.javaField().getDeclaringClass().getName(),
painlessField.javaField().getName(),
PainlessContextTypeInfo.getType(painlessField.typeParameter().getName())
);
}

View File

@ -53,10 +53,10 @@ public class PainlessContextInstanceBindingInfo implements Writeable, ToXContent
public PainlessContextInstanceBindingInfo(PainlessInstanceBinding painlessInstanceBinding) {
this(
painlessInstanceBinding.javaMethod.getDeclaringClass().getName(),
painlessInstanceBinding.javaMethod.getName(),
painlessInstanceBinding.returnType.getName(),
painlessInstanceBinding.typeParameters.stream().map(Class::getName).collect(Collectors.toList())
painlessInstanceBinding.javaMethod().getDeclaringClass().getName(),
painlessInstanceBinding.javaMethod().getName(),
painlessInstanceBinding.returnType().getName(),
painlessInstanceBinding.typeParameters().stream().map(Class::getName).collect(Collectors.toList())
);
}

View File

@ -53,10 +53,10 @@ public class PainlessContextMethodInfo implements Writeable, ToXContentObject {
public PainlessContextMethodInfo(PainlessMethod painlessMethod) {
this(
painlessMethod.javaMethod.getDeclaringClass().getName(),
painlessMethod.javaMethod.getName(),
PainlessContextTypeInfo.getType(painlessMethod.returnType.getName()),
painlessMethod.typeParameters.stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList())
painlessMethod.javaMethod().getDeclaringClass().getName(),
painlessMethod.javaMethod().getName(),
PainlessContextTypeInfo.getType(painlessMethod.returnType().getName()),
painlessMethod.typeParameters().stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList())
);
}

View File

@ -14,29 +14,13 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
public class PainlessClassBinding {
public final Constructor<?> javaConstructor;
public final Method javaMethod;
public final Class<?> returnType;
public final List<Class<?>> typeParameters;
public final Map<Class<?>, Object> annotations;
PainlessClassBinding(
Constructor<?> javaConstructor,
Method javaMethod,
Class<?> returnType,
List<Class<?>> typeParameters,
Map<Class<?>, Object> annotations
) {
this.javaConstructor = javaConstructor;
this.javaMethod = javaMethod;
this.returnType = returnType;
this.typeParameters = typeParameters;
this.annotations = annotations;
}
public record PainlessClassBinding(
Constructor<?> javaConstructor,
Method javaMethod,
Class<?> returnType,
List<Class<?>> typeParameters,
Map<Class<?>, Object> annotations
) {
@Override
public boolean equals(Object object) {
@ -49,7 +33,6 @@ public class PainlessClassBinding {
}
PainlessClassBinding that = (PainlessClassBinding) object;
return Objects.equals(javaConstructor, that.javaConstructor)
&& Objects.equals(javaMethod, that.javaMethod)
&& Objects.equals(returnType, that.returnType)

View File

@ -15,27 +15,13 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
public class PainlessConstructor {
public final Constructor<?> javaConstructor;
public final List<Class<?>> typeParameters;
public final MethodHandle methodHandle;
public final MethodType methodType;
public final Map<Class<?>, Object> annotations;
PainlessConstructor(
Constructor<?> javaConstructor,
List<Class<?>> typeParameters,
MethodHandle methodHandle,
MethodType methodType,
Map<Class<?>, Object> annotations
) {
this.javaConstructor = javaConstructor;
this.typeParameters = typeParameters;
this.methodHandle = methodHandle;
this.methodType = methodType;
this.annotations = annotations;
}
public record PainlessConstructor(
Constructor<?> javaConstructor,
List<Class<?>> typeParameters,
MethodHandle methodHandle,
MethodType methodType,
Map<Class<?>, Object> annotations
) {
@Override
public boolean equals(Object object) {
@ -48,7 +34,6 @@ public class PainlessConstructor {
}
PainlessConstructor that = (PainlessConstructor) object;
return Objects.equals(javaConstructor, that.javaConstructor)
&& Objects.equals(typeParameters, that.typeParameters)
&& Objects.equals(methodType, that.methodType)

View File

@ -13,30 +13,13 @@ import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;
public final class PainlessField {
public final Field javaField;
public final Class<?> typeParameter;
public final Map<Class<?>, Object> annotations;
public final MethodHandle getterMethodHandle;
public final MethodHandle setterMethodHandle;
PainlessField(
Field javaField,
Class<?> typeParameter,
Map<Class<?>, Object> annotations,
MethodHandle getterMethodHandle,
MethodHandle setterMethodHandle
) {
this.javaField = javaField;
this.typeParameter = typeParameter;
this.annotations = annotations;
this.getterMethodHandle = getterMethodHandle;
this.setterMethodHandle = setterMethodHandle;
}
public record PainlessField(
Field javaField,
Class<?> typeParameter,
Map<Class<?>, Object> annotations,
MethodHandle getterMethodHandle,
MethodHandle setterMethodHandle
) {
@Override
public boolean equals(Object object) {
@ -49,7 +32,6 @@ public final class PainlessField {
}
PainlessField that = (PainlessField) object;
return Objects.equals(javaField, that.javaField)
&& Objects.equals(typeParameter, that.typeParameter)
&& Objects.equals(annotations, that.annotations);

View File

@ -11,53 +11,13 @@ package org.elasticsearch.painless.lookup;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class PainlessInstanceBinding {
public record PainlessInstanceBinding(
Object targetInstance,
Method javaMethod,
Class<?> returnType,
List<Class<?>> typeParameters,
Map<Class<?>, Object> annotations
) {
public final Object targetInstance;
public final Method javaMethod;
public final Class<?> returnType;
public final List<Class<?>> typeParameters;
public final Map<Class<?>, Object> annotations;
PainlessInstanceBinding(
Object targetInstance,
Method javaMethod,
Class<?> returnType,
List<Class<?>> typeParameters,
Map<Class<?>, Object> annotations
) {
this.targetInstance = targetInstance;
this.javaMethod = javaMethod;
this.returnType = returnType;
this.typeParameters = typeParameters;
this.annotations = annotations;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
PainlessInstanceBinding that = (PainlessInstanceBinding) object;
return targetInstance == that.targetInstance
&& Objects.equals(javaMethod, that.javaMethod)
&& Objects.equals(returnType, that.returnType)
&& Objects.equals(typeParameters, that.typeParameters)
&& Objects.equals(annotations, that.annotations);
}
@Override
public int hashCode() {
return Objects.hash(targetInstance, javaMethod, returnType, typeParameters);
}
}

View File

@ -523,7 +523,7 @@ public final class PainlessLookupBuilder {
+ "[["
+ targetCanonicalClassName
+ "], "
+ typesToCanonicalTypeNames(existingPainlessConstructor.typeParameters)
+ typesToCanonicalTypeNames(existingPainlessConstructor.typeParameters())
+ "]"
);
}
@ -767,7 +767,7 @@ public final class PainlessLookupBuilder {
// injections alter the type parameters required for the user to call this method, since some are injected by compiler
if (annotations.containsKey(InjectConstantAnnotation.class)) {
int numInjections = ((InjectConstantAnnotation) annotations.get(InjectConstantAnnotation.class)).injects.size();
int numInjections = ((InjectConstantAnnotation) annotations.get(InjectConstantAnnotation.class)).injects().size();
if (numInjections > 0) {
typeParameters.subList(0, numInjections).clear();
@ -880,9 +880,9 @@ public final class PainlessLookupBuilder {
+ methodName
+ "], "
+ "["
+ typeToCanonicalTypeName(existingPainlessMethod.returnType)
+ typeToCanonicalTypeName(existingPainlessMethod.returnType())
+ "], "
+ typesToCanonicalTypeNames(existingPainlessMethod.typeParameters)
+ typesToCanonicalTypeNames(existingPainlessMethod.typeParameters())
+ "]"
);
}
@ -920,7 +920,7 @@ public final class PainlessLookupBuilder {
}
String augmentedCanonicalClassName = annotations.containsKey(AugmentedAnnotation.class)
? ((AugmentedAnnotation) annotations.get(AugmentedAnnotation.class)).getAugmentedCanonicalClassName()
? ((AugmentedAnnotation) annotations.get(AugmentedAnnotation.class)).augmentedCanonicalClassName()
: null;
Class<?> augmentedClass = null;
@ -1119,9 +1119,9 @@ public final class PainlessLookupBuilder {
+ "[["
+ targetCanonicalClassName
+ "], ["
+ existingPainlessField.javaField.getName()
+ existingPainlessField.javaField().getName()
+ "], "
+ typeToCanonicalTypeName(existingPainlessField.typeParameter)
+ typeToCanonicalTypeName(existingPainlessField.typeParameter())
+ "] "
+ "with the same name and different type parameters"
);
@ -1162,9 +1162,9 @@ public final class PainlessLookupBuilder {
+ "[["
+ targetCanonicalClassName
+ "], ["
+ existingPainlessField.javaField.getName()
+ existingPainlessField.javaField().getName()
+ "], "
+ typeToCanonicalTypeName(existingPainlessField.typeParameter)
+ typeToCanonicalTypeName(existingPainlessField.typeParameter())
+ "] "
+ "with the same name and different type parameters"
);
@ -1433,9 +1433,9 @@ public final class PainlessLookupBuilder {
+ methodName
+ "], "
+ "["
+ typeToCanonicalTypeName(existingImportedPainlessMethod.returnType)
+ typeToCanonicalTypeName(existingImportedPainlessMethod.returnType())
+ "], "
+ typesToCanonicalTypeNames(existingImportedPainlessMethod.typeParameters)
+ typesToCanonicalTypeNames(existingImportedPainlessMethod.typeParameters())
+ "]"
);
}
@ -1766,9 +1766,9 @@ public final class PainlessLookupBuilder {
+ methodName
+ "], "
+ "["
+ typeToCanonicalTypeName(existingPainlessClassBinding.returnType)
+ typeToCanonicalTypeName(existingPainlessClassBinding.returnType())
+ "], "
+ typesToCanonicalTypeNames(existingPainlessClassBinding.typeParameters)
+ typesToCanonicalTypeNames(existingPainlessClassBinding.typeParameters())
+ "]"
);
}
@ -2001,11 +2001,11 @@ public final class PainlessLookupBuilder {
+ methodName
+ "], "
+ "["
+ typeToCanonicalTypeName(existingPainlessInstanceBinding.returnType)
+ typeToCanonicalTypeName(existingPainlessInstanceBinding.returnType())
+ "], "
+ typesToCanonicalTypeNames(existingPainlessInstanceBinding.typeParameters)
+ typesToCanonicalTypeNames(existingPainlessInstanceBinding.typeParameters())
+ "], "
+ existingPainlessInstanceBinding.annotations
+ existingPainlessInstanceBinding.annotations()
);
}
}
@ -2186,7 +2186,7 @@ public final class PainlessLookupBuilder {
painlessClassBuilder.runtimeMethods.putAll(painlessClassBuilder.methods);
for (PainlessMethod painlessMethod : painlessClassBuilder.runtimeMethods.values()) {
for (Class<?> typeParameter : painlessMethod.typeParameters) {
for (Class<?> typeParameter : painlessMethod.typeParameters()) {
if (typeParameter == Byte.class
|| typeParameter == Short.class
|| typeParameter == Character.class
@ -2202,12 +2202,12 @@ public final class PainlessLookupBuilder {
}
private void generateBridgeMethod(PainlessClassBuilder painlessClassBuilder, PainlessMethod painlessMethod) {
String painlessMethodKey = buildPainlessMethodKey(painlessMethod.javaMethod.getName(), painlessMethod.typeParameters.size());
String painlessMethodKey = buildPainlessMethodKey(painlessMethod.javaMethod().getName(), painlessMethod.typeParameters().size());
PainlessMethod bridgePainlessMethod = painlessBridgeCache.get(painlessMethod);
if (bridgePainlessMethod == null) {
Method javaMethod = painlessMethod.javaMethod;
boolean isStatic = Modifier.isStatic(painlessMethod.javaMethod.getModifiers());
Method javaMethod = painlessMethod.javaMethod();
boolean isStatic = Modifier.isStatic(painlessMethod.javaMethod().getModifiers());
int bridgeClassFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
int bridgeClassAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL;
@ -2267,10 +2267,10 @@ public final class PainlessLookupBuilder {
}
}
MethodType bridgeMethodType = MethodType.methodType(painlessMethod.returnType, bridgeTypeParameters);
MethodType bridgeMethodType = MethodType.methodType(painlessMethod.returnType(), bridgeTypeParameters);
MethodWriter bridgeMethodWriter = new MethodWriter(
Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
new org.objectweb.asm.commons.Method(painlessMethod.javaMethod.getName(), bridgeMethodType.toMethodDescriptorString()),
new org.objectweb.asm.commons.Method(painlessMethod.javaMethod().getName(), bridgeMethodType.toMethodDescriptorString()),
bridgeClassWriter,
null,
null
@ -2310,14 +2310,14 @@ public final class PainlessLookupBuilder {
Class<?> bridgeClass = bridgeLoader.defineBridge(bridgeClassName.replace('/', '.'), bridgeClassWriter.toByteArray());
Method bridgeMethod = bridgeClass.getMethod(
painlessMethod.javaMethod.getName(),
painlessMethod.javaMethod().getName(),
bridgeTypeParameters.toArray(new Class<?>[0])
);
MethodHandle bridgeHandle = MethodHandles.publicLookup().in(bridgeClass).unreflect(bridgeClass.getMethods()[0]);
bridgePainlessMethod = new PainlessMethod(
bridgeMethod,
bridgeClass,
painlessMethod.returnType,
painlessMethod.returnType(),
bridgeTypeParameters,
bridgeHandle,
bridgeMethodType,
@ -2347,8 +2347,8 @@ public final class PainlessLookupBuilder {
String methodKey = painlessMethodEntry.getKey();
PainlessMethod painlessMethod = painlessMethodEntry.getValue();
PainlessMethod bridgePainlessMethod = painlessClassBuilder.runtimeMethods.get(methodKey);
String methodName = painlessMethod.javaMethod.getName();
int typeParametersSize = painlessMethod.typeParameters.size();
String methodName = painlessMethod.javaMethod().getName();
int typeParametersSize = painlessMethod.typeParameters().size();
if (typeParametersSize == 0
&& methodName.startsWith("get")
@ -2356,7 +2356,7 @@ public final class PainlessLookupBuilder {
&& Character.isUpperCase(methodName.charAt(3))) {
painlessClassBuilder.getterMethodHandles.putIfAbsent(
Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4),
bridgePainlessMethod.methodHandle
bridgePainlessMethod.methodHandle()
);
} else if (typeParametersSize == 0
&& methodName.startsWith("is")
@ -2364,7 +2364,7 @@ public final class PainlessLookupBuilder {
&& Character.isUpperCase(methodName.charAt(2))) {
painlessClassBuilder.getterMethodHandles.putIfAbsent(
Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3),
bridgePainlessMethod.methodHandle
bridgePainlessMethod.methodHandle()
);
} else if (typeParametersSize == 1
&& methodName.startsWith("set")
@ -2372,14 +2372,14 @@ public final class PainlessLookupBuilder {
&& Character.isUpperCase(methodName.charAt(3))) {
painlessClassBuilder.setterMethodHandles.putIfAbsent(
Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4),
bridgePainlessMethod.methodHandle
bridgePainlessMethod.methodHandle()
);
}
}
for (PainlessField painlessField : painlessClassBuilder.fields.values()) {
painlessClassBuilder.getterMethodHandles.put(painlessField.javaField.getName().intern(), painlessField.getterMethodHandle);
painlessClassBuilder.setterMethodHandles.put(painlessField.javaField.getName().intern(), painlessField.setterMethodHandle);
painlessClassBuilder.getterMethodHandles.put(painlessField.javaField().getName().intern(), painlessField.getterMethodHandle());
painlessClassBuilder.setterMethodHandles.put(painlessField.javaField().getName().intern(), painlessField.setterMethodHandle());
}
}
}

View File

@ -356,11 +356,11 @@ public final class PainlessLookupUtility {
* derived from an {@link org.elasticsearch.painless.spi.annotation.InjectConstantAnnotation}.
*/
public static Object[] buildInjections(PainlessMethod painlessMethod, Map<String, Object> constants) {
if (painlessMethod.annotations.containsKey(InjectConstantAnnotation.class) == false) {
if (painlessMethod.annotations().containsKey(InjectConstantAnnotation.class) == false) {
return new Object[0];
}
List<String> names = ((InjectConstantAnnotation) painlessMethod.annotations.get(InjectConstantAnnotation.class)).injects;
List<String> names = ((InjectConstantAnnotation) painlessMethod.annotations().get(InjectConstantAnnotation.class)).injects();
Object[] injections = new Object[names.size()];
for (int i = 0; i < names.size(); i++) {
@ -373,7 +373,7 @@ public final class PainlessLookupUtility {
+ name
+ "] not found for injection into method "
+ "["
+ buildPainlessMethodKey(painlessMethod.javaMethod.getName(), painlessMethod.typeParameters.size())
+ buildPainlessMethodKey(painlessMethod.javaMethod().getName(), painlessMethod.typeParameters().size())
+ "]"
);
}

View File

@ -15,15 +15,15 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
public class PainlessMethod {
public final Method javaMethod;
public final Class<?> targetClass;
public final Class<?> returnType;
public final List<Class<?>> typeParameters;
public final MethodHandle methodHandle;
public final MethodType methodType;
public final Map<Class<?>, Object> annotations;
public record PainlessMethod(
Method javaMethod,
Class<?> targetClass,
Class<?> returnType,
List<Class<?>> typeParameters,
MethodHandle methodHandle,
MethodType methodType,
Map<Class<?>, Object> annotations
) {
public PainlessMethod(
Method javaMethod,
@ -34,7 +34,6 @@ public class PainlessMethod {
MethodType methodType,
Map<Class<?>, Object> annotations
) {
this.javaMethod = javaMethod;
this.targetClass = targetClass;
this.returnType = returnType;
@ -55,7 +54,6 @@ public class PainlessMethod {
}
PainlessMethod that = (PainlessMethod) object;
return Objects.equals(javaMethod, that.javaMethod)
&& Objects.equals(targetClass, that.targetClass)
&& Objects.equals(returnType, that.returnType)

View File

@ -1085,13 +1085,13 @@ public class DefaultConstantFoldingOptimizationPhase extends IRTreeBaseVisitor<C
irInvokeCallMemberNode.getArgumentNodes().get(i).visit(this, (e) -> irInvokeCallMemberNode.getArgumentNodes().set(j, e));
}
PainlessMethod method = irInvokeCallMemberNode.getDecorationValue(IRDMethod.class);
if (method != null && method.annotations.containsKey(CompileTimeOnlyAnnotation.class)) {
replaceCallWithConstant(irInvokeCallMemberNode, scope, method.javaMethod, null);
if (method != null && method.annotations().containsKey(CompileTimeOnlyAnnotation.class)) {
replaceCallWithConstant(irInvokeCallMemberNode, scope, method.javaMethod(), null);
return;
}
PainlessInstanceBinding instanceBinding = irInvokeCallMemberNode.getDecorationValue(IRDInstanceBinding.class);
if (instanceBinding != null && instanceBinding.annotations.containsKey(CompileTimeOnlyAnnotation.class)) {
replaceCallWithConstant(irInvokeCallMemberNode, scope, instanceBinding.javaMethod, instanceBinding.targetInstance);
if (instanceBinding != null && instanceBinding.annotations().containsKey(CompileTimeOnlyAnnotation.class)) {
replaceCallWithConstant(irInvokeCallMemberNode, scope, instanceBinding.javaMethod(), instanceBinding.targetInstance());
return;
}
}

View File

@ -1179,8 +1179,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.newInstance(MethodWriter.getType(irListInitializationNode.getDecorationValue(IRDExpressionType.class)));
methodWriter.dup();
methodWriter.invokeConstructor(
Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor)
Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor())
);
for (ExpressionNode irArgumentNode : irListInitializationNode.getArgumentNodes()) {
@ -1200,8 +1200,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.newInstance(MethodWriter.getType(irMapInitializationNode.getDecorationValue(IRDExpressionType.class)));
methodWriter.dup();
methodWriter.invokeConstructor(
Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor)
Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor())
);
for (int index = 0; index < irMapInitializationNode.getArgumentsSize(); ++index) {
@ -1262,8 +1262,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
PainlessConstructor painlessConstructor = irNewObjectNode.getDecorationValue(IRDConstructor.class);
methodWriter.invokeConstructor(
Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor)
Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()),
Method.getMethod(painlessConstructor.javaConstructor())
);
}
@ -1428,10 +1428,10 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.writeDebugInfo(irLoadDotNode.getLocation());
PainlessField painlessField = irLoadDotNode.getDecorationValue(IRDField.class);
boolean isStatic = Modifier.isStatic(painlessField.javaField.getModifiers());
Type asmOwnerType = Type.getType(painlessField.javaField.getDeclaringClass());
String fieldName = painlessField.javaField.getName();
Type asmFieldType = MethodWriter.getType(painlessField.typeParameter);
boolean isStatic = Modifier.isStatic(painlessField.javaField().getModifiers());
Type asmOwnerType = Type.getType(painlessField.javaField().getDeclaringClass());
String fieldName = painlessField.javaField().getName();
Type asmFieldType = MethodWriter.getType(painlessField.typeParameter());
if (isStatic) {
methodWriter.getStatic(asmOwnerType, fieldName, asmFieldType);
@ -1448,8 +1448,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
PainlessMethod getterPainlessMethod = irDotSubShortcutNode.getDecorationValue(IRDMethod.class);
methodWriter.invokeMethodCall(getterPainlessMethod);
if (getterPainlessMethod.returnType.equals(getterPainlessMethod.javaMethod.getReturnType()) == false) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType));
if (getterPainlessMethod.returnType().equals(getterPainlessMethod.javaMethod().getReturnType()) == false) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType()));
}
}
@ -1461,8 +1461,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
PainlessMethod getterPainlessMethod = irLoadListShortcutNode.getDecorationValue(IRDMethod.class);
methodWriter.invokeMethodCall(getterPainlessMethod);
if (getterPainlessMethod.returnType == getterPainlessMethod.javaMethod.getReturnType()) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType));
if (getterPainlessMethod.returnType() == getterPainlessMethod.javaMethod().getReturnType()) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType()));
}
}
@ -1474,8 +1474,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
PainlessMethod getterPainlessMethod = irLoadMapShortcutNode.getDecorationValue(IRDMethod.class);
methodWriter.invokeMethodCall(getterPainlessMethod);
if (getterPainlessMethod.returnType != getterPainlessMethod.javaMethod.getReturnType()) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType));
if (getterPainlessMethod.returnType() != getterPainlessMethod.javaMethod().getReturnType()) {
methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType()));
}
}
@ -1549,10 +1549,10 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.writeDebugInfo(irStoreDotNode.getLocation());
PainlessField painlessField = irStoreDotNode.getDecorationValue(IRDField.class);
boolean isStatic = Modifier.isStatic(painlessField.javaField.getModifiers());
Type asmOwnerType = Type.getType(painlessField.javaField.getDeclaringClass());
String fieldName = painlessField.javaField.getName();
Type asmFieldType = MethodWriter.getType(painlessField.typeParameter);
boolean isStatic = Modifier.isStatic(painlessField.javaField().getModifiers());
Type asmOwnerType = Type.getType(painlessField.javaField().getDeclaringClass());
String fieldName = painlessField.javaField().getName();
Type asmFieldType = MethodWriter.getType(painlessField.typeParameter());
if (isStatic) {
methodWriter.putStatic(asmOwnerType, fieldName, asmFieldType);
@ -1569,7 +1569,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.writeDebugInfo(irDotSubShortcutNode.getLocation());
methodWriter.invokeMethodCall(irDotSubShortcutNode.getDecorationValue(IRDMethod.class));
methodWriter.writePop(MethodWriter.getType(irDotSubShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize());
methodWriter.writePop(MethodWriter.getType(irDotSubShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize());
}
@Override
@ -1580,7 +1580,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.writeDebugInfo(irStoreListShortcutNode.getLocation());
methodWriter.invokeMethodCall(irStoreListShortcutNode.getDecorationValue(IRDMethod.class));
methodWriter.writePop(MethodWriter.getType(irStoreListShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize());
methodWriter.writePop(MethodWriter.getType(irStoreListShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize());
}
@Override
@ -1591,7 +1591,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
methodWriter.writeDebugInfo(irStoreMapShortcutNode.getLocation());
methodWriter.invokeMethodCall(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class));
methodWriter.writePop(MethodWriter.getType(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize());
methodWriter.writePop(MethodWriter.getType(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize());
}
@Override
@ -1769,8 +1769,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
}
Method asmMethod = new Method(
thisMethod.javaMethod.getName(),
thisMethod.methodType.dropParameterTypes(0, 1).toMethodDescriptorString()
thisMethod.javaMethod().getName(),
thisMethod.methodType().dropParameterTypes(0, 1).toMethodDescriptorString()
);
methodWriter.invokeVirtual(CLASS_TYPE, asmMethod);
} else if (importedMethod != null) {
@ -1778,13 +1778,13 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
visit(irArgumentNode, writeScope);
}
Type asmType = Type.getType(importedMethod.targetClass);
Method asmMethod = new Method(importedMethod.javaMethod.getName(), importedMethod.methodType.toMethodDescriptorString());
Type asmType = Type.getType(importedMethod.targetClass());
Method asmMethod = new Method(importedMethod.javaMethod().getName(), importedMethod.methodType().toMethodDescriptorString());
methodWriter.invokeStatic(asmType, asmMethod);
} else if (classBinding != null) {
Type type = Type.getType(classBinding.javaConstructor.getDeclaringClass());
Type type = Type.getType(classBinding.javaConstructor().getDeclaringClass());
int classBindingOffset = irInvokeCallMemberNode.hasCondition(IRCStatic.class) ? 0 : 1;
int javaConstructorParameterCount = classBinding.javaConstructor.getParameterCount() - classBindingOffset;
int javaConstructorParameterCount = classBinding.javaConstructor().getParameterCount() - classBindingOffset;
String bindingName = irInvokeCallMemberNode.getDecorationValue(IRDName.class);
Label nonNull = new Label();
@ -1804,30 +1804,30 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor<WriteScope> {
visit(irArgumentNodes.get(argument), writeScope);
}
methodWriter.invokeConstructor(type, Method.getMethod(classBinding.javaConstructor));
methodWriter.invokeConstructor(type, Method.getMethod(classBinding.javaConstructor()));
methodWriter.putField(CLASS_TYPE, bindingName, type);
methodWriter.mark(nonNull);
methodWriter.loadThis();
methodWriter.getField(CLASS_TYPE, bindingName, type);
for (int argument = 0; argument < classBinding.javaMethod.getParameterCount(); ++argument) {
for (int argument = 0; argument < classBinding.javaMethod().getParameterCount(); ++argument) {
visit(irArgumentNodes.get(argument + javaConstructorParameterCount), writeScope);
}
methodWriter.invokeVirtual(type, Method.getMethod(classBinding.javaMethod));
methodWriter.invokeVirtual(type, Method.getMethod(classBinding.javaMethod()));
} else if (instanceBinding != null) {
Type type = Type.getType(instanceBinding.targetInstance.getClass());
Type type = Type.getType(instanceBinding.targetInstance().getClass());
String bindingName = irInvokeCallMemberNode.getDecorationValue(IRDName.class);
methodWriter.loadThis();
methodWriter.getStatic(CLASS_TYPE, bindingName, type);
for (int argument = 0; argument < instanceBinding.javaMethod.getParameterCount(); ++argument) {
for (int argument = 0; argument < instanceBinding.javaMethod().getParameterCount(); ++argument) {
visit(irArgumentNodes.get(argument), writeScope);
}
methodWriter.invokeVirtual(type, Method.getMethod(instanceBinding.javaMethod));
methodWriter.invokeVirtual(type, Method.getMethod(instanceBinding.javaMethod()));
} else {
throw new IllegalStateException("invalid unbound call");
}

View File

@ -162,8 +162,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
*/
public void decorateWithCast(AExpression userExpressionNode, SemanticScope semanticScope) {
Location location = userExpressionNode.getLocation();
Class<?> valueType = semanticScope.getDecoration(userExpressionNode, ValueType.class).getValueType();
Class<?> targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).getTargetType();
Class<?> valueType = semanticScope.getDecoration(userExpressionNode, ValueType.class).valueType();
Class<?> targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).targetType();
boolean isExplicitCast = semanticScope.getCondition(userExpressionNode, Explicit.class);
boolean isInternalCast = semanticScope.getCondition(userExpressionNode, Internal.class);
@ -196,7 +196,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
throw userExpressionNode.createError(
new IllegalArgumentException(
"cannot resolve symbol ["
+ semanticScope.getDecoration(userExpressionNode, PartialCanonicalTypeName.class).getPartialCanonicalTypeName()
+ semanticScope.getDecoration(userExpressionNode, PartialCanonicalTypeName.class).partialCanonicalTypeName()
+ "]"
)
);
@ -643,13 +643,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
throw userEachNode.createError(new IllegalArgumentException("extraneous foreach loop"));
}
Class<?> iterableValueType = semanticScope.getDecoration(userIterableNode, ValueType.class).getValueType();
Class<?> iterableValueType = semanticScope.getDecoration(userIterableNode, ValueType.class).valueType();
if (iterableValueType.isArray()) {
PainlessCast painlessCast = AnalyzerCaster.getLegalCast(
location,
iterableValueType.getComponentType(),
variable.getType(),
variable.type(),
true,
true
);
@ -790,7 +790,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
}
checkedVisit(userStatementNode, semanticScope);
Class<?> expressionValueType = semanticScope.getDecoration(userStatementNode, ValueType.class).getValueType();
Class<?> expressionValueType = semanticScope.getDecoration(userStatementNode, ValueType.class).valueType();
boolean rtn = lastSource && isVoid == false && expressionValueType != void.class;
if (rtn) {
@ -980,7 +980,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.replicateCondition(userAssignmentNode, userLeftNode, Read.class);
semanticScope.setCondition(userLeftNode, Write.class);
checkedVisit(userLeftNode, semanticScope);
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, Decorations.ValueType.class).getValueType();
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, Decorations.ValueType.class).valueType();
AExpression userRightNode = userAssignmentNode.getRightNode();
semanticScope.setCondition(userRightNode, Read.class);
@ -989,7 +989,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (operation != null) {
checkedVisit(userRightNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType();
Class<?> compoundType;
boolean isConcatenation = false;
@ -1078,7 +1078,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
// if the lhs node is a def optimized node we update the actual type to remove the need for a cast
} else if (semanticScope.getCondition(userLeftNode, DefOptimized.class)) {
checkedVisit(userRightNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType();
if (rightValueType == void.class) {
throw userAssignmentNode.createError(
@ -1144,7 +1144,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
decorateWithCast(userChildNode, semanticScope);
}
valueType = semanticScope.getDecoration(userChildNode, ValueType.class).getValueType();
valueType = semanticScope.getDecoration(userChildNode, ValueType.class).valueType();
} else {
if (operation == Operation.NOT) {
semanticScope.setCondition(userChildNode, Read.class);
@ -1156,7 +1156,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
} else if (operation == Operation.BWNOT || operation == Operation.ADD || operation == Operation.SUB) {
semanticScope.setCondition(userChildNode, Read.class);
checkedVisit(userChildNode, semanticScope);
Class<?> childValueType = semanticScope.getDecoration(userChildNode, ValueType.class).getValueType();
Class<?> childValueType = semanticScope.getDecoration(userChildNode, ValueType.class).valueType();
unaryType = AnalyzerCaster.promoteNumeric(childValueType, operation != Operation.BWNOT);
@ -1182,7 +1182,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
TargetType targetType = semanticScope.getDecoration(userUnaryNode, TargetType.class);
if (unaryType == def.class && targetType != null) {
valueType = targetType.getTargetType();
valueType = targetType.targetType();
} else {
valueType = unaryType;
}
@ -1225,12 +1225,12 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
AExpression userLeftNode = userBinaryNode.getLeftNode();
semanticScope.setCondition(userLeftNode, Read.class);
checkedVisit(userLeftNode, semanticScope);
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType();
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType();
AExpression userRightNode = userBinaryNode.getRightNode();
semanticScope.setCondition(userRightNode, Read.class);
checkedVisit(userRightNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType();
Class<?> valueType;
Class<?> binaryType;
@ -1290,7 +1290,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
TargetType targetType = semanticScope.getDecoration(userBinaryNode, TargetType.class);
if (targetType != null) {
valueType = targetType.getTargetType();
valueType = targetType.targetType();
}
} else if (operation != Operation.ADD || binaryType != String.class) {
semanticScope.putDecoration(userLeftNode, new TargetType(binaryType));
@ -1385,12 +1385,12 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
AExpression userLeftNode = userCompNode.getLeftNode();
semanticScope.setCondition(userLeftNode, Read.class);
checkedVisit(userLeftNode, semanticScope);
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType();
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType();
AExpression userRightNode = userCompNode.getRightNode();
semanticScope.setCondition(userRightNode, Read.class);
checkedVisit(userRightNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType();
Class<?> promotedType;
@ -1546,7 +1546,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.replicateCondition(userConditionalNode, userTrueNode, Explicit.class);
semanticScope.replicateCondition(userConditionalNode, userTrueNode, Internal.class);
checkedVisit(userTrueNode, semanticScope);
Class<?> leftValueType = semanticScope.getDecoration(userTrueNode, ValueType.class).getValueType();
Class<?> leftValueType = semanticScope.getDecoration(userTrueNode, ValueType.class).valueType();
AExpression userFalseNode = userConditionalNode.getFalseNode();
semanticScope.setCondition(userFalseNode, Read.class);
@ -1554,7 +1554,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.replicateCondition(userConditionalNode, userFalseNode, Explicit.class);
semanticScope.replicateCondition(userConditionalNode, userFalseNode, Internal.class);
checkedVisit(userFalseNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userFalseNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userFalseNode, ValueType.class).valueType();
TargetType targetType = semanticScope.getDecoration(userConditionalNode, TargetType.class);
Class<?> valueType;
@ -1580,7 +1580,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.putDecoration(userFalseNode, new TargetType(promote));
valueType = promote;
} else {
valueType = targetType.getTargetType();
valueType = targetType.targetType();
}
decorateWithCast(userTrueNode, semanticScope);
@ -1607,7 +1607,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
TargetType targetType = semanticScope.getDecoration(userElvisNode, TargetType.class);
if (targetType != null && targetType.getTargetType().isPrimitive()) {
if (targetType != null && targetType.targetType().isPrimitive()) {
throw userElvisNode.createError(new IllegalArgumentException("Elvis operator cannot return primitives"));
}
@ -1617,7 +1617,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.replicateCondition(userElvisNode, userLeftNode, Explicit.class);
semanticScope.replicateCondition(userElvisNode, userLeftNode, Internal.class);
checkedVisit(userLeftNode, semanticScope);
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType();
Class<?> leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType();
AExpression userRightNode = userElvisNode.getRightNode();
semanticScope.setCondition(userRightNode, Read.class);
@ -1625,7 +1625,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.replicateCondition(userElvisNode, userRightNode, Explicit.class);
semanticScope.replicateCondition(userElvisNode, userRightNode, Internal.class);
checkedVisit(userRightNode, semanticScope);
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType();
Class<?> rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType();
if (userLeftNode instanceof ENull) {
throw userElvisNode.createError(new IllegalArgumentException("Extraneous elvis operator. LHS is null."));
@ -1652,7 +1652,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.putDecoration(userRightNode, new TargetType(promote));
valueType = promote;
} else {
valueType = targetType.getTargetType();
valueType = targetType.targetType();
}
decorateWithCast(userLeftNode, semanticScope);
@ -1849,19 +1849,19 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
}
scriptScope.putDecoration(userNewObjNode, new StandardPainlessConstructor(constructor));
scriptScope.markNonDeterministic(constructor.annotations.containsKey(NonDeterministicAnnotation.class));
scriptScope.markNonDeterministic(constructor.annotations().containsKey(NonDeterministicAnnotation.class));
Class<?>[] types = new Class<?>[constructor.typeParameters.size()];
constructor.typeParameters.toArray(types);
Class<?>[] types = new Class<?>[constructor.typeParameters().size()];
constructor.typeParameters().toArray(types);
if (constructor.typeParameters.size() != userArgumentsSize) {
if (constructor.typeParameters().size() != userArgumentsSize) {
throw userNewObjNode.createError(
new IllegalArgumentException(
"When calling constructor on type ["
+ PainlessLookupUtility.typeToCanonicalTypeName(valueType)
+ "] "
+ "expected ["
+ constructor.typeParameters.size()
+ constructor.typeParameters().size()
+ "] arguments, but found ["
+ userArgumentsSize
+ "]."
@ -1930,8 +1930,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
// check to see if this class binding requires an implicit this reference
if (classBinding != null
&& classBinding.typeParameters.isEmpty() == false
&& classBinding.typeParameters.get(0) == scriptScope.getScriptClassInfo().getBaseClass()) {
&& classBinding.typeParameters().isEmpty() == false
&& classBinding.typeParameters().get(0) == scriptScope.getScriptClassInfo().getBaseClass()) {
classBinding = null;
}
@ -1945,8 +1945,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
classBinding = scriptScope.getPainlessLookup().lookupPainlessClassBinding(methodName, userArgumentsSize + 1);
if (classBinding != null) {
if (classBinding.typeParameters.isEmpty() == false
&& classBinding.typeParameters.get(0) == scriptScope.getScriptClassInfo().getBaseClass()) {
if (classBinding.typeParameters().isEmpty() == false
&& classBinding.typeParameters().get(0) == scriptScope.getScriptClassInfo().getBaseClass()) {
classBindingOffset = 1;
} else {
classBinding = null;
@ -1981,27 +1981,27 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.setUsesInstanceMethod();
semanticScope.putDecoration(userCallLocalNode, new ThisPainlessMethod(thisMethod));
scriptScope.markNonDeterministic(thisMethod.annotations.containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(thisMethod.typeParameters);
valueType = thisMethod.returnType;
scriptScope.markNonDeterministic(thisMethod.annotations().containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(thisMethod.typeParameters());
valueType = thisMethod.returnType();
} else if (importedMethod != null) {
semanticScope.putDecoration(userCallLocalNode, new StandardPainlessMethod(importedMethod));
scriptScope.markNonDeterministic(importedMethod.annotations.containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(importedMethod.typeParameters);
valueType = importedMethod.returnType;
scriptScope.markNonDeterministic(importedMethod.annotations().containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(importedMethod.typeParameters());
valueType = importedMethod.returnType();
} else if (classBinding != null) {
semanticScope.putDecoration(userCallLocalNode, new StandardPainlessClassBinding(classBinding));
semanticScope.putDecoration(userCallLocalNode, new StandardConstant(classBindingOffset));
scriptScope.markNonDeterministic(classBinding.annotations.containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(classBinding.typeParameters);
valueType = classBinding.returnType;
scriptScope.markNonDeterministic(classBinding.annotations().containsKey(NonDeterministicAnnotation.class));
typeParameters = new ArrayList<>(classBinding.typeParameters());
valueType = classBinding.returnType();
} else if (instanceBinding != null) {
semanticScope.putDecoration(userCallLocalNode, new StandardPainlessInstanceBinding(instanceBinding));
typeParameters = new ArrayList<>(instanceBinding.typeParameters);
valueType = instanceBinding.returnType;
typeParameters = new ArrayList<>(instanceBinding.typeParameters());
valueType = instanceBinding.returnType();
} else {
throw new IllegalStateException("Illegal tree structure.");
}
@ -2103,7 +2103,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
} else {
try {
TargetType targetType = semanticScope.getDecoration(userNumericNode, TargetType.class);
Class<?> sort = targetType == null ? int.class : targetType.getTargetType();
Class<?> sort = targetType == null ? int.class : targetType.targetType();
int integer = Integer.parseInt(numeric, radix);
if (sort == byte.class && integer >= Byte.MIN_VALUE && integer <= Byte.MAX_VALUE) {
@ -2228,13 +2228,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
Class<?> valueType;
if (targetType != null) {
if (targetType.getTargetType().isPrimitive()) {
if (targetType.targetType().isPrimitive()) {
throw userNullNode.createError(
new IllegalArgumentException("Cannot cast null to a primitive type [" + targetType.getTargetCanonicalTypeName() + "].")
);
}
valueType = targetType.getTargetType();
valueType = targetType.targetType();
} else {
valueType = Object.class;
}
@ -2360,7 +2360,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
}
} else {
// we know the method statically, infer return type and any unknown/def types
interfaceMethod = scriptScope.getPainlessLookup().lookupFunctionalInterfacePainlessMethod(targetType.getTargetType());
interfaceMethod = scriptScope.getPainlessLookup().lookupFunctionalInterfacePainlessMethod(targetType.targetType());
if (interfaceMethod == null) {
throw userLambdaNode.createError(
new IllegalArgumentException(
@ -2369,25 +2369,25 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
);
}
// check arity before we manipulate parameters
if (interfaceMethod.typeParameters.size() != canonicalTypeNameParameters.size()) throw new IllegalArgumentException(
if (interfaceMethod.typeParameters().size() != canonicalTypeNameParameters.size()) throw new IllegalArgumentException(
"Incorrect number of parameters for ["
+ interfaceMethod.javaMethod.getName()
+ interfaceMethod.javaMethod().getName()
+ "] in ["
+ targetType.getTargetCanonicalTypeName()
+ "]"
);
// for method invocation, its allowed to ignore the return value
if (interfaceMethod.returnType == void.class) {
if (interfaceMethod.returnType() == void.class) {
returnType = def.class;
} else {
returnType = interfaceMethod.returnType;
returnType = interfaceMethod.returnType();
}
// replace any null types with the actual type
typeParameters = new ArrayList<>(canonicalTypeNameParameters.size());
for (int i = 0; i < canonicalTypeNameParameters.size(); i++) {
String paramType = canonicalTypeNameParameters.get(i);
if (paramType == null) {
typeParameters.add(interfaceMethod.typeParameters.get(i));
typeParameters.add(interfaceMethod.typeParameters().get(i));
} else {
Class<?> typeParameter = scriptScope.getPainlessLookup().canonicalTypeNameToType(paramType);
@ -2433,8 +2433,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
List<String> parameterNamesWithCaptures = new ArrayList<>(capturedVariables.size() + parameterNames.size());
for (Variable capturedVariable : capturedVariables) {
typeParametersWithCaptures.add(capturedVariable.getType());
parameterNamesWithCaptures.add(capturedVariable.getName());
typeParametersWithCaptures.add(capturedVariable.type());
parameterNamesWithCaptures.add(capturedVariable.name());
}
typeParametersWithCaptures.addAll(typeParameters);
@ -2451,21 +2451,21 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
valueType = String.class;
semanticScope.putDecoration(
userLambdaNode,
new EncodingDecoration(true, lambdaScope.usesInstanceMethod(), "this", name, capturedVariables.size())
EncodingDecoration.of(true, lambdaScope.usesInstanceMethod(), "this", name, capturedVariables.size())
);
} else {
FunctionRef ref = FunctionRef.create(
scriptScope.getPainlessLookup(),
scriptScope.getFunctionTable(),
location,
targetType.getTargetType(),
targetType.targetType(),
"this",
name,
capturedVariables.size(),
scriptScope.getCompilerSettings().asMap(),
lambdaScope.usesInstanceMethod()
);
valueType = targetType.getTargetType();
valueType = targetType.targetType();
semanticScope.putDecoration(userLambdaNode, new ReferenceDecoration(ref));
}
@ -2516,20 +2516,20 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
}
if (targetType == null) {
valueType = String.class;
semanticScope.putDecoration(userFunctionRefNode, new EncodingDecoration(true, isInstanceReference, symbol, methodName, 0));
semanticScope.putDecoration(userFunctionRefNode, EncodingDecoration.of(true, isInstanceReference, symbol, methodName, 0));
} else {
FunctionRef ref = FunctionRef.create(
scriptScope.getPainlessLookup(),
scriptScope.getFunctionTable(),
location,
targetType.getTargetType(),
targetType.targetType(),
symbol,
methodName,
0,
scriptScope.getCompilerSettings().asMap(),
isInstanceReference
);
valueType = targetType.getTargetType();
valueType = targetType.targetType();
semanticScope.putDecoration(userFunctionRefNode, new ReferenceDecoration(ref));
}
} else {
@ -2552,30 +2552,30 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
SemanticScope.Variable captured = semanticScope.getVariable(location, symbol);
semanticScope.putDecoration(userFunctionRefNode, new CapturesDecoration(Collections.singletonList(captured)));
if (captured.getType().isPrimitive()) {
if (captured.type().isPrimitive()) {
semanticScope.setCondition(userFunctionRefNode, CaptureBox.class);
}
if (targetType == null) {
EncodingDecoration encodingDecoration;
if (captured.getType() == def.class) {
if (captured.type() == def.class) {
// dynamic implementation
encodingDecoration = new EncodingDecoration(false, false, symbol, methodName, 1);
encodingDecoration = EncodingDecoration.of(false, false, symbol, methodName, 1);
} else {
// typed implementation
encodingDecoration = new EncodingDecoration(true, false, captured.getCanonicalTypeName(), methodName, 1);
encodingDecoration = EncodingDecoration.of(true, false, captured.getCanonicalTypeName(), methodName, 1);
}
valueType = String.class;
semanticScope.putDecoration(userFunctionRefNode, encodingDecoration);
} else {
valueType = targetType.getTargetType();
valueType = targetType.targetType();
// static case
if (captured.getType() != def.class) {
if (captured.type() != def.class) {
FunctionRef ref = FunctionRef.create(
scriptScope.getPainlessLookup(),
scriptScope.getFunctionTable(),
location,
targetType.getTargetType(),
targetType.targetType(),
captured.getCanonicalTypeName(),
methodName,
1,
@ -2632,20 +2632,20 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (targetType == null) {
valueType = String.class;
scriptScope.putDecoration(userNewArrayFunctionRefNode, new EncodingDecoration(true, false, "this", name, 0));
scriptScope.putDecoration(userNewArrayFunctionRefNode, EncodingDecoration.of(true, false, "this", name, 0));
} else {
FunctionRef ref = FunctionRef.create(
scriptScope.getPainlessLookup(),
scriptScope.getFunctionTable(),
userNewArrayFunctionRefNode.getLocation(),
targetType.getTargetType(),
targetType.targetType(),
"this",
name,
0,
scriptScope.getCompilerSettings().asMap(),
false
);
valueType = targetType.getTargetType();
valueType = targetType.targetType();
semanticScope.putDecoration(userNewArrayFunctionRefNode, new ReferenceDecoration(ref));
}
@ -2694,10 +2694,10 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
Variable variable = semanticScope.getVariable(location, symbol);
if (write && variable.isFinal()) {
throw userSymbolNode.createError(new IllegalArgumentException("Variable [" + variable.getName() + "] is read-only."));
throw userSymbolNode.createError(new IllegalArgumentException("Variable [" + variable.name() + "] is read-only."));
}
Class<?> valueType = variable.getType();
Class<?> valueType = variable.type();
semanticScope.putDecoration(userSymbolNode, new ValueType(valueType));
} else {
semanticScope.putDecoration(userSymbolNode, new PartialCanonicalTypeName(symbol));
@ -2754,13 +2754,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (prefixStaticType != null) {
throw userDotNode.createError(
new IllegalArgumentException(
"value required: instead found unexpected type " + "[" + prefixStaticType.getStaticType() + "]"
"value required: instead found unexpected type " + "[" + prefixStaticType.staticType() + "]"
)
);
}
String canonicalTypeName = semanticScope.getDecoration(userPrefixNode, PartialCanonicalTypeName.class)
.getPartialCanonicalTypeName()
.partialCanonicalTypeName()
+ "."
+ index;
Class<?> staticType = scriptScope.getPainlessLookup().canonicalTypeNameToType(canonicalTypeName);
@ -2805,7 +2805,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
} else {
Class<?> valueType = null;
if (prefixValueType != null && prefixValueType.getValueType().isArray()) {
if (prefixValueType != null && prefixValueType.valueType().isArray()) {
if ("length".equals(index)) {
if (write) {
throw userDotNode.createError(
@ -2823,11 +2823,11 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
)
);
}
} else if (prefixValueType != null && prefixValueType.getValueType() == def.class) {
} else if (prefixValueType != null && prefixValueType.valueType() == def.class) {
TargetType targetType = userDotNode.isNullSafe() ? null : semanticScope.getDecoration(userDotNode, TargetType.class);
valueType = targetType == null || semanticScope.getCondition(userDotNode, Explicit.class)
? def.class
: targetType.getTargetType();
: targetType.targetType();
if (write) {
semanticScope.setCondition(userDotNode, DefOptimized.class);
@ -2838,11 +2838,11 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
boolean isStatic;
if (prefixValueType != null) {
prefixType = prefixValueType.getValueType();
prefixType = prefixValueType.valueType();
prefixCanonicalTypeName = prefixValueType.getValueCanonicalTypeName();
isStatic = false;
} else if (prefixStaticType != null) {
prefixType = prefixStaticType.getStaticType();
prefixType = prefixStaticType.staticType();
prefixCanonicalTypeName = prefixStaticType.getStaticCanonicalTypeName();
isStatic = true;
} else {
@ -2884,7 +2884,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
);
if (getter != null || setter != null) {
if (getter != null && (getter.returnType == void.class || getter.typeParameters.isEmpty() == false)) {
if (getter != null && (getter.returnType() == void.class || getter.typeParameters().isEmpty() == false)) {
throw userDotNode.createError(
new IllegalArgumentException(
"Illegal get shortcut on field [" + index + "] for type [" + prefixCanonicalTypeName + "]."
@ -2892,7 +2892,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
);
}
if (setter != null && (setter.returnType != void.class || setter.typeParameters.size() != 1)) {
if (setter != null && (setter.returnType() != void.class || setter.typeParameters().size() != 1)) {
throw userDotNode.createError(
new IllegalArgumentException(
"Illegal set shortcut on field [" + index + "] for type [" + prefixCanonicalTypeName + "]."
@ -2900,12 +2900,12 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
);
}
if (getter != null && setter != null && setter.typeParameters.get(0) != getter.returnType) {
if (getter != null && setter != null && setter.typeParameters().get(0) != getter.returnType()) {
throw userDotNode.createError(new IllegalArgumentException("Shortcut argument types must match."));
}
if ((read == false || getter != null) && (write == false || setter != null)) {
valueType = setter != null ? setter.typeParameters.get(0) : getter.returnType;
valueType = setter != null ? setter.typeParameters().get(0) : getter.returnType();
} else {
throw userDotNode.createError(
new IllegalArgumentException(
@ -2924,17 +2924,17 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.setCondition(userDotNode, Shortcut.class);
} else if (isStatic == false) {
if (Map.class.isAssignableFrom(prefixValueType.getValueType())) {
if (Map.class.isAssignableFrom(prefixValueType.valueType())) {
getter = scriptScope.getPainlessLookup().lookupPainlessMethod(prefixType, false, "get", 1);
setter = scriptScope.getPainlessLookup().lookupPainlessMethod(prefixType, false, "put", 2);
if (getter != null && (getter.returnType == void.class || getter.typeParameters.size() != 1)) {
if (getter != null && (getter.returnType() == void.class || getter.typeParameters().size() != 1)) {
throw userDotNode.createError(
new IllegalArgumentException("Illegal map get shortcut for type [" + prefixCanonicalTypeName + "].")
);
}
if (setter != null && setter.typeParameters.size() != 2) {
if (setter != null && setter.typeParameters().size() != 2) {
throw userDotNode.createError(
new IllegalArgumentException("Illegal map set shortcut for type [" + prefixCanonicalTypeName + "].")
);
@ -2942,13 +2942,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (getter != null
&& setter != null
&& (getter.typeParameters.get(0).equals(setter.typeParameters.get(0)) == false
|| getter.returnType.equals(setter.typeParameters.get(1)) == false)) {
&& (getter.typeParameters().get(0).equals(setter.typeParameters().get(0)) == false
|| getter.returnType().equals(setter.typeParameters().get(1)) == false)) {
throw userDotNode.createError(new IllegalArgumentException("Shortcut argument types must match."));
}
if ((read == false || getter != null) && (write == false || setter != null)) {
valueType = setter != null ? setter.typeParameters.get(1) : getter.returnType;
valueType = setter != null ? setter.typeParameters().get(1) : getter.returnType();
} else {
throw userDotNode.createError(
new IllegalArgumentException("Illegal map shortcut for type [" + prefixCanonicalTypeName + "].")
@ -2977,9 +2977,9 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
setter = scriptScope.getPainlessLookup().lookupPainlessMethod(prefixType, false, "set", 2);
if (getter != null
&& (getter.returnType == void.class
|| getter.typeParameters.size() != 1
|| getter.typeParameters.get(0) != int.class)) {
&& (getter.returnType() == void.class
|| getter.typeParameters().size() != 1
|| getter.typeParameters().get(0) != int.class)) {
throw userDotNode.createError(
new IllegalArgumentException(
"Illegal list get shortcut for type [" + prefixCanonicalTypeName + "]."
@ -2987,7 +2987,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
);
}
if (setter != null && (setter.typeParameters.size() != 2 || setter.typeParameters.get(0) != int.class)) {
if (setter != null
&& (setter.typeParameters().size() != 2 || setter.typeParameters().get(0) != int.class)) {
throw userDotNode.createError(
new IllegalArgumentException(
"Illegal list set shortcut for type [" + prefixCanonicalTypeName + "]."
@ -2997,13 +2998,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (getter != null
&& setter != null
&& (getter.typeParameters.get(0).equals(setter.typeParameters.get(0)) == false
|| getter.returnType.equals(setter.typeParameters.get(1)) == false)) {
&& (getter.typeParameters().get(0).equals(setter.typeParameters().get(0)) == false
|| getter.returnType().equals(setter.typeParameters().get(1)) == false)) {
throw userDotNode.createError(new IllegalArgumentException("Shortcut argument types must match."));
}
if ((read == false || getter != null) && (write == false || setter != null)) {
valueType = setter != null ? setter.typeParameters.get(1) : getter.returnType;
valueType = setter != null ? setter.typeParameters().get(1) : getter.returnType();
} else {
throw userDotNode.createError(
new IllegalArgumentException("Illegal list shortcut for type [" + prefixCanonicalTypeName + "].")
@ -3038,16 +3039,16 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
}
}
} else {
if (write && Modifier.isFinal(field.javaField.getModifiers())) {
if (write && Modifier.isFinal(field.javaField().getModifiers())) {
throw userDotNode.createError(
new IllegalArgumentException(
"invalid assignment: cannot assign a value to read-only field [" + field.javaField.getName() + "]"
"invalid assignment: cannot assign a value to read-only field [" + field.javaField().getName() + "]"
)
);
}
semanticScope.putDecoration(userDotNode, new StandardPainlessField(field));
valueType = field.typeParameter;
valueType = field.typeParameter();
}
}
@ -3085,7 +3086,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
AExpression userPrefixNode = userBraceNode.getPrefixNode();
semanticScope.setCondition(userPrefixNode, Read.class);
checkedVisit(userPrefixNode, semanticScope);
Class<?> prefixValueType = semanticScope.getDecoration(userPrefixNode, ValueType.class).getValueType();
Class<?> prefixValueType = semanticScope.getDecoration(userPrefixNode, ValueType.class).valueType();
AExpression userIndexNode = userBraceNode.getIndexNode();
Class<?> valueType;
@ -3102,8 +3103,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
TargetType targetType = semanticScope.getDecoration(userBraceNode, TargetType.class);
// TODO: remove ZonedDateTime exception when JodaCompatibleDateTime is removed
valueType = targetType == null
|| targetType.getTargetType() == ZonedDateTime.class
|| semanticScope.getCondition(userBraceNode, Explicit.class) ? def.class : targetType.getTargetType();
|| targetType.targetType() == ZonedDateTime.class
|| semanticScope.getCondition(userBraceNode, Explicit.class) ? def.class : targetType.targetType();
if (write) {
semanticScope.setCondition(userBraceNode, DefOptimized.class);
@ -3118,13 +3119,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
.getPainlessLookup()
.lookupPainlessMethod(prefixValueType, false, "put", 2);
if (getter != null && (getter.returnType == void.class || getter.typeParameters.size() != 1)) {
if (getter != null && (getter.returnType() == void.class || getter.typeParameters().size() != 1)) {
throw userBraceNode.createError(
new IllegalArgumentException("Illegal map get shortcut for type [" + canonicalClassName + "].")
);
}
if (setter != null && setter.typeParameters.size() != 2) {
if (setter != null && setter.typeParameters().size() != 2) {
throw userBraceNode.createError(
new IllegalArgumentException("Illegal map set shortcut for type [" + canonicalClassName + "].")
);
@ -3132,8 +3133,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (getter != null
&& setter != null
&& (getter.typeParameters.get(0).equals(setter.typeParameters.get(0)) == false
|| getter.returnType.equals(setter.typeParameters.get(1)) == false)) {
&& (getter.typeParameters().get(0).equals(setter.typeParameters().get(0)) == false
|| getter.returnType().equals(setter.typeParameters().get(1)) == false)) {
throw userBraceNode.createError(new IllegalArgumentException("Shortcut argument types must match."));
}
@ -3141,12 +3142,12 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.setCondition(userIndexNode, Read.class);
semanticScope.putDecoration(
userIndexNode,
new TargetType(setter != null ? setter.typeParameters.get(0) : getter.typeParameters.get(0))
new TargetType(setter != null ? setter.typeParameters().get(0) : getter.typeParameters().get(0))
);
checkedVisit(userIndexNode, semanticScope);
decorateWithCast(userIndexNode, semanticScope);
valueType = setter != null ? setter.typeParameters.get(1) : getter.returnType;
valueType = setter != null ? setter.typeParameters().get(1) : getter.returnType();
if (getter != null) {
semanticScope.putDecoration(userBraceNode, new GetterPainlessMethod(getter));
@ -3173,13 +3174,15 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
.lookupPainlessMethod(prefixValueType, false, "set", 2);
if (getter != null
&& (getter.returnType == void.class || getter.typeParameters.size() != 1 || getter.typeParameters.get(0) != int.class)) {
&& (getter.returnType() == void.class
|| getter.typeParameters().size() != 1
|| getter.typeParameters().get(0) != int.class)) {
throw userBraceNode.createError(
new IllegalArgumentException("Illegal list get shortcut for type [" + canonicalClassName + "].")
);
}
if (setter != null && (setter.typeParameters.size() != 2 || setter.typeParameters.get(0) != int.class)) {
if (setter != null && (setter.typeParameters().size() != 2 || setter.typeParameters().get(0) != int.class)) {
throw userBraceNode.createError(
new IllegalArgumentException("Illegal list set shortcut for type [" + canonicalClassName + "].")
);
@ -3187,8 +3190,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
if (getter != null
&& setter != null
&& (getter.typeParameters.get(0).equals(setter.typeParameters.get(0)) == false
|| getter.returnType.equals(setter.typeParameters.get(1)) == false)) {
&& (getter.typeParameters().get(0).equals(setter.typeParameters().get(0)) == false
|| getter.returnType().equals(setter.typeParameters().get(1)) == false)) {
throw userBraceNode.createError(new IllegalArgumentException("Shortcut argument types must match."));
}
@ -3198,7 +3201,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
checkedVisit(userIndexNode, semanticScope);
decorateWithCast(userIndexNode, semanticScope);
valueType = setter != null ? setter.typeParameters.get(1) : getter.returnType;
valueType = setter != null ? setter.typeParameters().get(1) : getter.returnType();
if (getter != null) {
semanticScope.putDecoration(userBraceNode, new GetterPainlessMethod(getter));
@ -3268,7 +3271,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
new IllegalArgumentException(
"cannot resolve symbol "
+ "["
+ semanticScope.getDecoration(userPrefixNode, PartialCanonicalTypeName.class).getPartialCanonicalTypeName()
+ semanticScope.getDecoration(userPrefixNode, PartialCanonicalTypeName.class).partialCanonicalTypeName()
+ "]"
)
);
@ -3278,10 +3281,10 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
PainlessMethod method = null;
if (prefixValueType != null) {
Class<?> type = prefixValueType.getValueType();
Class<?> type = prefixValueType.valueType();
PainlessLookup lookup = semanticScope.getScriptScope().getPainlessLookup();
if (prefixValueType.getValueType() == def.class) {
if (prefixValueType.valueType() == def.class) {
dynamic = true;
} else {
method = lookup.lookupPainlessMethod(type, false, methodName, userArgumentsSize);
@ -3310,7 +3313,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
} else if (prefixStaticType != null) {
method = semanticScope.getScriptScope()
.getPainlessLookup()
.lookupPainlessMethod(prefixStaticType.getStaticType(), true, methodName, userArgumentsSize);
.lookupPainlessMethod(prefixStaticType.staticType(), true, methodName, userArgumentsSize);
if (method == null) {
throw userCallNode.createError(
@ -3338,7 +3341,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
semanticScope.setCondition(userArgumentNode, Read.class);
semanticScope.setCondition(userArgumentNode, Internal.class);
checkedVisit(userArgumentNode, semanticScope);
Class<?> argumentValueType = semanticScope.getDecoration(userArgumentNode, ValueType.class).getValueType();
Class<?> argumentValueType = semanticScope.getDecoration(userArgumentNode, ValueType.class).valueType();
if (argumentValueType == void.class) {
throw userCallNode.createError(
@ -3350,25 +3353,25 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor<SemanticSc
TargetType targetType = userCallNode.isNullSafe() ? null : semanticScope.getDecoration(userCallNode, TargetType.class);
valueType = targetType == null || semanticScope.getCondition(userCallNode, Explicit.class)
? def.class
: targetType.getTargetType();
: targetType.targetType();
semanticScope.setCondition(userCallNode, DynamicInvocation.class);
} else {
Objects.requireNonNull(method);
semanticScope.getScriptScope().markNonDeterministic(method.annotations.containsKey(NonDeterministicAnnotation.class));
semanticScope.getScriptScope().markNonDeterministic(method.annotations().containsKey(NonDeterministicAnnotation.class));
for (int argument = 0; argument < userArgumentsSize; ++argument) {
AExpression userArgumentNode = userArgumentNodes.get(argument);
semanticScope.setCondition(userArgumentNode, Read.class);
semanticScope.putDecoration(userArgumentNode, new TargetType(method.typeParameters.get(argument)));
semanticScope.putDecoration(userArgumentNode, new TargetType(method.typeParameters().get(argument)));
semanticScope.setCondition(userArgumentNode, Internal.class);
checkedVisit(userArgumentNode, semanticScope);
decorateWithCast(userArgumentNode, semanticScope);
}
semanticScope.putDecoration(userCallNode, new StandardPainlessMethod(method));
valueType = method.returnType;
valueType = method.returnType();
}
if (userCallNode.isNullSafe() && valueType.isPrimitive()) {

View File

@ -450,7 +450,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
return irExpressionNode;
}
PainlessCast painlessCast = expressionPainlessCast.getExpressionPainlessCast();
PainlessCast painlessCast = expressionPainlessCast.expressionPainlessCast();
Class<?> targetType = painlessCast.targetType;
if (painlessCast.boxTargetType != null) {
@ -558,7 +558,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
return null;
} else {
userNode.visit(this, scriptScope);
return scriptScope.getDecoration(userNode, IRNodeDecoration.class).getIRNode();
return scriptScope.getDecoration(userNode, IRNodeDecoration.class).irNode();
}
}
@ -728,12 +728,12 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitEach(SEach userEachNode, ScriptScope scriptScope) {
Variable variable = scriptScope.getDecoration(userEachNode, SemanticVariable.class).getSemanticVariable();
Variable variable = scriptScope.getDecoration(userEachNode, SemanticVariable.class).semanticVariable();
PainlessCast painlessCast = scriptScope.hasDecoration(userEachNode, ExpressionPainlessCast.class)
? scriptScope.getDecoration(userEachNode, ExpressionPainlessCast.class).getExpressionPainlessCast()
? scriptScope.getDecoration(userEachNode, ExpressionPainlessCast.class).expressionPainlessCast()
: null;
ExpressionNode irIterableNode = (ExpressionNode) visit(userEachNode.getIterableNode(), scriptScope);
Class<?> iterableValueType = scriptScope.getDecoration(userEachNode.getIterableNode(), ValueType.class).getValueType();
Class<?> iterableValueType = scriptScope.getDecoration(userEachNode.getIterableNode(), ValueType.class).valueType();
BlockNode irBlockNode = (BlockNode) visit(userEachNode.getBlockNode(), scriptScope);
ConditionNode irConditionNode;
@ -742,8 +742,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ForEachSubArrayNode irForEachSubArrayNode = new ForEachSubArrayNode(userEachNode.getLocation());
irForEachSubArrayNode.setConditionNode(irIterableNode);
irForEachSubArrayNode.setBlockNode(irBlockNode);
irForEachSubArrayNode.attachDecoration(new IRDVariableType(variable.getType()));
irForEachSubArrayNode.attachDecoration(new IRDVariableName(variable.getName()));
irForEachSubArrayNode.attachDecoration(new IRDVariableType(variable.type()));
irForEachSubArrayNode.attachDecoration(new IRDVariableName(variable.name()));
irForEachSubArrayNode.attachDecoration(new IRDArrayType(iterableValueType));
irForEachSubArrayNode.attachDecoration(new IRDArrayName("#array" + userEachNode.getLocation().getOffset()));
irForEachSubArrayNode.attachDecoration(new IRDIndexType(int.class));
@ -759,14 +759,14 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ForEachSubIterableNode irForEachSubIterableNode = new ForEachSubIterableNode(userEachNode.getLocation());
irForEachSubIterableNode.setConditionNode(irIterableNode);
irForEachSubIterableNode.setBlockNode(irBlockNode);
irForEachSubIterableNode.attachDecoration(new IRDVariableType(variable.getType()));
irForEachSubIterableNode.attachDecoration(new IRDVariableName(variable.getName()));
irForEachSubIterableNode.attachDecoration(new IRDVariableType(variable.type()));
irForEachSubIterableNode.attachDecoration(new IRDVariableName(variable.name()));
irForEachSubIterableNode.attachDecoration(new IRDIterableType(Iterator.class));
irForEachSubIterableNode.attachDecoration(new IRDIterableName("#itr" + userEachNode.getLocation().getOffset()));
if (iterableValueType != def.class) {
irForEachSubIterableNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userEachNode, IterablePainlessMethod.class).getIterablePainlessMethod())
new IRDMethod(scriptScope.getDecoration(userEachNode, IterablePainlessMethod.class).iterablePainlessMethod())
);
}
@ -798,12 +798,12 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitDeclaration(SDeclaration userDeclarationNode, ScriptScope scriptScope) {
Variable variable = scriptScope.getDecoration(userDeclarationNode, SemanticVariable.class).getSemanticVariable();
Variable variable = scriptScope.getDecoration(userDeclarationNode, SemanticVariable.class).semanticVariable();
DeclarationNode irDeclarationNode = new DeclarationNode(userDeclarationNode.getLocation());
irDeclarationNode.setExpressionNode(injectCast(userDeclarationNode.getValueNode(), scriptScope));
irDeclarationNode.attachDecoration(new IRDDeclarationType(variable.getType()));
irDeclarationNode.attachDecoration(new IRDName(variable.getName()));
irDeclarationNode.attachDecoration(new IRDDeclarationType(variable.type()));
irDeclarationNode.attachDecoration(new IRDName(variable.name()));
scriptScope.putDecoration(userDeclarationNode, new IRNodeDecoration(irDeclarationNode));
}
@ -849,11 +849,11 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitCatch(SCatch userCatchNode, ScriptScope scriptScope) {
Variable variable = scriptScope.getDecoration(userCatchNode, SemanticVariable.class).getSemanticVariable();
Variable variable = scriptScope.getDecoration(userCatchNode, SemanticVariable.class).semanticVariable();
CatchNode irCatchNode = new CatchNode(userCatchNode.getLocation());
irCatchNode.attachDecoration(new IRDExceptionType(variable.getType()));
irCatchNode.attachDecoration(new IRDSymbol(variable.getName()));
irCatchNode.attachDecoration(new IRDExceptionType(variable.type()));
irCatchNode.attachDecoration(new IRDSymbol(variable.name()));
irCatchNode.setBlockNode((BlockNode) visit(userCatchNode.getBlockNode(), scriptScope));
scriptScope.putDecoration(userCatchNode, new IRNodeDecoration(irCatchNode));
@ -885,7 +885,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
public void visitAssignment(EAssignment userAssignmentNode, ScriptScope scriptScope) {
boolean read = scriptScope.getCondition(userAssignmentNode, Read.class);
Class<?> compoundType = scriptScope.hasDecoration(userAssignmentNode, CompoundType.class)
? scriptScope.getDecoration(userAssignmentNode, CompoundType.class).getCompoundType()
? scriptScope.getDecoration(userAssignmentNode, CompoundType.class).compoundType()
: null;
ExpressionNode irAssignmentNode;
@ -923,7 +923,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
PainlessCast downcast = scriptScope.hasDecoration(userAssignmentNode, DowncastPainlessCast.class)
? scriptScope.getDecoration(userAssignmentNode, DowncastPainlessCast.class).getDowncastPainlessCast()
? scriptScope.getDecoration(userAssignmentNode, DowncastPainlessCast.class).downcastPainlessCast()
: null;
// no need to downcast so the binary math node is the value for the store node
@ -941,7 +941,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
// the value is also read from this assignment
if (read) {
int accessDepth = scriptScope.getDecoration(userAssignmentNode.getLeftNode(), AccessDepth.class).getAccessDepth();
int accessDepth = scriptScope.getDecoration(userAssignmentNode.getLeftNode(), AccessDepth.class).accessDepth();
DupNode irDupNode;
// the value is read from prior to assignment (post-increment)
@ -966,7 +966,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
PainlessCast upcast = scriptScope.hasDecoration(userAssignmentNode, UpcastPainlessCast.class)
? scriptScope.getDecoration(userAssignmentNode, UpcastPainlessCast.class).getUpcastPainlessCast()
? scriptScope.getDecoration(userAssignmentNode, UpcastPainlessCast.class).upcastPainlessCast()
: null;
// upcast the stored value if necessary
@ -996,7 +996,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
// the value is read from after the assignment
if (read) {
int size = MethodWriter.getType(irValueNode.getDecorationValue(IRDExpressionType.class)).getSize();
int accessDepth = scriptScope.getDecoration(userAssignmentNode.getLeftNode(), AccessDepth.class).getAccessDepth();
int accessDepth = scriptScope.getDecoration(userAssignmentNode.getLeftNode(), AccessDepth.class).accessDepth();
DupNode irDupNode = new DupNode(irValueNode.getLocation());
irDupNode.attachDecoration(irValueNode.getDecoration(IRDExpressionType.class));
@ -1019,7 +1019,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitUnary(EUnary userUnaryNode, ScriptScope scriptScope) {
Class<?> unaryType = scriptScope.hasDecoration(userUnaryNode, UnaryType.class)
? scriptScope.getDecoration(userUnaryNode, UnaryType.class).getUnaryType()
? scriptScope.getDecoration(userUnaryNode, UnaryType.class).unaryType()
: null;
IRNode irNode;
@ -1028,9 +1028,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irNode = visit(userUnaryNode.getChildNode(), scriptScope);
} else {
UnaryMathNode irUnaryMathNode = new UnaryMathNode(userUnaryNode.getLocation());
irUnaryMathNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userUnaryNode, ValueType.class).getValueType())
);
irUnaryMathNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userUnaryNode, ValueType.class).valueType()));
if (unaryType != null) {
irUnaryMathNode.attachDecoration(new IRDUnaryType(unaryType));
@ -1054,7 +1052,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ExpressionNode irExpressionNode;
Operation operation = userBinaryNode.getOperation();
Class<?> valueType = scriptScope.getDecoration(userBinaryNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userBinaryNode, ValueType.class).valueType();
if (operation == Operation.ADD && valueType == String.class) {
StringConcatenationNode stringConcatenationNode = new StringConcatenationNode(userBinaryNode.getLocation());
@ -1062,9 +1060,9 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
stringConcatenationNode.addArgumentNode((ExpressionNode) visit(userBinaryNode.getRightNode(), scriptScope));
irExpressionNode = stringConcatenationNode;
} else {
Class<?> binaryType = scriptScope.getDecoration(userBinaryNode, BinaryType.class).getBinaryType();
Class<?> binaryType = scriptScope.getDecoration(userBinaryNode, BinaryType.class).binaryType();
Class<?> shiftType = scriptScope.hasDecoration(userBinaryNode, ShiftType.class)
? scriptScope.getDecoration(userBinaryNode, ShiftType.class).getShiftType()
? scriptScope.getDecoration(userBinaryNode, ShiftType.class).shiftType()
: null;
BinaryMathNode irBinaryMathNode = new BinaryMathNode(userBinaryNode.getLocation());
@ -1096,7 +1094,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitBooleanComp(EBooleanComp userBooleanCompNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userBooleanCompNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userBooleanCompNode, ValueType.class).valueType();
BooleanNode irBooleanNode = new BooleanNode(userBooleanCompNode.getLocation());
irBooleanNode.attachDecoration(new IRDExpressionType(valueType));
@ -1110,9 +1108,9 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitComp(EComp userCompNode, ScriptScope scriptScope) {
ComparisonNode irComparisonNode = new ComparisonNode(userCompNode.getLocation());
irComparisonNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userCompNode, ValueType.class).getValueType()));
irComparisonNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userCompNode, ValueType.class).valueType()));
irComparisonNode.attachDecoration(
new IRDComparisonType(scriptScope.getDecoration(userCompNode, ComparisonType.class).getComparisonType())
new IRDComparisonType(scriptScope.getDecoration(userCompNode, ComparisonType.class).comparisonType())
);
irComparisonNode.attachDecoration(new IRDOperation(userCompNode.getOperation()));
irComparisonNode.setLeftNode(injectCast(userCompNode.getLeftNode(), scriptScope));
@ -1128,8 +1126,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitInstanceof(EInstanceof userInstanceofNode, ScriptScope scriptScope) {
Class<?> valuetype = scriptScope.getDecoration(userInstanceofNode, ValueType.class).getValueType();
Class<?> instanceType = scriptScope.getDecoration(userInstanceofNode, InstanceType.class).getInstanceType();
Class<?> valuetype = scriptScope.getDecoration(userInstanceofNode, ValueType.class).valueType();
Class<?> instanceType = scriptScope.getDecoration(userInstanceofNode, InstanceType.class).instanceType();
InstanceofNode irInstanceofNode = new InstanceofNode(userInstanceofNode.getLocation());
irInstanceofNode.attachDecoration(new IRDExpressionType(valuetype));
@ -1143,7 +1141,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
public void visitConditional(EConditional userConditionalNode, ScriptScope scriptScope) {
ConditionalNode irConditionalNode = new ConditionalNode(userConditionalNode.getLocation());
irConditionalNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userConditionalNode, ValueType.class).getValueType())
new IRDExpressionType(scriptScope.getDecoration(userConditionalNode, ValueType.class).valueType())
);
irConditionalNode.setConditionNode(injectCast(userConditionalNode.getConditionNode(), scriptScope));
irConditionalNode.setLeftNode(injectCast(userConditionalNode.getTrueNode(), scriptScope));
@ -1155,7 +1153,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitElvis(EElvis userElvisNode, ScriptScope scriptScope) {
ElvisNode irElvisNode = new ElvisNode(userElvisNode.getLocation());
irElvisNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userElvisNode, ValueType.class).getValueType()));
irElvisNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userElvisNode, ValueType.class).valueType()));
irElvisNode.setLeftNode(injectCast(userElvisNode.getLeftNode(), scriptScope));
irElvisNode.setRightNode(injectCast(userElvisNode.getRightNode(), scriptScope));
@ -1167,15 +1165,13 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ListInitializationNode irListInitializationNode = new ListInitializationNode(userListInitNode.getLocation());
irListInitializationNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userListInitNode, ValueType.class).getValueType())
new IRDExpressionType(scriptScope.getDecoration(userListInitNode, ValueType.class).valueType())
);
irListInitializationNode.attachDecoration(
new IRDConstructor(
scriptScope.getDecoration(userListInitNode, StandardPainlessConstructor.class).getStandardPainlessConstructor()
)
new IRDConstructor(scriptScope.getDecoration(userListInitNode, StandardPainlessConstructor.class).standardPainlessConstructor())
);
irListInitializationNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userListInitNode, StandardPainlessMethod.class).getStandardPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userListInitNode, StandardPainlessMethod.class).standardPainlessMethod())
);
for (AExpression userValueNode : userListInitNode.getValueNodes()) {
@ -1190,15 +1186,13 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
MapInitializationNode irMapInitializationNode = new MapInitializationNode(userMapInitNode.getLocation());
irMapInitializationNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userMapInitNode, ValueType.class).getValueType())
new IRDExpressionType(scriptScope.getDecoration(userMapInitNode, ValueType.class).valueType())
);
irMapInitializationNode.attachDecoration(
new IRDConstructor(
scriptScope.getDecoration(userMapInitNode, StandardPainlessConstructor.class).getStandardPainlessConstructor()
)
new IRDConstructor(scriptScope.getDecoration(userMapInitNode, StandardPainlessConstructor.class).standardPainlessConstructor())
);
irMapInitializationNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userMapInitNode, StandardPainlessMethod.class).getStandardPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userMapInitNode, StandardPainlessMethod.class).standardPainlessMethod())
);
for (int i = 0; i < userMapInitNode.getKeyNodes().size(); ++i) {
@ -1215,7 +1209,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
public void visitNewArray(ENewArray userNewArrayNode, ScriptScope scriptScope) {
NewArrayNode irNewArrayNode = new NewArrayNode(userNewArrayNode.getLocation());
irNewArrayNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userNewArrayNode, ValueType.class).getValueType()));
irNewArrayNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userNewArrayNode, ValueType.class).valueType()));
if (userNewArrayNode.isInitializer()) {
irNewArrayNode.attachCondition(IRCInitialize.class);
@ -1230,9 +1224,9 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitNewObj(ENewObj userNewObjectNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userNewObjectNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userNewObjectNode, ValueType.class).valueType();
PainlessConstructor painlessConstructor = scriptScope.getDecoration(userNewObjectNode, StandardPainlessConstructor.class)
.getStandardPainlessConstructor();
.standardPainlessConstructor();
NewObjectNode irNewObjectNode = new NewObjectNode(userNewObjectNode.getLocation());
irNewObjectNode.attachDecoration(new IRDExpressionType(valueType));
@ -1254,29 +1248,28 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(callLocalNode.getLocation());
if (scriptScope.hasDecoration(callLocalNode, StandardLocalFunction.class)) {
LocalFunction localFunction = scriptScope.getDecoration(callLocalNode, StandardLocalFunction.class).getLocalFunction();
LocalFunction localFunction = scriptScope.getDecoration(callLocalNode, StandardLocalFunction.class).localFunction();
irInvokeCallMemberNode.attachDecoration(new IRDFunction(localFunction));
} else if (scriptScope.hasDecoration(callLocalNode, ThisPainlessMethod.class)) {
PainlessMethod thisMethod = scriptScope.getDecoration(callLocalNode, ThisPainlessMethod.class).getThisPainlessMethod();
PainlessMethod thisMethod = scriptScope.getDecoration(callLocalNode, ThisPainlessMethod.class).thisPainlessMethod();
irInvokeCallMemberNode.attachDecoration(new IRDThisMethod(thisMethod));
} else if (scriptScope.hasDecoration(callLocalNode, StandardPainlessMethod.class)) {
PainlessMethod importedMethod = scriptScope.getDecoration(callLocalNode, StandardPainlessMethod.class)
.getStandardPainlessMethod();
PainlessMethod importedMethod = scriptScope.getDecoration(callLocalNode, StandardPainlessMethod.class).standardPainlessMethod();
irInvokeCallMemberNode.attachDecoration(new IRDMethod(importedMethod));
} else if (scriptScope.hasDecoration(callLocalNode, StandardPainlessClassBinding.class)) {
PainlessClassBinding painlessClassBinding = scriptScope.getDecoration(callLocalNode, StandardPainlessClassBinding.class)
.getPainlessClassBinding();
.painlessClassBinding();
String bindingName = scriptScope.getNextSyntheticName("class_binding");
FieldNode irFieldNode = new FieldNode(callLocalNode.getLocation());
irFieldNode.attachDecoration(new IRDModifiers(Modifier.PRIVATE));
irFieldNode.attachDecoration(new IRDFieldType(painlessClassBinding.javaConstructor.getDeclaringClass()));
irFieldNode.attachDecoration(new IRDFieldType(painlessClassBinding.javaConstructor().getDeclaringClass()));
irFieldNode.attachDecoration(new IRDName(bindingName));
irClassNode.addFieldNode(irFieldNode);
irInvokeCallMemberNode.attachDecoration(new IRDClassBinding(painlessClassBinding));
if ((int) scriptScope.getDecoration(callLocalNode, StandardConstant.class).getStandardConstant() == 0) {
if ((int) scriptScope.getDecoration(callLocalNode, StandardConstant.class).standardConstant() == 0) {
irInvokeCallMemberNode.attachCondition(IRCStatic.class);
}
@ -1285,19 +1278,19 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
PainlessInstanceBinding painlessInstanceBinding = scriptScope.getDecoration(
callLocalNode,
StandardPainlessInstanceBinding.class
).getPainlessInstanceBinding();
).painlessInstanceBinding();
String bindingName = scriptScope.getNextSyntheticName("instance_binding");
FieldNode irFieldNode = new FieldNode(callLocalNode.getLocation());
irFieldNode.attachDecoration(new IRDModifiers(Modifier.PUBLIC | Modifier.STATIC));
irFieldNode.attachDecoration(new IRDFieldType(painlessInstanceBinding.targetInstance.getClass()));
irFieldNode.attachDecoration(new IRDFieldType(painlessInstanceBinding.targetInstance().getClass()));
irFieldNode.attachDecoration(new IRDName(bindingName));
irClassNode.addFieldNode(irFieldNode);
irInvokeCallMemberNode.attachDecoration(new IRDInstanceBinding(painlessInstanceBinding));
irInvokeCallMemberNode.attachDecoration(new IRDName(bindingName));
scriptScope.addStaticConstant(bindingName, painlessInstanceBinding.targetInstance);
scriptScope.addStaticConstant(bindingName, painlessInstanceBinding.targetInstance());
} else {
throw callLocalNode.createError(new IllegalStateException("illegal tree structure"));
}
@ -1306,7 +1299,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irInvokeCallMemberNode.addArgumentNode(injectCast(userArgumentNode, scriptScope));
}
Class<?> valueType = scriptScope.getDecoration(callLocalNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(callLocalNode, ValueType.class).valueType();
irInvokeCallMemberNode.attachDecoration(new IRDExpressionType(valueType));
scriptScope.putDecoration(callLocalNode, new IRNodeDecoration(irInvokeCallMemberNode));
@ -1314,8 +1307,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitBooleanConstant(EBooleanConstant userBooleanConstantNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userBooleanConstantNode, ValueType.class).getValueType();
Object constant = scriptScope.getDecoration(userBooleanConstantNode, StandardConstant.class).getStandardConstant();
Class<?> valueType = scriptScope.getDecoration(userBooleanConstantNode, ValueType.class).valueType();
Object constant = scriptScope.getDecoration(userBooleanConstantNode, StandardConstant.class).standardConstant();
ConstantNode irConstantNode = new ConstantNode(userBooleanConstantNode.getLocation());
irConstantNode.attachDecoration(new IRDExpressionType(valueType));
@ -1326,8 +1319,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitNumeric(ENumeric userNumericNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userNumericNode, ValueType.class).getValueType();
Object constant = scriptScope.getDecoration(userNumericNode, StandardConstant.class).getStandardConstant();
Class<?> valueType = scriptScope.getDecoration(userNumericNode, ValueType.class).valueType();
Object constant = scriptScope.getDecoration(userNumericNode, StandardConstant.class).standardConstant();
ConstantNode irConstantNode = new ConstantNode(userNumericNode.getLocation());
irConstantNode.attachDecoration(new IRDExpressionType(valueType));
@ -1338,8 +1331,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitDecimal(EDecimal userDecimalNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userDecimalNode, ValueType.class).getValueType();
Object constant = scriptScope.getDecoration(userDecimalNode, StandardConstant.class).getStandardConstant();
Class<?> valueType = scriptScope.getDecoration(userDecimalNode, ValueType.class).valueType();
Object constant = scriptScope.getDecoration(userDecimalNode, StandardConstant.class).standardConstant();
ConstantNode irConstantNode = new ConstantNode(userDecimalNode.getLocation());
irConstantNode.attachDecoration(new IRDExpressionType(valueType));
@ -1350,8 +1343,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitString(EString userStringNode, ScriptScope scriptScope) {
Class<?> valueType = scriptScope.getDecoration(userStringNode, ValueType.class).getValueType();
Object constant = scriptScope.getDecoration(userStringNode, StandardConstant.class).getStandardConstant();
Class<?> valueType = scriptScope.getDecoration(userStringNode, ValueType.class).valueType();
Object constant = scriptScope.getDecoration(userStringNode, StandardConstant.class).standardConstant();
ConstantNode irConstantNode = new ConstantNode(userStringNode.getLocation());
irConstantNode.attachDecoration(new IRDExpressionType(valueType));
@ -1363,7 +1356,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
@Override
public void visitNull(ENull userNullNode, ScriptScope scriptScope) {
NullNode irNullNode = new NullNode(userNullNode.getLocation());
irNullNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userNullNode, ValueType.class).getValueType()));
irNullNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userNullNode, ValueType.class).valueType()));
scriptScope.putDecoration(userNullNode, new IRNodeDecoration(irNullNode));
}
@ -1372,7 +1365,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
public void visitRegex(ERegex userRegexNode, ScriptScope scriptScope) {
ConstantNode constant = new ConstantNode(userRegexNode.getLocation());
constant.attachDecoration(new IRDExpressionType(Pattern.class));
constant.attachDecoration(new IRDConstant(scriptScope.getDecoration(userRegexNode, StandardConstant.class).getStandardConstant()));
constant.attachDecoration(new IRDConstant(scriptScope.getDecoration(userRegexNode, StandardConstant.class).standardConstant()));
scriptScope.putDecoration(userRegexNode, new IRNodeDecoration(constant));
}
@ -1383,26 +1376,26 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
if (scriptScope.hasDecoration(userLambdaNode, TargetType.class)) {
TypedInterfaceReferenceNode typedInterfaceReferenceNode = new TypedInterfaceReferenceNode(userLambdaNode.getLocation());
typedInterfaceReferenceNode.attachDecoration(
new IRDReference(scriptScope.getDecoration(userLambdaNode, ReferenceDecoration.class).getReference())
new IRDReference(scriptScope.getDecoration(userLambdaNode, ReferenceDecoration.class).reference())
);
irExpressionNode = typedInterfaceReferenceNode;
} else {
DefInterfaceReferenceNode defInterfaceReferenceNode = new DefInterfaceReferenceNode(userLambdaNode.getLocation());
defInterfaceReferenceNode.attachDecoration(
new IRDDefReferenceEncoding(scriptScope.getDecoration(userLambdaNode, EncodingDecoration.class).getEncoding())
new IRDDefReferenceEncoding(scriptScope.getDecoration(userLambdaNode, EncodingDecoration.class).encoding())
);
irExpressionNode = defInterfaceReferenceNode;
}
FunctionNode irFunctionNode = new FunctionNode(userLambdaNode.getLocation());
irFunctionNode.setBlockNode((BlockNode) visit(userLambdaNode.getBlockNode(), scriptScope));
irFunctionNode.attachDecoration(new IRDName(scriptScope.getDecoration(userLambdaNode, MethodNameDecoration.class).getMethodName()));
irFunctionNode.attachDecoration(new IRDReturnType(scriptScope.getDecoration(userLambdaNode, ReturnType.class).getReturnType()));
irFunctionNode.attachDecoration(new IRDName(scriptScope.getDecoration(userLambdaNode, MethodNameDecoration.class).methodName()));
irFunctionNode.attachDecoration(new IRDReturnType(scriptScope.getDecoration(userLambdaNode, ReturnType.class).returnType()));
irFunctionNode.attachDecoration(
new IRDTypeParameters(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, TypeParameters.class).getTypeParameters()))
new IRDTypeParameters(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, TypeParameters.class).typeParameters()))
);
irFunctionNode.attachDecoration(
new IRDParameterNames(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, ParameterNames.class).getParameterNames()))
new IRDParameterNames(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, ParameterNames.class).parameterNames()))
);
if (scriptScope.getCondition(userLambdaNode, InstanceCapturingLambda.class)) {
irFunctionNode.attachCondition(IRCInstanceCapture.class);
@ -1414,15 +1407,15 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irFunctionNode.attachDecoration(new IRDMaxLoopCounter(scriptScope.getCompilerSettings().getMaxLoopCounter()));
irClassNode.addFunctionNode(irFunctionNode);
irExpressionNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userLambdaNode, ValueType.class).getValueType()));
irExpressionNode.attachDecoration(new IRDExpressionType(scriptScope.getDecoration(userLambdaNode, ValueType.class).valueType()));
List<Variable> captures = scriptScope.getDecoration(userLambdaNode, CapturesDecoration.class).getCaptures();
List<Variable> captures = scriptScope.getDecoration(userLambdaNode, CapturesDecoration.class).captures();
if (captures.isEmpty() == false) {
List<String> captureNames = new ArrayList<>();
for (Variable capture : captures) {
captureNames.add(capture.getName());
captureNames.add(capture.name());
}
irExpressionNode.attachDecoration(new IRDCaptureNames(captureNames));
@ -1439,19 +1432,19 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
CapturesDecoration capturesDecoration = scriptScope.getDecoration(userFunctionRefNode, CapturesDecoration.class);
if (targetType == null) {
Def.Encoding encoding = scriptScope.getDecoration(userFunctionRefNode, EncodingDecoration.class).getEncoding();
Def.Encoding encoding = scriptScope.getDecoration(userFunctionRefNode, EncodingDecoration.class).encoding();
DefInterfaceReferenceNode defInterfaceReferenceNode = new DefInterfaceReferenceNode(userFunctionRefNode.getLocation());
defInterfaceReferenceNode.attachDecoration(new IRDDefReferenceEncoding(encoding));
if (scriptScope.getCondition(userFunctionRefNode, InstanceCapturingFunctionRef.class)) {
defInterfaceReferenceNode.attachCondition(IRCInstanceCapture.class);
}
irReferenceNode = defInterfaceReferenceNode;
} else if (capturesDecoration != null && capturesDecoration.getCaptures().get(0).getType() == def.class) {
} else if (capturesDecoration != null && capturesDecoration.captures().get(0).type() == def.class) {
TypedCaptureReferenceNode typedCaptureReferenceNode = new TypedCaptureReferenceNode(userFunctionRefNode.getLocation());
typedCaptureReferenceNode.attachDecoration(new IRDName(userFunctionRefNode.getMethodName()));
irReferenceNode = typedCaptureReferenceNode;
} else {
FunctionRef reference = scriptScope.getDecoration(userFunctionRefNode, ReferenceDecoration.class).getReference();
FunctionRef reference = scriptScope.getDecoration(userFunctionRefNode, ReferenceDecoration.class).reference();
TypedInterfaceReferenceNode typedInterfaceReferenceNode = new TypedInterfaceReferenceNode(userFunctionRefNode.getLocation());
typedInterfaceReferenceNode.attachDecoration(new IRDReference(reference));
if (scriptScope.getCondition(userFunctionRefNode, InstanceCapturingFunctionRef.class)) {
@ -1461,13 +1454,11 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
irReferenceNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userFunctionRefNode, ValueType.class).getValueType())
new IRDExpressionType(scriptScope.getDecoration(userFunctionRefNode, ValueType.class).valueType())
);
if (capturesDecoration != null) {
irReferenceNode.attachDecoration(
new IRDCaptureNames(Collections.singletonList(capturesDecoration.getCaptures().get(0).getName()))
);
irReferenceNode.attachDecoration(new IRDCaptureNames(Collections.singletonList(capturesDecoration.captures().get(0).name())));
if (scriptScope.getCondition(userFunctionRefNode, CaptureBox.class)) {
irReferenceNode.attachCondition(IRCCaptureBox.class);
@ -1485,17 +1476,17 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
TypedInterfaceReferenceNode typedInterfaceReferenceNode = new TypedInterfaceReferenceNode(
userNewArrayFunctionRefNode.getLocation()
);
FunctionRef reference = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReferenceDecoration.class).getReference();
FunctionRef reference = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReferenceDecoration.class).reference();
typedInterfaceReferenceNode.attachDecoration(new IRDReference(reference));
irReferenceNode = typedInterfaceReferenceNode;
} else {
Def.Encoding encoding = scriptScope.getDecoration(userNewArrayFunctionRefNode, EncodingDecoration.class).getEncoding();
Def.Encoding encoding = scriptScope.getDecoration(userNewArrayFunctionRefNode, EncodingDecoration.class).encoding();
DefInterfaceReferenceNode defInterfaceReferenceNode = new DefInterfaceReferenceNode(userNewArrayFunctionRefNode.getLocation());
defInterfaceReferenceNode.attachDecoration(new IRDDefReferenceEncoding(encoding));
irReferenceNode = defInterfaceReferenceNode;
}
Class<?> returnType = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReturnType.class).getReturnType();
Class<?> returnType = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReturnType.class).returnType();
LoadVariableNode irLoadVariableNode = new LoadVariableNode(userNewArrayFunctionRefNode.getLocation());
irLoadVariableNode.attachDecoration(new IRDExpressionType(int.class));
@ -1514,7 +1505,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
FunctionNode irFunctionNode = new FunctionNode(userNewArrayFunctionRefNode.getLocation());
irFunctionNode.attachDecoration(
new IRDName(scriptScope.getDecoration(userNewArrayFunctionRefNode, MethodNameDecoration.class).getMethodName())
new IRDName(scriptScope.getDecoration(userNewArrayFunctionRefNode, MethodNameDecoration.class).methodName())
);
irFunctionNode.attachDecoration(new IRDReturnType(returnType));
irFunctionNode.attachDecoration(new IRDTypeParameters(Collections.singletonList(int.class)));
@ -1527,7 +1518,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irClassNode.addFunctionNode(irFunctionNode);
irReferenceNode.attachDecoration(
new IRDExpressionType(scriptScope.getDecoration(userNewArrayFunctionRefNode, ValueType.class).getValueType())
new IRDExpressionType(scriptScope.getDecoration(userNewArrayFunctionRefNode, ValueType.class).valueType())
);
scriptScope.putDecoration(userNewArrayFunctionRefNode, new IRNodeDecoration(irReferenceNode));
@ -1542,7 +1533,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ExpressionNode irExpressionNode;
if (scriptScope.hasDecoration(userSymbolNode, StaticType.class)) {
Class<?> staticType = scriptScope.getDecoration(userSymbolNode, StaticType.class).getStaticType();
Class<?> staticType = scriptScope.getDecoration(userSymbolNode, StaticType.class).staticType();
StaticNode staticNode = new StaticNode(userSymbolNode.getLocation());
staticNode.attachDecoration(new IRDExpressionType(staticType));
irExpressionNode = staticNode;
@ -1552,7 +1543,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
boolean compound = scriptScope.getCondition(userSymbolNode, Compound.class);
Location location = userSymbolNode.getLocation();
String symbol = userSymbolNode.getSymbol();
Class<?> valueType = scriptScope.getDecoration(userSymbolNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userSymbolNode, ValueType.class).valueType();
UnaryNode irStoreNode = null;
ExpressionNode irLoadNode = null;
@ -1590,7 +1581,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ExpressionNode irExpressionNode;
if (scriptScope.hasDecoration(userDotNode, StaticType.class)) {
Class<?> staticType = scriptScope.getDecoration(userDotNode, StaticType.class).getStaticType();
Class<?> staticType = scriptScope.getDecoration(userDotNode, StaticType.class).staticType();
StaticNode staticNode = new StaticNode(userDotNode.getLocation());
staticNode.attachDecoration(new IRDExpressionType(staticType));
irExpressionNode = staticNode;
@ -1600,7 +1591,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
boolean compound = scriptScope.getCondition(userDotNode, Compound.class);
Location location = userDotNode.getLocation();
String index = userDotNode.getIndex();
Class<?> valueType = scriptScope.getDecoration(userDotNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userDotNode, ValueType.class).valueType();
ValueType prefixValueType = scriptScope.getDecoration(userDotNode.getPrefixNode(), ValueType.class);
ExpressionNode irPrefixNode = (ExpressionNode) visit(userDotNode.getPrefixNode(), scriptScope);
@ -1609,13 +1600,13 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ExpressionNode irLoadNode = null;
int accessDepth;
if (prefixValueType != null && prefixValueType.getValueType().isArray()) {
if (prefixValueType != null && prefixValueType.valueType().isArray()) {
LoadDotArrayLengthNode irLoadDotArrayLengthNode = new LoadDotArrayLengthNode(location);
irLoadDotArrayLengthNode.attachDecoration(new IRDExpressionType(int.class));
irLoadNode = irLoadDotArrayLengthNode;
accessDepth = 1;
} else if (prefixValueType != null && prefixValueType.getValueType() == def.class) {
} else if (prefixValueType != null && prefixValueType.valueType() == def.class) {
if (write || compound) {
StoreDotDefNode irStoreDotDefNode = new StoreDotDefNode(location);
irStoreDotDefNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
@ -1633,8 +1624,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
accessDepth = 1;
} else if (scriptScope.hasDecoration(userDotNode, StandardPainlessField.class)) {
PainlessField painlessField = scriptScope.getDecoration(userDotNode, StandardPainlessField.class)
.getStandardPainlessField();
PainlessField painlessField = scriptScope.getDecoration(userDotNode, StandardPainlessField.class).standardPainlessField();
if (write || compound) {
StoreDotNode irStoreDotNode = new StoreDotNode(location);
@ -1658,7 +1648,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irStoreDotShortcutNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
irStoreDotShortcutNode.attachDecoration(new IRDStoreType(valueType));
irStoreDotShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).getSetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).setterPainlessMethod())
);
irStoreNode = irStoreDotShortcutNode;
}
@ -1667,7 +1657,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
LoadDotShortcutNode irLoadDotShortcutNode = new LoadDotShortcutNode(location);
irLoadDotShortcutNode.attachDecoration(new IRDExpressionType(valueType));
irLoadDotShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getGetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getterPainlessMethod())
);
irLoadNode = irLoadDotShortcutNode;
}
@ -1684,7 +1674,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irStoreMapShortcutNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
irStoreMapShortcutNode.attachDecoration(new IRDStoreType(valueType));
irStoreMapShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).getSetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).setterPainlessMethod())
);
irStoreNode = irStoreMapShortcutNode;
}
@ -1693,7 +1683,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
LoadMapShortcutNode irLoadMapShortcutNode = new LoadMapShortcutNode(location);
irLoadMapShortcutNode.attachDecoration(new IRDExpressionType(valueType));
irLoadMapShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getGetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getterPainlessMethod())
);
irLoadNode = irLoadMapShortcutNode;
}
@ -1703,7 +1693,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ConstantNode irConstantNode = new ConstantNode(location);
irConstantNode.attachDecoration(new IRDExpressionType(int.class));
irConstantNode.attachDecoration(
new IRDConstant(scriptScope.getDecoration(userDotNode, StandardConstant.class).getStandardConstant())
new IRDConstant(scriptScope.getDecoration(userDotNode, StandardConstant.class).standardConstant())
);
irIndexNode = irConstantNode;
@ -1712,7 +1702,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irStoreListShortcutNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
irStoreListShortcutNode.attachDecoration(new IRDStoreType(valueType));
irStoreListShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).getSetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, SetterPainlessMethod.class).setterPainlessMethod())
);
irStoreNode = irStoreListShortcutNode;
}
@ -1721,7 +1711,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
LoadListShortcutNode irLoadListShortcutNode = new LoadListShortcutNode(location);
irLoadListShortcutNode.attachDecoration(new IRDExpressionType(valueType));
irLoadListShortcutNode.attachDecoration(
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getGetterPainlessMethod())
new IRDMethod(scriptScope.getDecoration(userDotNode, GetterPainlessMethod.class).getterPainlessMethod())
);
irLoadNode = irLoadListShortcutNode;
}
@ -1756,8 +1746,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
boolean write = scriptScope.getCondition(userBraceNode, Write.class);
boolean compound = scriptScope.getCondition(userBraceNode, Compound.class);
Location location = userBraceNode.getLocation();
Class<?> valueType = scriptScope.getDecoration(userBraceNode, ValueType.class).getValueType();
Class<?> prefixValueType = scriptScope.getDecoration(userBraceNode.getPrefixNode(), ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userBraceNode, ValueType.class).valueType();
Class<?> prefixValueType = scriptScope.getDecoration(userBraceNode.getPrefixNode(), ValueType.class).valueType();
ExpressionNode irPrefixNode = (ExpressionNode) visit(userBraceNode.getPrefixNode(), scriptScope);
ExpressionNode irIndexNode = injectCast(userBraceNode.getIndexNode(), scriptScope);
@ -1783,7 +1773,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irLoadNode = irLoadBraceNode;
}
} else if (prefixValueType == def.class) {
Class<?> indexType = scriptScope.getDecoration(userBraceNode.getIndexNode(), ValueType.class).getValueType();
Class<?> indexType = scriptScope.getDecoration(userBraceNode.getIndexNode(), ValueType.class).valueType();
FlipDefIndexNode irFlipDefIndexNode = new FlipDefIndexNode(userBraceNode.getIndexNode().getLocation());
irFlipDefIndexNode.attachDecoration(new IRDExpressionType(indexType));
irFlipDefIndexNode.setChildNode(irIndexNode);
@ -1805,7 +1795,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
} else if (scriptScope.getCondition(userBraceNode, MapShortcut.class)) {
if (write || compound) {
PainlessMethod setter = scriptScope.getDecoration(userBraceNode, SetterPainlessMethod.class).getSetterPainlessMethod();
PainlessMethod setter = scriptScope.getDecoration(userBraceNode, SetterPainlessMethod.class).setterPainlessMethod();
StoreMapShortcutNode irStoreMapShortcutNode = new StoreMapShortcutNode(location);
irStoreMapShortcutNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
irStoreMapShortcutNode.attachDecoration(new IRDStoreType(valueType));
@ -1814,7 +1804,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
if (write == false || compound) {
PainlessMethod getter = scriptScope.getDecoration(userBraceNode, GetterPainlessMethod.class).getGetterPainlessMethod();
PainlessMethod getter = scriptScope.getDecoration(userBraceNode, GetterPainlessMethod.class).getterPainlessMethod();
LoadMapShortcutNode irLoadMapShortcutNode = new LoadMapShortcutNode(location);
irLoadMapShortcutNode.attachDecoration(new IRDExpressionType(valueType));
irLoadMapShortcutNode.attachDecoration(new IRDMethod(getter));
@ -1827,7 +1817,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
irIndexNode = irFlipCollectionIndexNode;
if (write || compound) {
PainlessMethod setter = scriptScope.getDecoration(userBraceNode, SetterPainlessMethod.class).getSetterPainlessMethod();
PainlessMethod setter = scriptScope.getDecoration(userBraceNode, SetterPainlessMethod.class).setterPainlessMethod();
StoreListShortcutNode irStoreListShortcutNode = new StoreListShortcutNode(location);
irStoreListShortcutNode.attachDecoration(new IRDExpressionType(read ? valueType : void.class));
irStoreListShortcutNode.attachDecoration(new IRDStoreType(valueType));
@ -1836,7 +1826,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
if (write == false || compound) {
PainlessMethod getter = scriptScope.getDecoration(userBraceNode, GetterPainlessMethod.class).getGetterPainlessMethod();
PainlessMethod getter = scriptScope.getDecoration(userBraceNode, GetterPainlessMethod.class).getterPainlessMethod();
LoadListShortcutNode irLoadListShortcutNode = new LoadListShortcutNode(location);
irLoadListShortcutNode.attachDecoration(new IRDExpressionType(valueType));
irLoadListShortcutNode.attachDecoration(new IRDMethod(getter));
@ -1859,7 +1849,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
ExpressionNode irExpressionNode;
ValueType prefixValueType = scriptScope.getDecoration(userCallNode.getPrefixNode(), ValueType.class);
Class<?> valueType = scriptScope.getDecoration(userCallNode, ValueType.class).getValueType();
Class<?> valueType = scriptScope.getDecoration(userCallNode, ValueType.class).valueType();
if (scriptScope.getCondition(userCallNode, DynamicInvocation.class)) {
InvokeCallDefNode irCallSubDefNode = new InvokeCallDefNode(userCallNode.getLocation());
@ -1875,16 +1865,16 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
Class<?> boxType;
if (prefixValueType != null) {
boxType = prefixValueType.getValueType();
boxType = prefixValueType.valueType();
} else {
boxType = scriptScope.getDecoration(userCallNode.getPrefixNode(), StaticType.class).getStaticType();
boxType = scriptScope.getDecoration(userCallNode.getPrefixNode(), StaticType.class).staticType();
}
InvokeCallNode irInvokeCallNode = new InvokeCallNode(userCallNode.getLocation());
PainlessMethod method = scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).getStandardPainlessMethod();
PainlessMethod method = scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).standardPainlessMethod();
Object[] injections = PainlessLookupUtility.buildInjections(method, scriptScope.getCompilerSettings().asMap());
Class<?>[] parameterTypes = method.javaMethod.getParameterTypes();
int augmentedOffset = method.javaMethod.getDeclaringClass() == method.targetClass ? 0 : 1;
Class<?>[] parameterTypes = method.javaMethod().getParameterTypes();
int augmentedOffset = method.javaMethod().getDeclaringClass() == method.targetClass() ? 0 : 1;
for (int i = 0; i < injections.length; i++) {
Object injection = injections[i];
@ -1905,7 +1895,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor<ScriptScope
}
irInvokeCallNode.attachDecoration(new IRDExpressionType(valueType));
irInvokeCallNode.setMethod(scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).getStandardPainlessMethod());
irInvokeCallNode.setMethod(scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).standardPainlessMethod());
irInvokeCallNode.setBox(boxType);
irExpressionNode = irInvokeCallNode;
}

View File

@ -123,7 +123,7 @@ public class PainlessSemanticAnalysisPhase extends DefaultSemanticAnalysisPhase
}
checkedVisit(userStatementNode, semanticScope);
Class<?> expressionValueType = semanticScope.getDecoration(userStatementNode, Decorations.ValueType.class).getValueType();
Class<?> expressionValueType = semanticScope.getDecoration(userStatementNode, Decorations.ValueType.class).valueType();
boolean rtn = lastSource && isVoid == false && expressionValueType != void.class;
if (rtn) {
@ -203,8 +203,8 @@ public class PainlessSemanticAnalysisPhase extends DefaultSemanticAnalysisPhase
ScriptClassInfo scriptClassInfo
) {
Location location = userExpressionNode.getLocation();
Class<?> valueType = semanticScope.getDecoration(userExpressionNode, Decorations.ValueType.class).getValueType();
Class<?> targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).getTargetType();
Class<?> valueType = semanticScope.getDecoration(userExpressionNode, Decorations.ValueType.class).valueType();
Class<?> targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).targetType();
PainlessCast painlessCast;
if (valueType == def.class) {

View File

@ -530,7 +530,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase
}
IRNodeDecoration irNodeDecoration = scriptScope.getDecoration(userStatementNode, IRNodeDecoration.class);
IRNode irNode = irNodeDecoration.getIRNode();
IRNode irNode = irNodeDecoration.irNode();
if ((irNode instanceof ReturnNode) == false) {
// Shouldn't have a Converter decoration if StatementExpressionNode, should be ReturnNode if explicit return
@ -541,7 +541,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase
// inject converter
InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(userStatementNode.getLocation());
irInvokeCallMemberNode.attachDecoration(new IRDFunction(converter.getConverter()));
irInvokeCallMemberNode.attachDecoration(new IRDFunction(converter.converter()));
ExpressionNode returnExpression = returnNode.getExpressionNode();
returnNode.setExpressionNode(irInvokeCallMemberNode);
irInvokeCallMemberNode.addArgumentNode(returnExpression);
@ -550,7 +550,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase
@Override
public void visitCallLocal(ECallLocal userCallLocalNode, ScriptScope scriptScope) {
if ("$".equals(userCallLocalNode.getMethodName())) {
PainlessMethod thisMethod = scriptScope.getDecoration(userCallLocalNode, ThisPainlessMethod.class).getThisPainlessMethod();
PainlessMethod thisMethod = scriptScope.getDecoration(userCallLocalNode, ThisPainlessMethod.class).thisPainlessMethod();
InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(userCallLocalNode.getLocation());
irInvokeCallMemberNode.attachDecoration(new IRDThisMethod(thisMethod));

View File

@ -80,17 +80,7 @@ public class Decorations {
}
public static class TargetType implements Decoration {
private final Class<?> targetType;
public TargetType(Class<?> targetType) {
this.targetType = Objects.requireNonNull(targetType);
}
public Class<?> getTargetType() {
return targetType;
}
public record TargetType(Class<?> targetType) implements Decoration {
public String getTargetCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(targetType);
@ -107,51 +97,22 @@ public class Decorations {
// standard output for user expression node during semantic phase
public static class ValueType implements Decoration {
private final Class<?> valueType;
public ValueType(Class<?> valueType) {
this.valueType = Objects.requireNonNull(valueType);
}
public Class<?> getValueType() {
return valueType;
}
public record ValueType(Class<?> valueType) implements Decoration {
public String getValueCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(valueType);
}
}
public static class StaticType implements Decoration {
private final Class<?> staticType;
public StaticType(Class<?> staticType) {
this.staticType = Objects.requireNonNull(staticType);
}
public Class<?> getStaticType() {
return staticType;
}
public record StaticType(Class<?> staticType) implements Decoration {
public String getStaticCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(staticType);
}
}
public static class PartialCanonicalTypeName implements Decoration {
public record PartialCanonicalTypeName(String partialCanonicalTypeName) implements Decoration {
private final String partialCanonicalTypeName;
public PartialCanonicalTypeName(String partialCanonicalTypeName) {
this.partialCanonicalTypeName = Objects.requireNonNull(partialCanonicalTypeName);
}
public String getPartialCanonicalTypeName() {
return partialCanonicalTypeName;
}
}
public interface DefOptimized extends Condition {
@ -176,381 +137,121 @@ public class Decorations {
}
public static class ExpressionPainlessCast implements Decoration {
public record ExpressionPainlessCast(PainlessCast expressionPainlessCast) implements Decoration {}
private final PainlessCast expressionPainlessCast;
public record SemanticVariable(Variable semanticVariable) implements Decoration {}
public ExpressionPainlessCast(PainlessCast expressionPainlessCast) {
this.expressionPainlessCast = Objects.requireNonNull(expressionPainlessCast);
}
public record IterablePainlessMethod(PainlessMethod iterablePainlessMethod) implements Decoration {}
public PainlessCast getExpressionPainlessCast() {
return expressionPainlessCast;
}
}
public static class SemanticVariable implements Decoration {
private final Variable semanticVariable;
public SemanticVariable(Variable semanticVariable) {
this.semanticVariable = semanticVariable;
}
public Variable getSemanticVariable() {
return semanticVariable;
}
}
public static class IterablePainlessMethod implements Decoration {
private final PainlessMethod iterablePainlessMethod;
public IterablePainlessMethod(PainlessMethod iterablePainlessMethod) {
this.iterablePainlessMethod = Objects.requireNonNull(iterablePainlessMethod);
}
public PainlessMethod getIterablePainlessMethod() {
return iterablePainlessMethod;
}
}
public static class UnaryType implements Decoration {
private final Class<?> unaryType;
public UnaryType(Class<?> unaryType) {
this.unaryType = Objects.requireNonNull(unaryType);
}
public Class<?> getUnaryType() {
return unaryType;
}
public record UnaryType(Class<?> unaryType) implements Decoration {
public String getUnaryCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(unaryType);
}
}
public static class BinaryType implements Decoration {
private final Class<?> binaryType;
public BinaryType(Class<?> binaryType) {
this.binaryType = Objects.requireNonNull(binaryType);
}
public Class<?> getBinaryType() {
return binaryType;
}
public record BinaryType(Class<?> binaryType) implements Decoration {
public String getBinaryCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(binaryType);
}
}
public static class ShiftType implements Decoration {
private final Class<?> shiftType;
public ShiftType(Class<?> shiftType) {
this.shiftType = Objects.requireNonNull(shiftType);
}
public Class<?> getShiftType() {
return shiftType;
}
public record ShiftType(Class<?> shiftType) implements Decoration {
public String getShiftCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(shiftType);
}
}
public static class ComparisonType implements Decoration {
private final Class<?> comparisonType;
public ComparisonType(Class<?> comparisonType) {
this.comparisonType = Objects.requireNonNull(comparisonType);
}
public Class<?> getComparisonType() {
return comparisonType;
}
public record ComparisonType(Class<?> comparisonType) implements Decoration {
public String getComparisonCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(comparisonType);
}
}
public static class CompoundType implements Decoration {
private final Class<?> compoundType;
public CompoundType(Class<?> compoundType) {
this.compoundType = Objects.requireNonNull(compoundType);
}
public Class<?> getCompoundType() {
return compoundType;
}
public record CompoundType(Class<?> compoundType) implements Decoration {
public String getCompoundCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(compoundType);
}
}
public static class UpcastPainlessCast implements Decoration {
public record UpcastPainlessCast(PainlessCast upcastPainlessCast) implements Decoration {}
private final PainlessCast upcastPainlessCast;
public UpcastPainlessCast(PainlessCast upcastPainlessCast) {
this.upcastPainlessCast = Objects.requireNonNull(upcastPainlessCast);
}
public PainlessCast getUpcastPainlessCast() {
return upcastPainlessCast;
}
}
public static class DowncastPainlessCast implements Decoration {
private final PainlessCast downcastPainlessCast;
public record DowncastPainlessCast(PainlessCast downcastPainlessCast) implements Decoration {
public DowncastPainlessCast(PainlessCast downcastPainlessCast) {
this.downcastPainlessCast = Objects.requireNonNull(downcastPainlessCast);
}
public PainlessCast getDowncastPainlessCast() {
return downcastPainlessCast;
}
}
public static class StandardPainlessField implements Decoration {
public record StandardPainlessField(PainlessField standardPainlessField) implements Decoration {}
private final PainlessField standardPainlessField;
public record StandardPainlessConstructor(PainlessConstructor standardPainlessConstructor) implements Decoration {}
public StandardPainlessField(PainlessField standardPainlessField) {
this.standardPainlessField = Objects.requireNonNull(standardPainlessField);
}
public record StandardPainlessMethod(PainlessMethod standardPainlessMethod) implements Decoration {}
public PainlessField getStandardPainlessField() {
return standardPainlessField;
}
}
public interface DynamicInvocation extends Condition {}
public static class StandardPainlessConstructor implements Decoration {
public record GetterPainlessMethod(PainlessMethod getterPainlessMethod) implements Decoration {}
private final PainlessConstructor standardPainlessConstructor;
public record SetterPainlessMethod(PainlessMethod setterPainlessMethod) implements Decoration {}
public StandardPainlessConstructor(PainlessConstructor standardPainlessConstructor) {
this.standardPainlessConstructor = Objects.requireNonNull(standardPainlessConstructor);
}
public record StandardConstant(Object standardConstant) implements Decoration {}
public PainlessConstructor getStandardPainlessConstructor() {
return standardPainlessConstructor;
}
}
public record StandardLocalFunction(LocalFunction localFunction) implements Decoration {}
public static class StandardPainlessMethod implements Decoration {
public record ThisPainlessMethod(PainlessMethod thisPainlessMethod) implements Decoration {}
private final PainlessMethod standardPainlessMethod;
public record StandardPainlessClassBinding(PainlessClassBinding painlessClassBinding) implements Decoration {}
public StandardPainlessMethod(PainlessMethod standardPainlessMethod) {
this.standardPainlessMethod = Objects.requireNonNull(standardPainlessMethod);
}
public PainlessMethod getStandardPainlessMethod() {
return standardPainlessMethod;
}
}
public interface DynamicInvocation extends Condition {
public record StandardPainlessInstanceBinding(PainlessInstanceBinding painlessInstanceBinding) implements Decoration {
}
public static class GetterPainlessMethod implements Decoration {
public record MethodNameDecoration(String methodName) implements Decoration {
private final PainlessMethod getterPainlessMethod;
public GetterPainlessMethod(PainlessMethod getterPainlessMethod) {
this.getterPainlessMethod = Objects.requireNonNull(getterPainlessMethod);
}
public PainlessMethod getGetterPainlessMethod() {
return getterPainlessMethod;
}
}
public static class SetterPainlessMethod implements Decoration {
private final PainlessMethod setterPainlessMethod;
public SetterPainlessMethod(PainlessMethod setterPainlessMethod) {
this.setterPainlessMethod = Objects.requireNonNull(setterPainlessMethod);
}
public PainlessMethod getSetterPainlessMethod() {
return setterPainlessMethod;
}
}
public static class StandardConstant implements Decoration {
private final Object standardConstant;
public StandardConstant(Object standardConstant) {
this.standardConstant = Objects.requireNonNull(standardConstant);
}
public Object getStandardConstant() {
return standardConstant;
}
}
public static class StandardLocalFunction implements Decoration {
private final LocalFunction localFunction;
public StandardLocalFunction(LocalFunction localFunction) {
this.localFunction = Objects.requireNonNull(localFunction);
}
public LocalFunction getLocalFunction() {
return localFunction;
}
}
public static class ThisPainlessMethod implements Decoration {
private final PainlessMethod thisPainlessMethod;
public ThisPainlessMethod(PainlessMethod thisPainlessMethod) {
this.thisPainlessMethod = Objects.requireNonNull(thisPainlessMethod);
}
public PainlessMethod getThisPainlessMethod() {
return thisPainlessMethod;
}
}
public static class StandardPainlessClassBinding implements Decoration {
private final PainlessClassBinding painlessClassBinding;
public StandardPainlessClassBinding(PainlessClassBinding painlessClassBinding) {
this.painlessClassBinding = Objects.requireNonNull(painlessClassBinding);
}
public PainlessClassBinding getPainlessClassBinding() {
return painlessClassBinding;
}
}
public static class StandardPainlessInstanceBinding implements Decoration {
private final PainlessInstanceBinding painlessInstanceBinding;
public StandardPainlessInstanceBinding(PainlessInstanceBinding painlessInstanceBinding) {
this.painlessInstanceBinding = Objects.requireNonNull(painlessInstanceBinding);
}
public PainlessInstanceBinding getPainlessInstanceBinding() {
return painlessInstanceBinding;
}
}
public static class MethodNameDecoration implements Decoration {
private final String methodName;
public MethodNameDecoration(String methodName) {
this.methodName = Objects.requireNonNull(methodName);
}
public String getMethodName() {
return methodName;
}
}
public static class ReturnType implements Decoration {
private final Class<?> returnType;
public ReturnType(Class<?> returnType) {
this.returnType = Objects.requireNonNull(returnType);
}
public Class<?> getReturnType() {
return returnType;
}
public record ReturnType(Class<?> returnType) implements Decoration {
public String getReturnCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(returnType);
}
}
public static class TypeParameters implements Decoration {
private final List<Class<?>> typeParameters;
public record TypeParameters(List<Class<?>> typeParameters) implements Decoration {
public TypeParameters(List<Class<?>> typeParameters) {
this.typeParameters = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(typeParameters)));
}
public List<Class<?>> getTypeParameters() {
return typeParameters;
}
}
public static class ParameterNames implements Decoration {
private final List<String> parameterNames;
public record ParameterNames(List<String> parameterNames) implements Decoration {
public ParameterNames(List<String> parameterNames) {
this.parameterNames = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(parameterNames)));
}
}
public List<String> getParameterNames() {
return parameterNames;
public record ReferenceDecoration(FunctionRef reference) implements Decoration {}
public record EncodingDecoration(Def.Encoding encoding) implements Decoration {
public static EncodingDecoration of(boolean isStatic, boolean needsInstance, String symbol, String methodName, int captures) {
return new EncodingDecoration(new Def.Encoding(isStatic, needsInstance, symbol, methodName, captures));
}
}
public static class ReferenceDecoration implements Decoration {
private final FunctionRef reference;
public ReferenceDecoration(FunctionRef reference) {
this.reference = Objects.requireNonNull(reference);
}
public FunctionRef getReference() {
return reference;
}
}
public static class EncodingDecoration implements Decoration {
private final Def.Encoding encoding;
public EncodingDecoration(boolean isStatic, boolean needsInstance, String symbol, String methodName, int captures) {
this.encoding = new Def.Encoding(isStatic, needsInstance, symbol, methodName, captures);
}
public Def.Encoding getEncoding() {
return encoding;
}
}
public static class CapturesDecoration implements Decoration {
private final List<Variable> captures;
public record CapturesDecoration(List<Variable> captures) implements Decoration {
public CapturesDecoration(List<Variable> captures) {
this.captures = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(captures)));
}
public List<Variable> getCaptures() {
public List<Variable> captures() {
return captures;
}
}
@ -559,17 +260,7 @@ public class Decorations {
}
public static class InstanceType implements Decoration {
private final Class<?> instanceType;
public InstanceType(Class<?> instanceType) {
this.instanceType = Objects.requireNonNull(instanceType);
}
public Class<?> getInstanceType() {
return instanceType;
}
public record InstanceType(Class<?> instanceType) implements Decoration {
public String getInstanceCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(instanceType);
@ -584,45 +275,13 @@ public class Decorations {
}
public static class AccessDepth implements Decoration {
private final int accessDepth;
public AccessDepth(int accessDepth) {
this.accessDepth = accessDepth;
}
public int getAccessDepth() {
return accessDepth;
}
}
public record AccessDepth(int accessDepth) implements Decoration {}
// standard output for user tree to ir tree phase
public static class IRNodeDecoration implements Decoration {
public record IRNodeDecoration(IRNode irNode) implements Decoration {}
private final IRNode irNode;
public IRNodeDecoration(IRNode irNode) {
this.irNode = Objects.requireNonNull(irNode);
}
public IRNode getIRNode() {
return irNode;
}
}
public static class Converter implements Decoration {
private final LocalFunction converter;
public Converter(LocalFunction converter) {
this.converter = converter;
}
public LocalFunction getConverter() {
return converter;
}
}
public record Converter(LocalFunction converter) implements Decoration {}
// collect additional information about where doc is used

View File

@ -286,7 +286,7 @@ public class IRDecorations {
@Override
public String toString() {
return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod.getName(), getValue().typeParameters.size());
return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod().getName(), getValue().typeParameters().size());
}
}
@ -379,7 +379,7 @@ public class IRDecorations {
@Override
public String toString() {
return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod.getName(), getValue().typeParameters.size());
return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod().getName(), getValue().typeParameters().size());
}
}

View File

@ -38,20 +38,11 @@ public abstract class SemanticScope {
* variables. Each {@link SemanticScope} tracks its own set of defined
* variables available for use.
*/
public static class Variable {
public record Variable(Class<?> type, String name, boolean isFinal) {
protected final Class<?> type;
protected final String name;
protected final boolean isFinal;
public Variable(Class<?> type, String name, boolean isFinal) {
this.type = Objects.requireNonNull(type);
this.name = Objects.requireNonNull(name);
this.isFinal = isFinal;
}
public Class<?> getType() {
return type;
public Variable {
Objects.requireNonNull(type);
Objects.requireNonNull(name);
}
/**
@ -61,14 +52,6 @@ public abstract class SemanticScope {
public String getCanonicalTypeName() {
return PainlessLookupUtility.typeToCanonicalTypeName(type);
}
public String getName() {
return name;
}
public boolean isFinal() {
return isFinal;
}
}
/**
@ -169,7 +152,7 @@ public abstract class SemanticScope {
if (variable == null) {
variable = parent.getVariable(location, name);
variable = new Variable(variable.getType(), variable.getName(), true);
variable = new Variable(variable.type(), variable.name(), true);
captures.add(variable);
} else {
usedVariables.add(name);

View File

@ -83,133 +83,133 @@ public class DecorationToXContent {
public static void ToXContent(TargetType targetType, XContentBuilderWrapper builder) {
start(targetType, builder);
builder.field(Fields.TYPE, targetType.getTargetType().getSimpleName());
builder.field(Fields.TYPE, targetType.targetType().getSimpleName());
builder.endObject();
}
public static void ToXContent(ValueType valueType, XContentBuilderWrapper builder) {
start(valueType, builder);
builder.field(Fields.TYPE, valueType.getValueType().getSimpleName());
builder.field(Fields.TYPE, valueType.valueType().getSimpleName());
builder.endObject();
}
public static void ToXContent(StaticType staticType, XContentBuilderWrapper builder) {
start(staticType, builder);
builder.field(Fields.TYPE, staticType.getStaticType().getSimpleName());
builder.field(Fields.TYPE, staticType.staticType().getSimpleName());
builder.endObject();
}
public static void ToXContent(PartialCanonicalTypeName partialCanonicalTypeName, XContentBuilderWrapper builder) {
start(partialCanonicalTypeName, builder);
builder.field(Fields.TYPE, partialCanonicalTypeName.getPartialCanonicalTypeName());
builder.field(Fields.TYPE, partialCanonicalTypeName.partialCanonicalTypeName());
builder.endObject();
}
public static void ToXContent(ExpressionPainlessCast expressionPainlessCast, XContentBuilderWrapper builder) {
start(expressionPainlessCast, builder);
builder.field(Fields.CAST);
ToXContent(expressionPainlessCast.getExpressionPainlessCast(), builder);
ToXContent(expressionPainlessCast.expressionPainlessCast(), builder);
builder.endObject();
}
public static void ToXContent(SemanticVariable semanticVariable, XContentBuilderWrapper builder) {
start(semanticVariable, builder);
builder.field("variable");
ToXContent(semanticVariable.getSemanticVariable(), builder);
ToXContent(semanticVariable.semanticVariable(), builder);
builder.endObject();
}
public static void ToXContent(IterablePainlessMethod iterablePainlessMethod, XContentBuilderWrapper builder) {
start(iterablePainlessMethod, builder);
builder.field(Fields.METHOD);
ToXContent(iterablePainlessMethod.getIterablePainlessMethod(), builder);
ToXContent(iterablePainlessMethod.iterablePainlessMethod(), builder);
builder.endObject();
}
public static void ToXContent(UnaryType unaryType, XContentBuilderWrapper builder) {
start(unaryType, builder);
builder.field(Fields.TYPE, unaryType.getUnaryType().getSimpleName());
builder.field(Fields.TYPE, unaryType.unaryType().getSimpleName());
builder.endObject();
}
public static void ToXContent(BinaryType binaryType, XContentBuilderWrapper builder) {
start(binaryType, builder);
builder.field(Fields.TYPE, binaryType.getBinaryType().getSimpleName());
builder.field(Fields.TYPE, binaryType.binaryType().getSimpleName());
builder.endObject();
}
public static void ToXContent(ShiftType shiftType, XContentBuilderWrapper builder) {
start(shiftType, builder);
builder.field(Fields.TYPE, shiftType.getShiftType().getSimpleName());
builder.field(Fields.TYPE, shiftType.shiftType().getSimpleName());
builder.endObject();
}
public static void ToXContent(ComparisonType comparisonType, XContentBuilderWrapper builder) {
start(comparisonType, builder);
builder.field(Fields.TYPE, comparisonType.getComparisonType().getSimpleName());
builder.field(Fields.TYPE, comparisonType.comparisonType().getSimpleName());
builder.endObject();
}
public static void ToXContent(CompoundType compoundType, XContentBuilderWrapper builder) {
start(compoundType, builder);
builder.field(Fields.TYPE, compoundType.getCompoundType().getSimpleName());
builder.field(Fields.TYPE, compoundType.compoundType().getSimpleName());
builder.endObject();
}
public static void ToXContent(UpcastPainlessCast upcastPainlessCast, XContentBuilderWrapper builder) {
start(upcastPainlessCast, builder);
builder.field(Fields.CAST);
ToXContent(upcastPainlessCast.getUpcastPainlessCast(), builder);
ToXContent(upcastPainlessCast.upcastPainlessCast(), builder);
builder.endObject();
}
public static void ToXContent(DowncastPainlessCast downcastPainlessCast, XContentBuilderWrapper builder) {
start(downcastPainlessCast, builder);
builder.field(Fields.CAST);
ToXContent(downcastPainlessCast.getDowncastPainlessCast(), builder);
ToXContent(downcastPainlessCast.downcastPainlessCast(), builder);
builder.endObject();
}
public static void ToXContent(StandardPainlessField standardPainlessField, XContentBuilderWrapper builder) {
start(standardPainlessField, builder);
builder.field("field");
ToXContent(standardPainlessField.getStandardPainlessField(), builder);
ToXContent(standardPainlessField.standardPainlessField(), builder);
builder.endObject();
}
public static void ToXContent(StandardPainlessConstructor standardPainlessConstructor, XContentBuilderWrapper builder) {
start(standardPainlessConstructor, builder);
builder.field("constructor");
ToXContent(standardPainlessConstructor.getStandardPainlessConstructor(), builder);
ToXContent(standardPainlessConstructor.standardPainlessConstructor(), builder);
builder.endObject();
}
public static void ToXContent(StandardPainlessMethod standardPainlessMethod, XContentBuilderWrapper builder) {
start(standardPainlessMethod, builder);
builder.field(Fields.METHOD);
ToXContent(standardPainlessMethod.getStandardPainlessMethod(), builder);
ToXContent(standardPainlessMethod.standardPainlessMethod(), builder);
builder.endObject();
}
public static void ToXContent(GetterPainlessMethod getterPainlessMethod, XContentBuilderWrapper builder) {
start(getterPainlessMethod, builder);
builder.field(Fields.METHOD);
ToXContent(getterPainlessMethod.getGetterPainlessMethod(), builder);
ToXContent(getterPainlessMethod.getterPainlessMethod(), builder);
builder.endObject();
}
public static void ToXContent(SetterPainlessMethod setterPainlessMethod, XContentBuilderWrapper builder) {
start(setterPainlessMethod, builder);
builder.field(Fields.METHOD);
ToXContent(setterPainlessMethod.getSetterPainlessMethod(), builder);
ToXContent(setterPainlessMethod.setterPainlessMethod(), builder);
builder.endObject();
}
public static void ToXContent(StandardConstant standardConstant, XContentBuilderWrapper builder) {
start(standardConstant, builder);
builder.startObject("constant");
builder.field(Fields.TYPE, standardConstant.getStandardConstant().getClass().getSimpleName());
builder.field("value", standardConstant.getStandardConstant());
builder.field(Fields.TYPE, standardConstant.standardConstant().getClass().getSimpleName());
builder.field("value", standardConstant.standardConstant());
builder.endObject();
builder.endObject();
}
@ -217,55 +217,55 @@ public class DecorationToXContent {
public static void ToXContent(StandardLocalFunction standardLocalFunction, XContentBuilderWrapper builder) {
start(standardLocalFunction, builder);
builder.field("function");
ToXContent(standardLocalFunction.getLocalFunction(), builder);
ToXContent(standardLocalFunction.localFunction(), builder);
builder.endObject();
}
public static void ToXContent(StandardPainlessClassBinding standardPainlessClassBinding, XContentBuilderWrapper builder) {
start(standardPainlessClassBinding, builder);
builder.field("PainlessClassBinding");
ToXContent(standardPainlessClassBinding.getPainlessClassBinding(), builder);
ToXContent(standardPainlessClassBinding.painlessClassBinding(), builder);
builder.endObject();
}
public static void ToXContent(StandardPainlessInstanceBinding standardPainlessInstanceBinding, XContentBuilderWrapper builder) {
start(standardPainlessInstanceBinding, builder);
builder.field("PainlessInstanceBinding");
ToXContent(standardPainlessInstanceBinding.getPainlessInstanceBinding(), builder);
ToXContent(standardPainlessInstanceBinding.painlessInstanceBinding(), builder);
builder.endObject();
}
public static void ToXContent(MethodNameDecoration methodNameDecoration, XContentBuilderWrapper builder) {
start(methodNameDecoration, builder);
builder.field("methodName", methodNameDecoration.getMethodName());
builder.field("methodName", methodNameDecoration.methodName());
builder.endObject();
}
public static void ToXContent(ReturnType returnType, XContentBuilderWrapper builder) {
start(returnType, builder);
builder.field("returnType", returnType.getReturnType().getSimpleName());
builder.field("returnType", returnType.returnType().getSimpleName());
builder.endObject();
}
public static void ToXContent(TypeParameters typeParameters, XContentBuilderWrapper builder) {
start(typeParameters, builder);
if (typeParameters.getTypeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(typeParameters.getTypeParameters()));
if (typeParameters.typeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(typeParameters.typeParameters()));
}
builder.endObject();
}
public static void ToXContent(ParameterNames parameterNames, XContentBuilderWrapper builder) {
start(parameterNames, builder);
if (parameterNames.getParameterNames().isEmpty() == false) {
builder.field("parameterNames", parameterNames.getParameterNames());
if (parameterNames.parameterNames().isEmpty() == false) {
builder.field("parameterNames", parameterNames.parameterNames());
}
builder.endObject();
}
public static void ToXContent(ReferenceDecoration referenceDecoration, XContentBuilderWrapper builder) {
start(referenceDecoration, builder);
FunctionRef ref = referenceDecoration.getReference();
FunctionRef ref = referenceDecoration.reference();
builder.field("interfaceMethodName", ref.interfaceMethodName);
builder.field("interfaceMethodType");
@ -298,15 +298,15 @@ public class DecorationToXContent {
public static void ToXContent(EncodingDecoration encodingDecoration, XContentBuilderWrapper builder) {
start(encodingDecoration, builder);
builder.field("encoding", encodingDecoration.getEncoding());
builder.field("encoding", encodingDecoration.encoding());
builder.endObject();
}
public static void ToXContent(CapturesDecoration capturesDecoration, XContentBuilderWrapper builder) {
start(capturesDecoration, builder);
if (capturesDecoration.getCaptures().isEmpty() == false) {
if (capturesDecoration.captures().isEmpty() == false) {
builder.startArray("captures");
for (SemanticScope.Variable capture : capturesDecoration.getCaptures()) {
for (SemanticScope.Variable capture : capturesDecoration.captures()) {
ToXContent(capture, builder);
}
builder.endArray();
@ -316,27 +316,27 @@ public class DecorationToXContent {
public static void ToXContent(InstanceType instanceType, XContentBuilderWrapper builder) {
start(instanceType, builder);
builder.field("instanceType", instanceType.getInstanceType().getSimpleName());
builder.field("instanceType", instanceType.instanceType().getSimpleName());
builder.endObject();
}
public static void ToXContent(AccessDepth accessDepth, XContentBuilderWrapper builder) {
start(accessDepth, builder);
builder.field("depth", accessDepth.getAccessDepth());
builder.field("depth", accessDepth.accessDepth());
builder.endObject();
}
public static void ToXContent(IRNodeDecoration irNodeDecoration, XContentBuilderWrapper builder) {
start(irNodeDecoration, builder);
// TODO(stu): expand this
builder.field("irNode", irNodeDecoration.getIRNode().toString());
builder.field("irNode", irNodeDecoration.irNode().toString());
builder.endObject();
}
public static void ToXContent(Converter converter, XContentBuilderWrapper builder) {
start(converter, builder);
builder.field("converter");
ToXContent(converter.getConverter(), builder);
ToXContent(converter.converter(), builder);
builder.endObject();
}
@ -442,25 +442,25 @@ public class DecorationToXContent {
public static void ToXContent(PainlessMethod method, XContentBuilderWrapper builder) {
builder.startObject();
if (method.javaMethod != null) {
if (method.javaMethod() != null) {
builder.field("javaMethod");
ToXContent(method.methodType, builder);
ToXContent(method.methodType(), builder);
}
if (method.targetClass != null) {
builder.field("targetClass", method.targetClass.getSimpleName());
if (method.targetClass() != null) {
builder.field("targetClass", method.targetClass().getSimpleName());
}
if (method.returnType != null) {
builder.field("returnType", method.returnType.getSimpleName());
if (method.returnType() != null) {
builder.field("returnType", method.returnType().getSimpleName());
}
if (method.typeParameters != null && method.typeParameters.isEmpty() == false) {
builder.field("typeParameters", classNames(method.typeParameters));
if (method.typeParameters() != null && method.typeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(method.typeParameters()));
}
if (method.methodHandle != null) {
if (method.methodHandle() != null) {
builder.field("methodHandle");
ToXContent(method.methodHandle.type(), builder);
ToXContent(method.methodHandle().type(), builder);
}
// ignoring methodType as that's handled under methodHandle
AnnotationsToXContent(method.annotations, builder);
AnnotationsToXContent(method.annotations(), builder);
builder.endObject();
}
@ -481,42 +481,42 @@ public class DecorationToXContent {
public static void ToXContent(PainlessClassBinding binding, XContentBuilderWrapper builder) {
builder.startObject();
builder.field("javaConstructor");
ToXContent(binding.javaConstructor, builder);
ToXContent(binding.javaConstructor(), builder);
builder.field("javaMethod");
ToXContent(binding.javaMethod, builder);
builder.field("returnType", binding.returnType.getSimpleName());
if (binding.typeParameters.isEmpty() == false) {
builder.field("typeParameters", classNames(binding.typeParameters));
ToXContent(binding.javaMethod(), builder);
builder.field("returnType", binding.returnType().getSimpleName());
if (binding.typeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(binding.typeParameters()));
}
AnnotationsToXContent(binding.annotations, builder);
AnnotationsToXContent(binding.annotations(), builder);
builder.endObject();
}
public static void ToXContent(PainlessInstanceBinding binding, XContentBuilderWrapper builder) {
builder.startObject();
builder.field("targetInstance", binding.targetInstance.getClass().getSimpleName());
builder.field("targetInstance", binding.targetInstance().getClass().getSimpleName());
builder.field("javaMethod");
ToXContent(binding.javaMethod, builder);
builder.field("returnType", binding.returnType.getSimpleName());
if (binding.typeParameters.isEmpty() == false) {
builder.field("typeParameters", classNames(binding.typeParameters));
ToXContent(binding.javaMethod(), builder);
builder.field("returnType", binding.returnType().getSimpleName());
if (binding.typeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(binding.typeParameters()));
}
AnnotationsToXContent(binding.annotations, builder);
AnnotationsToXContent(binding.annotations(), builder);
builder.endObject();
}
public static void ToXContent(PainlessField field, XContentBuilderWrapper builder) {
builder.startObject();
builder.field("javaField");
ToXContent(field.javaField, builder);
builder.field("typeParameter", field.typeParameter.getSimpleName());
ToXContent(field.javaField(), builder);
builder.field("typeParameter", field.typeParameter().getSimpleName());
builder.field("getterMethodHandle");
ToXContent(field.getterMethodHandle.type(), builder);
ToXContent(field.getterMethodHandle().type(), builder);
builder.field("setterMethodHandle");
if (field.setterMethodHandle != null) {
ToXContent(field.setterMethodHandle.type(), builder);
if (field.setterMethodHandle() != null) {
ToXContent(field.setterMethodHandle().type(), builder);
}
builder.endObject();
}
@ -524,20 +524,20 @@ public class DecorationToXContent {
public static void ToXContent(PainlessConstructor constructor, XContentBuilderWrapper builder) {
builder.startObject();
builder.field("javaConstructor");
ToXContent(constructor.javaConstructor, builder);
if (constructor.typeParameters.isEmpty() == false) {
builder.field("typeParameters", classNames(constructor.typeParameters));
ToXContent(constructor.javaConstructor(), builder);
if (constructor.typeParameters().isEmpty() == false) {
builder.field("typeParameters", classNames(constructor.typeParameters()));
}
builder.field("methodHandle");
ToXContent(constructor.methodHandle.type(), builder);
ToXContent(constructor.methodHandle().type(), builder);
builder.endObject();
}
// symbol
public static void ToXContent(SemanticScope.Variable variable, XContentBuilderWrapper builder) {
builder.startObject();
builder.field(Fields.TYPE, variable.getType());
builder.field("name", variable.getName());
builder.field(Fields.TYPE, variable.type());
builder.field("name", variable.name());
builder.field("isFinal", variable.isFinal());
builder.endObject();
}
@ -560,12 +560,12 @@ public class DecorationToXContent {
} else if (annotation instanceof DeprecatedAnnotation) {
builder.startObject();
builder.field("name", DeprecatedAnnotation.NAME);
builder.field("message", ((DeprecatedAnnotation) annotation).getMessage());
builder.field("message", ((DeprecatedAnnotation) annotation).message());
builder.endObject();
} else if (annotation instanceof InjectConstantAnnotation) {
builder.startObject();
builder.field("name", InjectConstantAnnotation.NAME);
builder.field("message", ((InjectConstantAnnotation) annotation).injects);
builder.field("message", ((InjectConstantAnnotation) annotation).injects());
builder.endObject();
} else if (annotation instanceof NoImportAnnotation) {
builder.value(NoImportAnnotation.NAME);

View File

@ -66,12 +66,12 @@ public final class Joiner {
Joiner(String joinField, List<Relations> relations) {
this.joinField = joinField;
for (Relations r : relations) {
for (String child : r.children) {
parentsToChildren.put(r.parent, r.children);
for (String child : r.children()) {
parentsToChildren.put(r.parent(), r.children());
if (childrenToParents.containsKey(child)) {
throw new IllegalArgumentException("[" + child + "] cannot have multiple parents");
}
childrenToParents.put(child, r.parent);
childrenToParents.put(child, r.parent());
}
}
}

View File

@ -125,7 +125,7 @@ public final class ParentJoinFieldMapper extends FieldMapper {
final Map<String, ParentIdFieldMapper> parentIdFields = new HashMap<>();
relations.get()
.stream()
.map(relation -> new ParentIdFieldMapper(name + "#" + relation.parent, eagerGlobalOrdinals.get()))
.map(relation -> new ParentIdFieldMapper(name + "#" + relation.parent(), eagerGlobalOrdinals.get()))
.forEach(mapper -> parentIdFields.put(mapper.name(), mapper));
Joiner joiner = new Joiner(name(), relations.get());
return new ParentJoinFieldMapper(
@ -306,10 +306,10 @@ public final class ParentJoinFieldMapper extends FieldMapper {
builder.field("eager_global_ordinals", eagerGlobalOrdinals);
builder.startObject("relations");
for (Relations relation : relations) {
if (relation.children.size() == 1) {
builder.field(relation.parent, relation.children.iterator().next());
if (relation.children().size() == 1) {
builder.field(relation.parent(), relation.children().iterator().next());
} else {
builder.field(relation.parent, relation.children);
builder.field(relation.parent(), relation.children());
}
}
builder.endObject();

View File

@ -16,39 +16,12 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Defines a relationship between a parent type and a set of child types
*/
class Relations {
final String parent;
final Set<String> children;
Relations(String parent, Set<String> children) {
this.parent = parent;
this.children = children;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Relations relation = (Relations) o;
return Objects.equals(parent, relation.parent) && Objects.equals(children, relation.children);
}
@Override
public int hashCode() {
return Objects.hash(parent, children);
}
@Override
public String toString() {
return parent + "->" + children;
}
record Relations(String parent, Set<String> children) {
static List<Relations> parse(Object fieldNode) {
List<Relations> parsed = new ArrayList<>();

View File

@ -94,8 +94,8 @@ public class EvalQueryQuality implements ToXContentFragment, Writeable {
builder.startArray(UNRATED_DOCS_FIELD.getPreferredName());
for (DocumentKey key : EvaluationMetric.filterUnratedDocuments(ratedHits)) {
builder.startObject();
builder.field(RatedDocument.INDEX_FIELD.getPreferredName(), key.getIndex());
builder.field(RatedDocument.DOC_ID_FIELD.getPreferredName(), key.getDocId());
builder.field(RatedDocument.INDEX_FIELD.getPreferredName(), key.index());
builder.field(RatedDocument.DOC_ID_FIELD.getPreferredName(), key.docId());
builder.endObject();
}
builder.endArray();

View File

@ -70,11 +70,11 @@ public class RatedDocument implements Writeable, ToXContentObject {
}
public String getIndex() {
return key.getIndex();
return key.index();
}
public String getDocID() {
return key.getDocId();
return key.docId();
}
public int getRating() {
@ -83,8 +83,8 @@ public class RatedDocument implements Writeable, ToXContentObject {
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(key.getIndex());
out.writeString(key.getDocId());
out.writeString(key.index());
out.writeString(key.docId());
out.writeVInt(rating);
}
@ -95,8 +95,8 @@ public class RatedDocument implements Writeable, ToXContentObject {
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(INDEX_FIELD.getPreferredName(), key.getIndex());
builder.field(DOC_ID_FIELD.getPreferredName(), key.getDocId());
builder.field(INDEX_FIELD.getPreferredName(), key.index());
builder.field(DOC_ID_FIELD.getPreferredName(), key.docId());
builder.field(RATING_FIELD.getPreferredName(), rating);
builder.endObject();
return builder;
@ -127,46 +127,15 @@ public class RatedDocument implements Writeable, ToXContentObject {
/**
* a joint document key consisting of the documents index and id
*/
static class DocumentKey {
record DocumentKey(String index, String docId) {
private final String docId;
private final String index;
DocumentKey(String index, String docId) {
DocumentKey {
if (Strings.isNullOrEmpty(index)) {
throw new IllegalArgumentException("Index must be set for each rated document");
}
if (Strings.isNullOrEmpty(docId)) {
throw new IllegalArgumentException("DocId must be set for each rated document");
}
this.index = index;
this.docId = docId;
}
String getIndex() {
return index;
}
String getDocId() {
return docId;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
DocumentKey other = (DocumentKey) obj;
return Objects.equals(index, other.index) && Objects.equals(docId, other.docId);
}
@Override
public final int hashCode() {
return Objects.hash(index, docId);
}
@Override

View File

@ -147,10 +147,10 @@ public class ReindexSslConfig {
* configurations if the underlying key/certificate files are modified.
*/
SSLIOSessionStrategy getStrategy() {
final HostnameVerifier hostnameVerifier = configuration.getVerificationMode().isHostnameVerificationEnabled()
final HostnameVerifier hostnameVerifier = configuration.verificationMode().isHostnameVerificationEnabled()
? new DefaultHostnameVerifier()
: new NoopHostnameVerifier();
final String[] protocols = configuration.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY);
final String[] protocols = configuration.supportedProtocols().toArray(Strings.EMPTY_ARRAY);
final String[] cipherSuites = configuration.getCipherSuites().toArray(Strings.EMPTY_ARRAY);
return new SSLIOSessionStrategy(context, protocols, cipherSuites, hostnameVerifier);
}

View File

@ -137,10 +137,10 @@ public class AnnotatedPassageFormatter extends PassageFormatter {
// Now add original text's annotations - ignoring any that might conflict with the search hits markup.
for (AnnotationToken token : annotations) {
int start = token.offset;
int end = token.endOffset;
int start = token.offset();
int end = token.endOffset();
if (start >= passage.getStartOffset() && end <= passage.getEndOffset()) {
String escapedValue = URLEncoder.encode(token.value, StandardCharsets.UTF_8.name());
String escapedValue = URLEncoder.encode(token.value(), StandardCharsets.UTF_8.name());
Markup markup = new Markup(start, end, escapedValue);
markupPassage.addUnlessOverlapping(markup);
}
@ -207,12 +207,12 @@ public class AnnotatedPassageFormatter extends PassageFormatter {
AnnotationToken token = fieldValueAnnotations.getAnnotation(i);
if (token.intersects(start - fieldValueOffset, end - fieldValueOffset)) {
intersectingAnnotations.add(
new AnnotationToken(token.offset + fieldValueOffset, token.endOffset + fieldValueOffset, token.value)
new AnnotationToken(token.offset() + fieldValueOffset, token.endOffset() + fieldValueOffset, token.value())
);
}
}
// add 1 for the fieldvalue separator character
fieldValueOffset += fieldValueAnnotations.textMinusMarkup.length() + 1;
fieldValueOffset += fieldValueAnnotations.textMinusMarkup().length() + 1;
}
return intersectingAnnotations.toArray(new AnnotationToken[intersectingAnnotations.size()]);
}

View File

@ -42,7 +42,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -152,10 +151,7 @@ public class AnnotatedTextFieldMapper extends FieldMapper {
* Parses markdown-like syntax into plain text and AnnotationTokens with offsets for
* annotations found in texts
*/
public static final class AnnotatedText {
public final String textPlusMarkup;
public final String textMinusMarkup;
List<AnnotationToken> annotations;
public record AnnotatedText(String textMinusMarkup, String textPlusMarkup, List<AnnotationToken> annotations) {
// Format is markdown-like syntax for URLs eg:
// "New mayor is [John Smith](type=person&value=John%20Smith) "
@ -201,23 +197,7 @@ public class AnnotatedTextFieldMapper extends FieldMapper {
return new AnnotatedText(sb.toString(), textPlusMarkup, annotations);
}
protected AnnotatedText(String textMinusMarkup, String textPlusMarkup, List<AnnotationToken> annotations) {
this.textMinusMarkup = textMinusMarkup;
this.textPlusMarkup = textPlusMarkup;
this.annotations = annotations;
}
public static final class AnnotationToken {
public final int offset;
public final int endOffset;
public final String value;
public AnnotationToken(int offset, int endOffset, String value) {
this.offset = offset;
this.endOffset = endOffset;
this.value = value;
}
public record AnnotationToken(int offset, int endOffset, String value) {
@Override
public String toString() {
@ -229,28 +209,6 @@ public class AnnotatedTextFieldMapper extends FieldMapper {
|| (start <= endOffset && end >= endOffset)
|| (start >= offset && end <= endOffset);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + endOffset;
result = prime * result + offset;
result = prime * result + Objects.hashCode(value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
AnnotationToken other = (AnnotationToken) obj;
return Objects.equals(endOffset, other.endOffset)
&& Objects.equals(offset, other.offset)
&& Objects.equals(value, other.value);
}
}
@Override

View File

@ -43,7 +43,7 @@ public class AnnotatedTextHighlighter extends UnifiedHighlighter {
AnnotatedText[] annotations = new AnnotatedText[fieldValues.size()];
for (int i = 0; i < fieldValues.size(); i++) {
annotations[i] = AnnotatedText.parse(fieldValues.get(i).toString());
strings.add(annotations[i].textMinusMarkup);
strings.add(annotations[i].textMinusMarkup());
}
// Store the annotations in the formatter and analyzer
((AnnotatedPassageFormatter) highlighter.getFormatter()).setAnnotations(annotations);

View File

@ -123,7 +123,7 @@ public class AnnotatedTextHighlighterTests extends ESTestCase {
ArrayList<Object> plainTextForHighlighter = new ArrayList<>(annotations.length);
for (int i = 0; i < annotations.length; i++) {
plainTextForHighlighter.add(annotations[i].textMinusMarkup);
plainTextForHighlighter.add(annotations[i].textMinusMarkup());
}
TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), 1, Sort.INDEXORDER);

View File

@ -21,8 +21,8 @@ public class AnnotatedTextParsingTests extends ESTestCase {
private void checkParsing(String markup, String expectedPlainText, AnnotationToken... expectedTokens) {
AnnotatedText at = AnnotatedText.parse(markup);
assertEquals(expectedPlainText, at.textMinusMarkup);
List<AnnotationToken> actualAnnotations = at.annotations;
assertEquals(expectedPlainText, at.textMinusMarkup());
List<AnnotationToken> actualAnnotations = at.annotations();
assertEquals(expectedTokens.length, actualAnnotations.size());
for (int i = 0; i < expectedTokens.length; i++) {
assertEquals(expectedTokens[i], actualAnnotations.get(i));

View File

@ -75,45 +75,7 @@ public class SearchStatesIT extends ESRestTestCase {
private static final Version UPGRADE_FROM_VERSION = Version.fromString(System.getProperty("tests.upgrade_from_version"));
private static final String CLUSTER_ALIAS = "remote_cluster";
static class Node {
final String id;
final String name;
final Version version;
final String transportAddress;
final String httpAddress;
final Map<String, Object> attributes;
Node(String id, String name, Version version, String transportAddress, String httpAddress, Map<String, Object> attributes) {
this.id = id;
this.name = name;
this.version = version;
this.transportAddress = transportAddress;
this.httpAddress = httpAddress;
this.attributes = attributes;
}
@Override
public String toString() {
return "Node{"
+ "id='"
+ id
+ '\''
+ ", name='"
+ name
+ '\''
+ ", version="
+ version
+ ", transportAddress='"
+ transportAddress
+ '\''
+ ", httpAddress='"
+ httpAddress
+ '\''
+ ", attributes="
+ attributes
+ '}';
}
}
record Node(String id, String name, Version version, String transportAddress, String httpAddress, Map<String, Object> attributes) {}
static List<Node> getNodes(RestClient restClient) throws IOException {
Response response = restClient.performRequest(new Request("GET", "_nodes"));

View File

@ -23,7 +23,7 @@ public class HotThreadsIT extends ESRestTestCase {
assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty());
assumeTrue(
"new nodes are higher version than BWC nodes",
nodes.getNewNodes().get(0).getVersion().compareTo(nodes.getBWCNodes().get(0).getVersion()) > 0
nodes.getNewNodes().get(0).version().compareTo(nodes.getBWCNodes().get(0).version()) > 0
);
final Request request = new Request("GET", "/_nodes/hot_threads");
final Response response = client().performRequest(request);

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