Skip to content

Commit

Permalink
Minor cleanups and refactorings.
Browse files Browse the repository at this point in the history
  • Loading branch information
fniephaus committed Nov 6, 2023
1 parent f0dac09 commit 4d70a33
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,6 @@ public static RuntimeException unsupportedFeature(String msg) {
throw new HostedError("UNSUPPORTED FEATURE: " + msg);
}

public static boolean hostedError(Throwable t) {
return t instanceof HostedError;
}

/**
* Processes {@code args} to convert selected values to strings.
* <ul>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,6 @@ protected BuildConfiguration(List<String> args) {
this(null, null, args);
}

@SuppressWarnings("deprecation")
BuildConfiguration(Path rootDir, Path workDir, List<String> args) {
try {
modulePathBuild = (boolean) isModulePathBuild.invoke(null);
Expand Down Expand Up @@ -635,16 +634,6 @@ public List<String> getBuildArgs() {
public boolean buildFallbackImage() {
return false;
}

/**
* ResourcesJar packs resources files needed for some jdk services such as xml
* serialization.
*
* @return the path to the resources.jar file
*/
public Optional<Path> getResourcesJar() {
return Optional.of(rootDir.resolve(Paths.get("lib", "resources.jar")));
}
}

class DriverMetaInfProcessor implements NativeImageMetaInfResourceProcessor {
Expand All @@ -669,7 +658,6 @@ public boolean processMetaInfResource(Path classpathEntry, Path resourceRoot, Pa
throw showError("Failed to process ForceOnModulePath attribute: Module descriptor for the module " + forceOnModulePath +
" could not be resolved with class-path entry: " + classpathEntry + ".", e);
}
ignoreClasspathEntry = true;
addImageModulePath(classpathEntry, true, false);
addAddedModules(forceOnModulePath);
ignoreClasspathEntry = true;
Expand All @@ -683,7 +671,7 @@ public boolean processMetaInfResource(Path classpathEntry, Path resourceRoot, Pa
*/
String originSuffix = isNativeImagePropertiesFile ? "" : OptionOrigin.isAPISuffix;

NativeImageArgsProcessor args = NativeImage.this.new NativeImageArgsProcessor(resourcePath.toUri().toString() + originSuffix);
NativeImageArgsProcessor args = NativeImage.this.new NativeImageArgsProcessor(resourcePath.toUri() + originSuffix);
Path componentDirectory = resourceRoot.relativize(resourcePath).getParent();
Function<String, String> resolver = str -> {
int nameCount = componentDirectory.getNameCount();
Expand Down Expand Up @@ -743,17 +731,13 @@ private ArrayList<String> createFallbackBuildArgs() {

List<String> runtimeJavaArgs = imageBuilderArgs.stream()
.filter(s -> s.startsWith(oRRuntimeJavaArg))
.collect(Collectors.toList());
for (String runtimeJavaArg : runtimeJavaArgs) {
buildArgs.add(runtimeJavaArg);
}
.toList();
buildArgs.addAll(runtimeJavaArgs);

List<String> fallbackExecutorJavaArgs = imageBuilderArgs.stream()
.filter(s -> s.startsWith(oHFallbackExecutorJavaArg))
.collect(Collectors.toList());
for (String fallbackExecutorJavaArg : fallbackExecutorJavaArgs) {
buildArgs.add(fallbackExecutorJavaArg);
}
.toList();
buildArgs.addAll(fallbackExecutorJavaArgs);

buildArgs.add(oHEnabled(SubstrateOptions.UnlockExperimentalVMOptions));
buildArgs.add(oHEnabled(SubstrateOptions.BuildOutputSilent));
Expand Down Expand Up @@ -810,11 +794,6 @@ private FallbackBuildConfiguration(NativeImage original) {
fallbackBuildArgs = original.createFallbackBuildArgs();
}

@Override
public List<Path> getImageClasspath() {
return Collections.emptyList();
}

@Override
public List<String> getBuildArgs() {
return fallbackBuildArgs;
Expand Down Expand Up @@ -932,10 +911,9 @@ private void completeOptionArgs() {
consolidateListArgs(imageBuilderJavaArgs, "-Dpolyglot.image-build-time.PreinitializeContexts=", ",", Function.identity());
}

protected static boolean replaceArg(Collection<String> args, String argPrefix, String argSuffix) {
boolean elementsRemoved = args.removeIf(arg -> arg.startsWith(argPrefix));
protected static void replaceArg(Collection<String> args, String argPrefix, String argSuffix) {
args.removeIf(arg -> arg.startsWith(argPrefix));
args.add(argPrefix + argSuffix);
return elementsRemoved;
}

private static LinkedHashSet<String> collectListArgs(Collection<String> args, String argPrefix, String delimiter) {
Expand Down Expand Up @@ -1340,14 +1318,7 @@ private static List<ArgumentEntry> getHostedOptionArgumentValues(List<String> ar
return values;
}

private static final class ArgumentEntry {
private final int index;
private final String value;

private ArgumentEntry(int index, String value) {
this.index = index;
this.value = value;
}
private record ArgumentEntry(int index, String value) {
}

private static Boolean getHostedOptionFinalBooleanArgumentValue(List<String> args, OptionKey<Boolean> option) {
Expand Down Expand Up @@ -1414,8 +1385,6 @@ private static String getAgentOptions(List<ArgumentEntry> options, String option
}

private String targetPlatform = null;
private String targetOS = null;
private String targetArch = null;

private void addTargetArguments() {
/*
Expand All @@ -1434,8 +1403,8 @@ private void addTargetArguments() {
throw NativeImage.showError("--target argument must be in format <OS>-<architecture>");
}

targetOS = parts[0];
targetArch = parts[1];
String targetOS = parts[0];
String targetArch = parts[1];

if (customJavaArgs.stream().anyMatch(arg -> arg.startsWith("-D" + Platform.PLATFORM_PROPERTY_NAME + "="))) {
LogUtils.warning("Usage of -D" + Platform.PLATFORM_PROPERTY_NAME + " might conflict with --target parameter.");
Expand Down Expand Up @@ -1512,8 +1481,7 @@ protected Path createImageBuilderArgumentFile(List<String> imageBuilderArguments

protected int buildImage(List<String> javaArgs, LinkedHashSet<Path> cp, LinkedHashSet<Path> mp, ArrayList<String> imageArgs, LinkedHashSet<Path> imagecp,
LinkedHashSet<Path> imagemp) {
List<String> arguments = new ArrayList<>();
arguments.addAll(javaArgs);
List<String> arguments = new ArrayList<>(javaArgs);

if (!cp.isEmpty()) {
arguments.addAll(Arrays.asList("-cp", cp.stream().map(Path::toString).collect(Collectors.joining(File.pathSeparator))));
Expand Down Expand Up @@ -2028,8 +1996,6 @@ void addImageClasspath(Path classpath) {
addImageClasspathEntry(imageClasspath, classpath, true);
}

LinkedHashSet<String> builderModuleNames = null;

void addImageModulePath(Path modulePathEntry) {
addImageModulePath(modulePathEntry, true, true);
}
Expand Down Expand Up @@ -2246,7 +2212,6 @@ void performANSIReset() {

@SuppressWarnings("serial")
public static final class NativeImageError extends Error {

final int exitCode;

private NativeImageError(String message) {
Expand Down Expand Up @@ -2472,13 +2437,6 @@ protected void deleteAllFiles(Path toDelete) {
}
}

private static final class ExcludeConfig {
final Pattern jarPattern;
final Pattern resourcePattern;

private ExcludeConfig(Pattern jarPattern, Pattern resourcePattern) {
this.jarPattern = jarPattern;
this.resourcePattern = resourcePattern;
}
private record ExcludeConfig(Pattern jarPattern, Pattern resourcePattern) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,13 @@ static void propagateEnv(Map<String, String> environment) {
OUTPUT_SEPARATOR, vcVarsAllLocation, OUTPUT_SEPARATOR);
Process p = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", commandSequence});
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line = null;
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(OUTPUT_SEPARATOR)) {
numSeenOutputSeparators++;
} else if (numSeenOutputSeparators == 0) {
// collect environment variables from 1st `set` invocation
processLineWithKeyValue(line, (key, value) -> originalEnv.put(key, value));
processLineWithKeyValue(line, originalEnv::put);
} else if (numSeenOutputSeparators == 2) {
// iterate through updated environment variables from 2nd `set` invocation
processLineWithKeyValue(line, (key, value) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.oracle.graal.pointsto.meta.AnalysisType;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.impl.ImageSingletonsSupport;
Expand Down Expand Up @@ -260,7 +261,7 @@ private void printFeatures(List<Feature> features) {
int numFeatures = features.size();
if (numFeatures > 0) {
l().a(" ").a(numFeatures).a(" ").doclink("user-specific feature(s)", "#glossary-user-specific-features").a(":").println();
features.sort((a, b) -> a.getClass().getName().compareTo(b.getClass().getName()));
features.sort(Comparator.comparing(a -> a.getClass().getName()));
for (Feature feature : features) {
printFeature(l(), feature);
}
Expand Down Expand Up @@ -343,7 +344,7 @@ private void printExperimentalOptions(ImageClassLoader classLoader) {
origins = origin.toString();
String valueString;
if (hok.getDescriptor().getOptionValueType() == Boolean.class) {
valueString = Boolean.valueOf(value.toString()) ? "+" : "-";
valueString = Boolean.parseBoolean(value.toString()) ? "+" : "-";
optionPrefix += valueString;
} else {
valueString = value.toString();
Expand Down Expand Up @@ -436,7 +437,7 @@ public void closeAction() {
private void printAnalysisStatistics(AnalysisUniverse universe, Collection<String> libraries) {
String actualFormat = "%,9d ";
String totalFormat = " (%4.1f%% of %,8d total)";
long reachableTypes = universe.getTypes().stream().filter(t -> t.isReachable()).count();
long reachableTypes = universe.getTypes().stream().filter(AnalysisType::isReachable).count();
long totalTypes = universe.getTypes().size();
recordJsonMetric(AnalysisResults.TYPES_TOTAL, totalTypes);
recordJsonMetric(AnalysisResults.DEPRECATED_CLASS_TOTAL, totalTypes);
Expand All @@ -445,14 +446,14 @@ private void printAnalysisStatistics(AnalysisUniverse universe, Collection<Strin
l().a(actualFormat, reachableTypes).doclink("reachable types", "#glossary-reachability").a(" ")
.a(totalFormat, Utils.toPercentage(reachableTypes, totalTypes), totalTypes).println();
Collection<AnalysisField> fields = universe.getFields();
long reachableFields = fields.stream().filter(f -> f.isAccessed()).count();
long reachableFields = fields.stream().filter(AnalysisField::isAccessed).count();
int totalFields = fields.size();
recordJsonMetric(AnalysisResults.FIELD_TOTAL, totalFields);
recordJsonMetric(AnalysisResults.FIELD_REACHABLE, reachableFields);
l().a(actualFormat, reachableFields).doclink("reachable fields", "#glossary-reachability").a(" ")
.a(totalFormat, Utils.toPercentage(reachableFields, totalFields), totalFields).println();
Collection<AnalysisMethod> methods = universe.getMethods();
long reachableMethods = methods.stream().filter(m -> m.isReachable()).count();
long reachableMethods = methods.stream().filter(AnalysisMethod::isReachable).count();
int totalMethods = methods.size();
recordJsonMetric(AnalysisResults.METHOD_TOTAL, totalMethods);
recordJsonMetric(AnalysisResults.METHOD_REACHABLE, reachableMethods);
Expand Down Expand Up @@ -617,7 +618,7 @@ private void printBreakdowns() {

int numCodeItems = codeBreakdown.size();
int numHeapItems = heapBreakdown.getSortedBreakdownEntries().size();
long totalCodeBytes = codeBreakdown.values().stream().collect(Collectors.summingLong(Long::longValue));
long totalCodeBytes = codeBreakdown.values().stream().mapToLong(Long::longValue).sum();

p.l().a(String.format("%9s for %s more packages", ByteFormattingUtil.bytesToHuman(totalCodeBytes - printedCodeBytes), numCodeItems - printedCodeItems))
.jumpToMiddle()
Expand Down Expand Up @@ -648,7 +649,7 @@ public void printEpilog(Optional<String> optionalImageName, Optional<NativeImage

if (optionalError.isPresent()) {
Path errorReportPath = NativeImageOptions.getErrorFilePath(parsedHostedOptions);
Optional<FeatureHandler> featureHandler = optionalGenerator.isEmpty() ? Optional.empty() : Optional.ofNullable(optionalGenerator.get().featureHandler);
Optional<FeatureHandler> featureHandler = optionalGenerator.map(nativeImageGenerator -> nativeImageGenerator.featureHandler);
ReportUtils.report("GraalVM Native Image Error Report", errorReportPath, p -> VMErrorReporter.generateErrorReport(p, buildOutputLog, classLoader, featureHandler, optionalError.get()),
false);
if (ImageSingletonsSupport.isInstalled()) {
Expand Down Expand Up @@ -738,9 +739,7 @@ private void printArtifacts(Map<ArtifactType, List<Path>> artifacts) {
pathToTypes.computeIfAbsent(path, p -> new ArrayList<>()).add(artifactType.name().toLowerCase());
}
});
pathToTypes.forEach((path, typeNames) -> {
l().a(" ").link(path).dim().a(" (").a(String.join(", ", typeNames)).a(")").reset().println();
});
pathToTypes.forEach((path, typeNames) -> l().a(" ").link(path).dim().a(" (").a(String.join(", ", typeNames)).a(")").reset().println());
}

private Path reportBuildOutput(Path jsonOutputFile) {
Expand Down Expand Up @@ -862,7 +861,7 @@ private static String truncateClassOrPackageName(String classOrPackageName) {
sb.append(rest);
} else {
int remainingSpaceDivBy2 = (maxLength - sbLength) / 2;
sb.append(rest.substring(0, remainingSpaceDivBy2 - 1) + "~" + rest.substring(restLength - remainingSpaceDivBy2, restLength));
sb.append(rest, 0, remainingSpaceDivBy2 - 1).append("~").append(rest, restLength - remainingSpaceDivBy2, restLength);
}
break;
}
Expand Down Expand Up @@ -968,11 +967,6 @@ public final T blueBold() {
return getThis();
}

public final T magentaBold() {
colorStrategy.magentaBold(this);
return getThis();
}

public final T red() {
colorStrategy.red(this);
return getThis();
Expand Down Expand Up @@ -1110,7 +1104,7 @@ abstract class StagePrinter<T extends StagePrinter<T>> extends LinePrinter<T> {
private ScheduledFuture<?> periodicPrintingTask;
private boolean isCancelled;

T start(BuildStage stage) {
void start(BuildStage stage) {
assert activeBuildStage == null;
activeBuildStage = stage;
appendStageStart();
Expand All @@ -1120,7 +1114,6 @@ T start(BuildStage stage) {
if (activeBuildStage.hasPeriodicProgress) {
startPeriodicProgress();
}
return getThis();
}

private void startPeriodicProgress() {
Expand Down Expand Up @@ -1225,10 +1218,9 @@ public CharacterwiseStagePrinter a(String value) {
}

@Override
CharacterwiseStagePrinter start(BuildStage stage) {
void start(BuildStage stage) {
super.start(stage);
builderIO.progressReporter = ProgressReporter.this;
return getThis();
}

@Override
Expand Down Expand Up @@ -1352,7 +1344,7 @@ default void reset() {
}
}

final class ColorlessStrategy implements ColorStrategy {
static final class ColorlessStrategy implements ColorStrategy {
}

final class ColorfulStrategy implements ColorStrategy {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,10 @@ private static boolean recommendTraceAgentForAWT() {
}

public record UserRecommendation(String id, String description, Supplier<Boolean> isApplicable) {
public UserRecommendation(String id, String description, Supplier<Boolean> isApplicable) {
public UserRecommendation {
assert id.toUpperCase().equals(id) && id.length() < 5 : "id must be uppercase and have fewer than 5 chars";
int maxLength = 74;
assert description.length() < maxLength : "description must have fewer than " + maxLength + " chars to fit in terminal. Length: " + description.length();
this.id = id;
this.description = description;
this.isApplicable = isApplicable;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ enum ImageDetailKey implements JsonMetric {
RUNTIME_COMPILED_METHODS_COUNT("runtime_compiled_methods", null, "count"),
GRAPH_ENCODING_SIZE("runtime_compiled_methods", null, "graph_encoding_bytes");

private String bucket;
private String jsonKey;
private String subBucket;
private final String bucket;
private final String jsonKey;
private final String subBucket;

ImageDetailKey(String bucket, String subBucket, String key) {
this.bucket = bucket;
Expand All @@ -135,8 +135,8 @@ enum ResourceUsageKey implements JsonMetric {
MEMORY_TOTAL("memory", "system_total"),
TOTAL_SECS(null, "total_secs");

private String bucket;
private String jsonKey;
private final String bucket;
private final String jsonKey;

ResourceUsageKey(String bucket, String key) {
this.bucket = bucket;
Expand Down Expand Up @@ -170,8 +170,8 @@ public enum AnalysisResults implements JsonMetric {
DEPRECATED_CLASS_JNI("classes", "jni"),
DEPRECATED_CLASS_REFLECT("classes", "reflection");

private String key;
private String bucket;
private final String key;
private final String bucket;

AnalysisResults(String bucket, String key) {
this.key = key;
Expand Down Expand Up @@ -209,8 +209,8 @@ public enum GeneralInfo implements JsonMetric {
GC("garbage_collector", null),
CC("c_compiler", null);

private String key;
private String bucket;
private final String key;
private final String bucket;

GeneralInfo(String key, String bucket) {
this.key = key;
Expand Down
Loading

0 comments on commit 4d70a33

Please sign in to comment.