@@ -819,8 +819,8 @@ ls build/linux-aarch64-server-release/
Icecc / icecream
icecc/icecream is a simple way to setup a distributed compiler network. If you have multiple machines available for building the JDK, you can drastically cut individual build times by utilizing it.
To use, setup an icecc network, and install icecc on the build machine. Then run configure using --enable-icecc.
-
Using sjavac
-
To speed up compilation of Java code, especially during incremental compilations, the sjavac server is automatically enabled in the configuration step by default. To explicitly enable or disable sjavac, use either --enable-javac-server or --disable-javac-server.
+
Using the javac server
+
To speed up compilation of Java code, especially during incremental compilations, the javac server is automatically enabled in the configuration step by default. To explicitly enable or disable the javac server, use either --enable-javac-server or --disable-javac-server.
Building the Right Target
Selecting the proper target to build can have dramatic impact on build time. For normal usage, jdk or the default target is just fine. You only need to build images for shipping, or if your tests require it.
diff --git a/doc/building.md b/doc/building.md
index 6268f4c5640..9678fc91880 100644
--- a/doc/building.md
+++ b/doc/building.md
@@ -1333,12 +1333,12 @@ it.
To use, setup an icecc network, and install icecc on the build machine. Then
run `configure` using `--enable-icecc`.
-### Using sjavac
+### Using the javac server
-To speed up compilation of Java code, especially during incremental compilations,
-the sjavac server is automatically enabled in the configuration step by default.
-To explicitly enable or disable sjavac, use either `--enable-javac-server`
-or `--disable-javac-server`.
+To speed up compilation of Java code, especially during incremental
+compilations, the javac server is automatically enabled in the configuration
+step by default. To explicitly enable or disable the javac server, use either
+`--enable-javac-server` or `--disable-javac-server`.
### Building the Right Target
diff --git a/make/CompileInterimLangtools.gmk b/make/CompileInterimLangtools.gmk
index 223e67d8c7b..0be8aa46ded 100644
--- a/make/CompileInterimLangtools.gmk
+++ b/make/CompileInterimLangtools.gmk
@@ -125,5 +125,20 @@ $(foreach m, $(INTERIM_LANGTOOLS_BASE_MODULES), \
)
################################################################################
+# Setup the compilation of the javac server build tool. Technically, this is not
+# really "interim" langtools, but just like it, it is needed henceforth for all
+# java compilation using the interim compiler.
+$(eval $(call SetupJavaCompilation, BUILD_JAVAC_SERVER, \
+ COMPILER := bootjdk, \
+ TARGET_RELEASE := $(TARGET_RELEASE_BOOTJDK), \
+ SRC := $(TOPDIR)/make/langtools/tools, \
+ INCLUDES := javacserver, \
+ BIN := $(BUILDTOOLS_OUTPUTDIR)/langtools_javacserver_classes, \
+))
+
+TARGETS += $(BUILD_JAVAC_SERVER)
+
+################################################################################
+
all: $(TARGETS)
diff --git a/make/Init.gmk b/make/Init.gmk
index 53652e64b3f..151127d5788 100644
--- a/make/Init.gmk
+++ b/make/Init.gmk
@@ -324,7 +324,7 @@ else # HAS_SPEC=true
ifneq ($(PARALLEL_TARGETS), )
$(call PrepareFailureLogs)
$(call StartGlobalTimer)
- $(call PrepareSmartJavac)
+ $(call PrepareJavacServer)
# JOBS will only be empty for a bootcycle-images recursive call
# or if specified via a make argument directly. In those cases
# treat it as NOT using jobs at all.
@@ -339,7 +339,7 @@ else # HAS_SPEC=true
cd $(TOPDIR) && $(MAKE) $(MAKE_ARGS) -j 1 -f make/Init.gmk \
HAS_SPEC=true on-failure ; \
exit $$exitcode ) )
- $(call CleanupSmartJavac)
+ $(call CleanupJavacServer)
$(call StopGlobalTimer)
$(call ReportBuildTimes)
endif
@@ -351,7 +351,7 @@ else # HAS_SPEC=true
endif
on-failure:
- $(call CleanupSmartJavac)
+ $(call CleanupJavacServer)
$(call StopGlobalTimer)
$(call ReportBuildTimes)
$(call PrintFailureReports)
@@ -364,11 +364,11 @@ else # HAS_SPEC=true
# Support targets for COMPARE_BUILD, used for makefile development
pre-compare-build:
- $(call WaitForSmartJavacFinish)
+ $(call WaitForJavacServerFinish)
$(call PrepareCompareBuild)
post-compare-build:
- $(call WaitForSmartJavacFinish)
+ $(call WaitForJavacServerFinish)
$(call CleanupCompareBuild)
$(call CompareBuildDoComparison)
diff --git a/make/InitSupport.gmk b/make/InitSupport.gmk
index a75d8a93c41..06a20e3abf2 100644
--- a/make/InitSupport.gmk
+++ b/make/InitSupport.gmk
@@ -493,15 +493,15 @@ else # $(HAS_SPEC)=true
# Remove any javac server logs and port files. This
# prevents a new make run to reuse the previous servers.
- define PrepareSmartJavac
+ define PrepareJavacServer
$(if $(JAVAC_SERVER_DIR), \
$(RM) -r $(JAVAC_SERVER_DIR) 2> /dev/null && \
$(MKDIR) -p $(JAVAC_SERVER_DIR) \
)
endef
- define CleanupSmartJavac
- [ -f $(JAVAC_SERVER_DIR)/server.port ] && $(ECHO) Stopping sjavac server && \
+ define CleanupJavacServer
+ [ -f $(JAVAC_SERVER_DIR)/server.port ] && $(ECHO) Stopping javac server && \
$(TOUCH) $(JAVAC_SERVER_DIR)/server.port.stop; true
endef
@@ -510,13 +510,13 @@ else # $(HAS_SPEC)=true
# move or remove the build output directory. Since we have no proper
# synchronization process, wait for a while and hope it helps. This is only
# used by build comparisons.
- define WaitForSmartJavacFinish
+ define WaitForJavacServerFinish
$(if $(JAVAC_SERVER_DIR), \
sleep 5\
)
endef
else
- define WaitForSmartJavacFinish
+ define WaitForJavacServerFinish
endef
endif
diff --git a/make/common/JavaCompilation.gmk b/make/common/JavaCompilation.gmk
index 9c0ee467275..802b0f130f9 100644
--- a/make/common/JavaCompilation.gmk
+++ b/make/common/JavaCompilation.gmk
@@ -219,7 +219,7 @@ define SetupJavaCompilationBody
# Use java server if it is enabled, and the user does not want a specialized
# class path.
ifeq ($$(ENABLE_JAVAC_SERVER)+$$($1_CLASSPATH), true+)
- $1_JAVAC := $$(INTERIM_LANGTOOLS_ARGS) -m jdk.compiler.interim/com.sun.tools.sjavac.Main
+ $1_JAVAC := $$(INTERIM_LANGTOOLS_ARGS) -cp $(BUILDTOOLS_OUTPUTDIR)/langtools_javacserver_classes javacserver.Main
# Create a configuration file with the needed information for the javac
# server to function properly.
diff --git a/make/ide/idea/langtools/template/runConfigurations/sjavac.xml b/make/ide/idea/langtools/template/runConfigurations/sjavac.xml
deleted file mode 100644
index cba46ff58d8..00000000000
--- a/make/ide/idea/langtools/template/runConfigurations/sjavac.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/make/langtools/build.properties b/make/langtools/build.properties
index 30ca441558c..b82d9155806 100644
--- a/make/langtools/build.properties
+++ b/make/langtools/build.properties
@@ -59,7 +59,6 @@ full.version = ${release}+${build.number}
tool.javac.main.class=com.sun.tools.javac.Main
tool.javadoc.main.class=jdk.javadoc.internal.tool.Main
tool.javap.main.class=com.sun.tools.javap.Main
-tool.sjavac.main.class=com.sun.tools.sjavac.Main
tool.jshell.main.class=jdk.internal.jshell.tool.JShellToolProvider
#test configuration:
diff --git a/make/langtools/build.xml b/make/langtools/build.xml
index 400edb6f674..d64b8aca4f3 100644
--- a/make/langtools/build.xml
+++ b/make/langtools/build.xml
@@ -238,7 +238,6 @@
-
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/AutoFlushWriter.java b/make/langtools/tools/javacserver/AutoFlushWriter.java
similarity index 94%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/AutoFlushWriter.java
rename to make/langtools/tools/javacserver/AutoFlushWriter.java
index 8741aa5cef5..92d64399690 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/AutoFlushWriter.java
+++ b/make/langtools/tools/javacserver/AutoFlushWriter.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac;
+package javacserver;
import java.io.FilterWriter;
import java.io.IOException;
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Log.java b/make/langtools/tools/javacserver/Log.java
similarity index 97%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/Log.java
rename to make/langtools/tools/javacserver/Log.java
index 11b1ebd37b1..49b62876083 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Log.java
+++ b/make/langtools/tools/javacserver/Log.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac;
+package javacserver;
import java.io.PrintWriter;
import java.io.StringWriter;
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Main.java b/make/langtools/tools/javacserver/Main.java
similarity index 88%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/Main.java
rename to make/langtools/tools/javacserver/Main.java
index d71f4521529..2eecfb2b4a8 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Main.java
+++ b/make/langtools/tools/javacserver/Main.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,14 +23,14 @@
* questions.
*/
-package com.sun.tools.sjavac;
-
-import static com.sun.tools.sjavac.options.Option.STARTSERVER;
+package javacserver;
import java.util.Arrays;
-import com.sun.tools.sjavac.client.ClientMain;
-import com.sun.tools.sjavac.server.ServerMain;
+import javacserver.client.ClientMain;
+import javacserver.server.ServerMain;
+
+import static javacserver.options.Option.STARTSERVER;
/**
* The application entry point of the smart javac wrapper tool.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/FileObjectWithLocation.java b/make/langtools/tools/javacserver/Result.java
similarity index 60%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/FileObjectWithLocation.java
rename to make/langtools/tools/javacserver/Result.java
index 142363ae9c9..084089fb01c 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/FileObjectWithLocation.java
+++ b/make/langtools/tools/javacserver/Result.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,33 +23,34 @@
* questions.
*/
-package com.sun.tools.sjavac.comp;
+package javacserver;
-import javax.tools.FileObject;
-import javax.tools.ForwardingFileObject;
-import javax.tools.JavaFileManager.Location;
+/** Result codes.
+ */
+public enum Result {
+ OK(0), // Compilation completed with no errors.
+ ERROR(1), // Completed but reported errors.
+ CMDERR(2), // Bad command-line arguments
+ SYSERR(3), // System error or resource exhaustion.
+ ABNORMAL(4); // Compiler terminated abnormally
-import com.sun.tools.javac.api.ClientCodeWrapper.Trusted;
-
-@Trusted
-public class FileObjectWithLocation extends ForwardingFileObject {
-
- private final Location loc;
-
- public FileObjectWithLocation(F delegate, Location loc) {
- super(delegate);
- this.loc = loc;
+ Result(int exitCode) {
+ this.exitCode = exitCode;
}
- public Location getLocation() {
- return loc;
+ public static Result of(int exitcode) {
+ for (Result result : values()) {
+ if (result.exitCode == exitcode) {
+ return result;
+ }
+ }
+
+ return ABNORMAL;
}
- public FileObject getDelegate() {
- return fileObject;
+ public boolean isOK() {
+ return (exitCode == 0);
}
- public String toString() {
- return "FileObjectWithLocation[" + fileObject + "]";
- }
+ public final int exitCode;
}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Util.java b/make/langtools/tools/javacserver/Util.java
similarity index 54%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/Util.java
rename to make/langtools/tools/javacserver/Util.java
index 2d9d1b40034..96558d503c8 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Util.java
+++ b/make/langtools/tools/javacserver/Util.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,21 +23,15 @@
* questions.
*/
-package com.sun.tools.sjavac;
+package javacserver;
-import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
-import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
-import java.util.Map;
import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.function.Function;
import java.util.regex.Pattern;
-import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@@ -50,30 +44,7 @@ import java.util.stream.Stream;
*/
public class Util {
- public static String toFileSystemPath(String pkgId) {
- if (pkgId == null || pkgId.length()==0) return null;
- String pn;
- if (pkgId.charAt(0) == ':') {
- // When the module is the default empty module.
- // Do not prepend the module directory, because there is none.
- // Thus :java.foo.bar translates to java/foo/bar (or \)
- pn = pkgId.substring(1).replace('.',File.separatorChar);
- } else {
- // There is a module. Thus jdk.base:java.foo.bar translates
- // into jdk.base/java/foo/bar
- int cp = pkgId.indexOf(':');
- String mn = pkgId.substring(0,cp);
- pn = mn+File.separatorChar+pkgId.substring(cp+1).replace('.',File.separatorChar);
- }
- return pn;
- }
- public static String justPackageName(String pkgName) {
- int c = pkgName.indexOf(":");
- if (c == -1)
- throw new IllegalArgumentException("Expected ':' in package name (" + pkgName + ")");
- return pkgName.substring(c+1);
- }
public static String extractStringOption(String opName, String s) {
return extractStringOption(opName, s, null);
@@ -96,17 +67,6 @@ public class Util {
return extractStringOptionWithDelimiter(opName, s, deflt, '\n').strip();
}
- public static boolean extractBooleanOption(String opName, String s, boolean deflt) {
- String str = extractStringOption(opName, s);
- return "true".equals(str) ? true
- : "false".equals(str) ? false
- : deflt;
- }
-
- public static int extractIntOption(String opName, String s) {
- return extractIntOption(opName, s, 0);
- }
-
public static int extractIntOption(String opName, String s, int deflt) {
int p = s.indexOf(opName+"=");
if (p == -1) return deflt;
@@ -120,47 +80,6 @@ public class Util {
return v;
}
- /**
- * Extract the package name from a fully qualified class name.
- *
- * Example: Given "pkg.subpkg.A" this method returns ":pkg.subpkg".
- * Given "C" this method returns ":".
- *
- * @returns package name of the given class name
- */
- public static String pkgNameOfClassName(String fqClassName) {
- int i = fqClassName.lastIndexOf('.');
- String pkg = i == -1 ? "" : fqClassName.substring(0, i);
- return ":" + pkg;
- }
-
- /**
- * Clean out unwanted sub options supplied inside a primary option.
- * For example to only had portfile remaining from:
- * settings="--server:id=foo,portfile=bar"
- * do settings = cleanOptions("--server:",Util.set("-portfile"),settings);
- * now settings equals "--server:portfile=bar"
- *
- * @param allowedSubOptions A set of the allowed sub options, id portfile etc.
- * @param s The option settings string.
- */
- public static String cleanSubOptions(Set allowedSubOptions, String s) {
- StringBuilder sb = new StringBuilder();
- StringTokenizer st = new StringTokenizer(s, ",");
- while (st.hasMoreTokens()) {
- String o = st.nextToken();
- int p = o.indexOf('=');
- if (p>0) {
- String key = o.substring(0,p);
- String val = o.substring(p+1);
- if (allowedSubOptions.contains(key)) {
- if (sb.length() > 0) sb.append(',');
- sb.append(key+"="+val);
- }
- }
- }
- return sb.toString();
- }
/**
* Convenience method to create a set with strings.
@@ -191,17 +110,6 @@ public class Util {
return file;
}
- /**
- * Locate the setting for the server properties.
- */
- public static String findServerSettings(String[] args) {
- for (String s : args) {
- if (s.startsWith("--server:")) {
- return s;
- }
- }
- return null;
- }
public static Set union(Set extends E> s1,
Set extends E> s2) {
@@ -224,11 +132,6 @@ public class Util {
return sw.toString();
}
- // TODO: Remove when refactoring from java.io.File to java.nio.file.Path.
- public static File pathToFile(Path path) {
- return path == null ? null : path.toFile();
- }
-
public static Set intersection(Collection extends E> c1,
Collection extends E> c2) {
Set intersection = new HashSet(c1);
@@ -236,16 +139,6 @@ public class Util {
return intersection;
}
- public static Map indexBy(Collection extends T> c,
- Function super T, ? extends I> indexFunction) {
- return c.stream().collect(Collectors.toMap(indexFunction, o -> o));
- }
-
- public static String fileSuffix(Path file) {
- String fileNameStr = file.getFileName().toString();
- int dotIndex = fileNameStr.indexOf('.');
- return dotIndex == -1 ? "" : fileNameStr.substring(dotIndex);
- }
public static Stream getLines(String str) {
return str.isEmpty()
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/ClientMain.java b/make/langtools/tools/javacserver/client/ClientMain.java
similarity index 77%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/ClientMain.java
rename to make/langtools/tools/javacserver/client/ClientMain.java
index 5ba63fed8d5..c26ead5e633 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/ClientMain.java
+++ b/make/langtools/tools/javacserver/client/ClientMain.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,19 +23,17 @@
* questions.
*/
-package com.sun.tools.sjavac.client;
+package javacserver.client;
import java.io.OutputStreamWriter;
import java.io.Writer;
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.AutoFlushWriter;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Util;
-import com.sun.tools.sjavac.comp.SjavacImpl;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.server.Sjavac;
+import javacserver.AutoFlushWriter;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.comp.SjavacImpl;
+import javacserver.options.Options;
+import javacserver.server.Sjavac;
/**
*
This is NOT part of any supported API.
@@ -65,11 +63,6 @@ public class ClientMain {
Log.setLogLevel(options.getLogLevel());
- Log.debug("==========================================================");
- Log.debug("Launching sjavac client with the following parameters:");
- Log.debug(" " + options.getStateArgsString());
- Log.debug("==========================================================");
-
// Prepare sjavac object
boolean useServer = options.getServerConf() != null;
Sjavac sjavac = useServer ? new SjavacClient(options) : new SjavacImpl();
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/PortFileInaccessibleException.java b/make/langtools/tools/javacserver/client/PortFileInaccessibleException.java
similarity index 92%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/PortFileInaccessibleException.java
rename to make/langtools/tools/javacserver/client/PortFileInaccessibleException.java
index 44d383566c6..c9db8dfc44a 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/PortFileInaccessibleException.java
+++ b/make/langtools/tools/javacserver/client/PortFileInaccessibleException.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.client;
+package javacserver.client;
import java.io.IOException;
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/SjavacClient.java b/make/langtools/tools/javacserver/client/SjavacClient.java
similarity index 94%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/SjavacClient.java
rename to make/langtools/tools/javacserver/client/SjavacClient.java
index 20886f1bd9e..3d12eb31782 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/client/SjavacClient.java
+++ b/make/langtools/tools/javacserver/client/SjavacClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.client;
+package javacserver.client;
import java.io.BufferedReader;
import java.io.IOException;
@@ -40,14 +40,13 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Util;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.server.PortFile;
-import com.sun.tools.sjavac.server.Sjavac;
-import com.sun.tools.sjavac.server.SjavacServer;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.Util;
+import javacserver.options.Options;
+import javacserver.server.PortFile;
+import javacserver.server.Sjavac;
+import javacserver.server.SjavacServer;
/**
* Sjavac implementation that delegates requests to a SjavacServer.
@@ -62,7 +61,7 @@ public class SjavacClient implements Sjavac {
private PortFile portFile;
// The servercmd option specifies how the server part of sjavac is spawned.
- // It should point to a com.sun.tools.sjavac.Main that supports --startserver
+ // It should point to a javacserver.Main that supports --startserver
private String serverCommand;
// Accept 120 seconds of inactivity before quitting.
@@ -144,7 +143,7 @@ public class SjavacClient implements Sjavac {
}
if (type.equals(SjavacServer.LINE_TYPE_RC)) {
- result = Main.Result.valueOf(content);
+ result = Result.valueOf(content);
}
}
} catch (PortFileInaccessibleException e) {
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PooledSjavac.java b/make/langtools/tools/javacserver/comp/PooledSjavac.java
similarity index 93%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PooledSjavac.java
rename to make/langtools/tools/javacserver/comp/PooledSjavac.java
index f84d52d5296..3647f17cc10 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PooledSjavac.java
+++ b/make/langtools/tools/javacserver/comp/PooledSjavac.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,17 +23,17 @@
* questions.
*/
-package com.sun.tools.sjavac.comp;
-
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.server.Sjavac;
+package javacserver.comp;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.server.Sjavac;
+
/**
* An sjavac implementation that limits the number of concurrent calls by
* wrapping invocations in Callables and delegating them to a FixedThreadPool.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartWriter.java b/make/langtools/tools/javacserver/comp/SjavacImpl.java
similarity index 50%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartWriter.java
rename to make/langtools/tools/javacserver/comp/SjavacImpl.java
index 2d1fa389858..eb7ba30f73d 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartWriter.java
+++ b/make/langtools/tools/javacserver/comp/SjavacImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,57 +23,56 @@
* questions.
*/
-package com.sun.tools.sjavac.comp;
+package javacserver.comp;
-import com.sun.tools.sjavac.Log;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.stream.Stream;
-import java.io.*;
-import javax.tools.JavaFileObject;
+import com.sun.tools.javac.Main;
+
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.Util;
+import javacserver.options.Option;
+import javacserver.server.Sjavac;
/**
- * The SmartWriter will cache the written data and when the writer is closed,
- * then it will compare the cached data with the old_content string.
- * If different, then it will write all the new content to the file.
- * If not, the file is not touched.
+ * The sjavac implementation that interacts with javac and performs the actual
+ * compilation.
*
*
This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.
*/
-public class SmartWriter extends Writer {
+public class SjavacImpl implements Sjavac {
- String name;
- JavaFileObject file;
- String oldContent;
- StringWriter newContent = new StringWriter();
- boolean closed;
+ @Override
+ @SuppressWarnings("deprecated")
+ public Result compile(String[] args) {
+ // Direct logging to our byte array stream.
+ StringWriter strWriter = new StringWriter();
+ PrintWriter printWriter = new PrintWriter(strWriter);
+
+ // Prepare arguments
+ String[] passThroughArgs = Stream.of(args)
+ .filter(arg -> !arg.startsWith(Option.SERVER.arg))
+ .toArray(String[]::new);
+ // Compile
+ int exitcode = Main.compile(passThroughArgs, printWriter);
+ Result result = Result.of(exitcode);
+
+ // Process compiler output (which is always errors)
+ printWriter.flush();
+ Util.getLines(strWriter.toString()).forEach(Log::error);
+
+ return result;
- public SmartWriter(JavaFileObject f, String s, String n) {
- name = n;
- file = f;
- oldContent = s;
- newContent = new StringWriter();
- closed = false;
}
- public void write(char[] chars, int i, int i1) {
- newContent.write(chars, i, i1);
- }
-
- public void close() throws IOException {
- if (closed) return;
- closed = true;
- String s = newContent.toString();
- if (!oldContent.equals(s)) {
- int p = file.getName().lastIndexOf(File.separatorChar);
- try (Writer writer = file.openWriter()) {
- writer.write(s);
- }
- Log.debug("Writing " + file.getName().substring(p + 1));
- }
- }
-
- public void flush() throws IOException {
+ @Override
+ public void shutdown() {
+ // Nothing to clean up
}
}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/options/ArgumentIterator.java b/make/langtools/tools/javacserver/options/ArgumentIterator.java
similarity index 95%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/options/ArgumentIterator.java
rename to make/langtools/tools/javacserver/options/ArgumentIterator.java
index 69d89e7fd85..54c6105227a 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/options/ArgumentIterator.java
+++ b/make/langtools/tools/javacserver/options/ArgumentIterator.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.options;
+package javacserver.options;
import java.util.Iterator;
diff --git a/make/langtools/tools/javacserver/options/CommandLine.java b/make/langtools/tools/javacserver/options/CommandLine.java
new file mode 100644
index 00000000000..017d32a0d7c
--- /dev/null
+++ b/make/langtools/tools/javacserver/options/CommandLine.java
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javacserver.options;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Various utility methods for processing Java tool command line arguments.
+ *
+ *
This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own risk.
+ * This code and its internal interfaces are subject to change or
+ * deletion without notice.
+ */
+public class CommandLine {
+ /**
+ * Process Win32-style command files for the specified command line
+ * arguments and return the resulting arguments. A command file argument
+ * is of the form '@file' where 'file' is the name of the file whose
+ * contents are to be parsed for additional arguments. The contents of
+ * the command file are parsed using StreamTokenizer and the original
+ * '@file' argument replaced with the resulting tokens. Recursive command
+ * files are not supported. The '@' character itself can be quoted with
+ * the sequence '@@'.
+ * @param args the arguments that may contain @files
+ * @return the arguments, with @files expanded
+ * @throws IOException if there is a problem reading any of the @files
+ */
+ public static List parse(List args) throws IOException {
+ List newArgs = new ArrayList<>();
+ appendParsedCommandArgs(newArgs, args);
+ return newArgs;
+ }
+
+ private static void appendParsedCommandArgs(List newArgs, List args) throws IOException {
+ for (String arg : args) {
+ if (arg.length() > 1 && arg.charAt(0) == '@') {
+ arg = arg.substring(1);
+ if (arg.charAt(0) == '@') {
+ newArgs.add(arg);
+ } else {
+ loadCmdFile(arg, newArgs);
+ }
+ } else {
+ newArgs.add(arg);
+ }
+ }
+ }
+
+ /**
+ * Process the given environment variable and appends any Win32-style
+ * command files for the specified command line arguments and return
+ * the resulting arguments. A command file argument
+ * is of the form '@file' where 'file' is the name of the file whose
+ * contents are to be parsed for additional arguments. The contents of
+ * the command file are parsed using StreamTokenizer and the original
+ * '@file' argument replaced with the resulting tokens. Recursive command
+ * files are not supported. The '@' character itself can be quoted with
+ * the sequence '@@'.
+ * @param envVariable the env variable to process
+ * @param args the arguments that may contain @files
+ * @return the arguments, with environment variable's content and expansion of @files
+ * @throws IOException if there is a problem reading any of the @files
+ * @throws UnmatchedQuote
+ */
+ public static List parse(String envVariable, List args)
+ throws IOException, UnmatchedQuote {
+
+ List inArgs = new ArrayList<>();
+ appendParsedEnvVariables(inArgs, envVariable);
+ inArgs.addAll(args);
+ List newArgs = new ArrayList<>();
+ appendParsedCommandArgs(newArgs, inArgs);
+ return newArgs;
+ }
+
+ private static void loadCmdFile(String name, List args) throws IOException {
+ try (Reader r = Files.newBufferedReader(Paths.get(name), Charset.defaultCharset())) {
+ Tokenizer t = new Tokenizer(r);
+ String s;
+ while ((s = t.nextToken()) != null) {
+ args.add(s);
+ }
+ }
+ }
+
+ public static class Tokenizer {
+ private final Reader in;
+ private int ch;
+
+ public Tokenizer(Reader in) throws IOException {
+ this.in = in;
+ ch = in.read();
+ }
+
+ public String nextToken() throws IOException {
+ skipWhite();
+ if (ch == -1) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ char quoteChar = 0;
+
+ while (ch != -1) {
+ switch (ch) {
+ case ' ':
+ case '\t':
+ case '\f':
+ if (quoteChar == 0) {
+ return sb.toString();
+ }
+ sb.append((char) ch);
+ break;
+
+ case '\n':
+ case '\r':
+ return sb.toString();
+
+ case '\'':
+ case '"':
+ if (quoteChar == 0) {
+ quoteChar = (char) ch;
+ } else if (quoteChar == ch) {
+ quoteChar = 0;
+ } else {
+ sb.append((char) ch);
+ }
+ break;
+
+ case '\\':
+ if (quoteChar != 0) {
+ ch = in.read();
+ switch (ch) {
+ case '\n':
+ case '\r':
+ while (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f') {
+ ch = in.read();
+ }
+ continue;
+
+ case 'n':
+ ch = '\n';
+ break;
+ case 'r':
+ ch = '\r';
+ break;
+ case 't':
+ ch = '\t';
+ break;
+ case 'f':
+ ch = '\f';
+ break;
+ }
+ }
+ sb.append((char) ch);
+ break;
+
+ default:
+ sb.append((char) ch);
+ }
+
+ ch = in.read();
+ }
+
+ return sb.toString();
+ }
+
+ void skipWhite() throws IOException {
+ while (ch != -1) {
+ switch (ch) {
+ case ' ':
+ case '\t':
+ case '\n':
+ case '\r':
+ case '\f':
+ break;
+
+ case '#':
+ ch = in.read();
+ while (ch != '\n' && ch != '\r' && ch != -1) {
+ ch = in.read();
+ }
+ break;
+
+ default:
+ return;
+ }
+
+ ch = in.read();
+ }
+ }
+ }
+
+ @SuppressWarnings("fallthrough")
+ private static void appendParsedEnvVariables(List newArgs, String envVariable)
+ throws UnmatchedQuote {
+
+ if (envVariable == null) {
+ return;
+ }
+ String in = System.getenv(envVariable);
+ if (in == null || in.trim().isEmpty()) {
+ return;
+ }
+
+ final char NUL = (char)0;
+ final int len = in.length();
+
+ int pos = 0;
+ StringBuilder sb = new StringBuilder();
+ char quote = NUL;
+ char ch;
+
+ loop:
+ while (pos < len) {
+ ch = in.charAt(pos);
+ switch (ch) {
+ case '\"': case '\'':
+ if (quote == NUL) {
+ quote = ch;
+ } else if (quote == ch) {
+ quote = NUL;
+ } else {
+ sb.append(ch);
+ }
+ pos++;
+ break;
+ case '\f': case '\n': case '\r': case '\t': case ' ':
+ if (quote == NUL) {
+ newArgs.add(sb.toString());
+ sb.setLength(0);
+ while (ch == '\f' || ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
+ pos++;
+ if (pos >= len) {
+ break loop;
+ }
+ ch = in.charAt(pos);
+ }
+ break;
+ }
+ // fall through
+ default:
+ sb.append(ch);
+ pos++;
+ }
+ }
+ if (sb.length() != 0) {
+ newArgs.add(sb.toString());
+ }
+ if (quote != NUL) {
+ throw new UnmatchedQuote(envVariable);
+ }
+ }
+
+ public static class UnmatchedQuote extends Exception {
+ private static final long serialVersionUID = 0;
+
+ public final String variableName;
+
+ UnmatchedQuote(String variable) {
+ this.variableName = variable;
+ }
+ }
+}
diff --git a/make/langtools/tools/javacserver/options/Option.java b/make/langtools/tools/javacserver/options/Option.java
new file mode 100644
index 00000000000..2856c65627b
--- /dev/null
+++ b/make/langtools/tools/javacserver/options/Option.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javacserver.options;
+
+/**
+ * Sjavac options can be classified as:
+ *
+ * (1) relevant only for sjavac, such as --server
+ * (2) relevant for sjavac and javac, such as -d, or
+ * (3) relevant only for javac, such as -g.
+ *
+ * This enum represents all options from (1) and (2). Note that instances of
+ * this enum only entail static information about the option. For storage of
+ * option values, refer to Options.
+ *
+ *
This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own risk.
+ * This code and its internal interfaces are subject to change or
+ * deletion without notice.
+ */
+public enum Option {
+ SERVER("--server:", "Specify server configuration file of running server") {
+ @Override
+ protected void processMatching(ArgumentIterator iter, Options.ArgDecoderOptionHelper helper) {
+ helper.serverConf(iter.current().substring(arg.length()));
+ }
+ },
+ STARTSERVER("--startserver:", "Start server and use the given configuration file") {
+ @Override
+ protected void processMatching(ArgumentIterator iter, Options.ArgDecoderOptionHelper helper) {
+ helper.startServerConf(iter.current().substring(arg.length()));
+ }
+ };
+
+
+ public final String arg;
+
+ final String description;
+
+ private Option(String arg, String description) {
+ this.arg = arg;
+ this.description = description;
+ }
+
+ // Future cleanup: Change the "=" syntax to ":" syntax to be consistent and
+ // to follow the javac-option style.
+
+ public boolean hasOption() {
+ return arg.endsWith(":") || arg.endsWith("=");
+ }
+
+
+ /**
+ * Process current argument of argIter.
+ *
+ * It's final, since the option customization is typically done in
+ * processMatching.
+ *
+ * @param argIter Iterator to read current and succeeding arguments from.
+ * @param helper The helper to report back to.
+ * @return true iff the argument was processed by this option.
+ */
+ public final boolean processCurrent(ArgumentIterator argIter,
+ Options.ArgDecoderOptionHelper helper) {
+ String fullArg = argIter.current(); // "-tr" or "-log=level"
+ if (hasOption() ? fullArg.startsWith(arg) : fullArg.equals(arg)) {
+ processMatching(argIter, helper);
+ return true;
+ }
+ // Did not match
+ return false;
+ }
+
+ /** Called by process if the current argument matches this option. */
+ protected abstract void processMatching(ArgumentIterator argIter,
+ Options.ArgDecoderOptionHelper helper);
+}
diff --git a/make/langtools/tools/javacserver/options/Options.java b/make/langtools/tools/javacserver/options/Options.java
new file mode 100644
index 00000000000..507e7134fdd
--- /dev/null
+++ b/make/langtools/tools/javacserver/options/Options.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javacserver.options;
+
+import java.util.List;
+
+/**
+ * Instances of this class represent values for sjavac command line options.
+ *
+ *
This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own risk.
+ * This code and its internal interfaces are subject to change or
+ * deletion without notice.
+ */
+public class Options {
+ private String logLevel = "info";
+
+ private boolean startServer = false;
+
+ // Server configuration string
+ private String serverConf;
+
+ /** Get the log level. */
+ public String getLogLevel() {
+ return logLevel;
+ }
+
+ /** Return true iff a new server should be started */
+ public boolean startServerFlag() {
+ return startServer;
+ }
+
+ /** Return the server configuration string. */
+ public String getServerConf() {
+ return serverConf;
+ }
+
+ /**
+ * Parses the given argument array and returns a corresponding Options
+ * instance.
+ */
+ public static Options parseArgs(String... args) {
+ Options options = new Options();
+ options.new ArgDecoderOptionHelper().traverse(args);
+ return options;
+ }
+
+ // OptionHelper that records the traversed options in this Options instance.
+ public class ArgDecoderOptionHelper {
+ public void reportError(String msg) {
+ throw new IllegalArgumentException(msg);
+ }
+
+ public void serverConf(String conf) {
+ if (serverConf != null)
+ reportError("Can not specify more than one server configuration.");
+ else
+ serverConf = conf;
+ }
+
+ public void startServerConf(String conf) {
+ if (serverConf != null)
+ reportError("Can not specify more than one server configuration.");
+ else {
+ startServer = true;
+ serverConf = conf;
+ }
+ }
+
+ /**
+ * Traverses an array of arguments and performs the appropriate callbacks.
+ *
+ * @param args the arguments to traverse.
+ */
+ void traverse(String[] args) {
+ Iterable allArgs;
+ try {
+ allArgs = CommandLine.parse(List.of(args)); // Detect @file and load it as a command line.
+ } catch (java.io.IOException e) {
+ throw new IllegalArgumentException("Problem reading @"+e.getMessage());
+ }
+ ArgumentIterator argIter = new ArgumentIterator(allArgs);
+
+ nextArg:
+ while (argIter.hasNext()) {
+
+ String arg = argIter.next();
+
+ if (arg.startsWith("-")) {
+ for (Option opt : Option.values()) {
+ if (opt.processCurrent(argIter, this))
+ continue nextArg;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/IdleResetSjavac.java b/make/langtools/tools/javacserver/server/IdleResetSjavac.java
similarity index 95%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/IdleResetSjavac.java
rename to make/langtools/tools/javacserver/server/IdleResetSjavac.java
index 724c5062d5d..be4be86c622 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/IdleResetSjavac.java
+++ b/make/langtools/tools/javacserver/server/IdleResetSjavac.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,14 +23,14 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
-
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.Log;
+package javacserver.server;
import java.util.Timer;
import java.util.TimerTask;
+import javacserver.Log;
+import javacserver.Result;
+
/**
* An sjavac implementation that keeps track of idleness and shuts down the
* given Terminable upon idleness timeout.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFile.java b/make/langtools/tools/javacserver/server/PortFile.java
similarity index 96%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFile.java
rename to make/langtools/tools/javacserver/server/PortFile.java
index dad5514c02b..3874a4c1ee2 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFile.java
+++ b/make/langtools/tools/javacserver/server/PortFile.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
+package javacserver.server;
import java.io.File;
import java.io.FileNotFoundException;
@@ -35,9 +35,8 @@ import java.nio.channels.FileLock;
import java.nio.channels.FileLockInterruptionException;
import java.util.concurrent.Semaphore;
-import com.sun.tools.javac.util.Assert;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.client.PortFileInaccessibleException;
+import javacserver.Log;
+import javacserver.client.PortFileInaccessibleException;
/**
* The PortFile class mediates access to a short binary file containing the tcp/ip port (for the localhost)
@@ -151,7 +150,6 @@ public class PortFile {
* If so, then we can acquire the tcp/ip port on localhost.
*/
public int getPort() {
- Assert.check(containsPortInfo);
return serverPort;
}
@@ -159,7 +157,6 @@ public class PortFile {
* If so, then we can acquire the server cookie.
*/
public long getCookie() {
- Assert.check(containsPortInfo);
return serverCookie;
}
@@ -167,7 +164,6 @@ public class PortFile {
* Store the values into the locked port file.
*/
public void setValues(int port, long cookie) throws IOException {
- Assert.check(lock != null);
rwfile.seek(0);
// Write the magic nr that identifies a port file.
rwfile.writeInt(magicNr);
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFileMonitor.java b/make/langtools/tools/javacserver/server/PortFileMonitor.java
similarity index 96%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFileMonitor.java
rename to make/langtools/tools/javacserver/server/PortFileMonitor.java
index 3f2200e8b4e..1b8828c694b 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/PortFileMonitor.java
+++ b/make/langtools/tools/javacserver/server/PortFileMonitor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,14 +23,14 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
-
-import com.sun.tools.sjavac.Log;
+package javacserver.server;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
+import javacserver.Log;
+
/**
* Monitors the presence of a port file and shuts down the given SjavacServer
* whenever the port file is deleted or invalidated.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/RequestHandler.java b/make/langtools/tools/javacserver/server/RequestHandler.java
similarity index 93%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/RequestHandler.java
rename to make/langtools/tools/javacserver/server/RequestHandler.java
index e26a5c77766..b2d04e4606b 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/RequestHandler.java
+++ b/make/langtools/tools/javacserver/server/RequestHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,11 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
-
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Util;
+package javacserver.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -35,7 +31,11 @@ import java.io.PrintWriter;
import java.net.Socket;
import java.nio.file.Path;
-import static com.sun.tools.sjavac.server.SjavacServer.LINE_TYPE_RC;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.Util;
+
+import static javacserver.server.SjavacServer.LINE_TYPE_RC;
/**
@@ -101,7 +101,7 @@ public class RequestHandler extends Thread {
checkInternalErrorLog();
// Perform compilation
- Main.Result rc = sjavac.compile(args);
+ Result rc = sjavac.compile(args);
// Send return code back to client
out.println(LINE_TYPE_RC + ":" + rc.name());
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/ServerMain.java b/make/langtools/tools/javacserver/server/ServerMain.java
similarity index 84%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/ServerMain.java
rename to make/langtools/tools/javacserver/server/ServerMain.java
index 39c22966e22..1f5b51755bb 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/ServerMain.java
+++ b/make/langtools/tools/javacserver/server/ServerMain.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,24 +23,18 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
+package javacserver.server;
-import java.io.FileWriter;
-import java.io.FilterOutputStream;
-import java.io.FilterWriter;
import java.io.IOException;
import java.io.PrintStream;
-import java.lang.Thread.UncaughtExceptionHandler;
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Log.Level;
-import com.sun.tools.sjavac.server.log.LazyInitFileLog;
-import com.sun.tools.sjavac.server.log.LoggingOutputStream;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.server.log.LazyInitFileLog;
+import javacserver.server.log.LoggingOutputStream;
-import static com.sun.tools.sjavac.Log.Level.ERROR;
-import static com.sun.tools.sjavac.Log.Level.INFO;
+import static javacserver.Log.Level.ERROR;
+import static javacserver.Log.Level.INFO;
/**
*
This is NOT part of any supported API.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Sjavac.java b/make/langtools/tools/javacserver/server/Sjavac.java
similarity index 90%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Sjavac.java
rename to make/langtools/tools/javacserver/server/Sjavac.java
index dd3c43db74d..9c7c980c2f2 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Sjavac.java
+++ b/make/langtools/tools/javacserver/server/Sjavac.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,12 +23,9 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
-
-import com.sun.tools.javac.main.Main.Result;
-
-import java.io.Writer;
+package javacserver.server;
+import javacserver.Result;
/**
* Interface of the SjavacImpl, the sjavac client and all wrappers such as
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SjavacServer.java b/make/langtools/tools/javacserver/server/SjavacServer.java
similarity index 94%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SjavacServer.java
rename to make/langtools/tools/javacserver/server/SjavacServer.java
index a1a8951de21..d52e274c4ac 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SjavacServer.java
+++ b/make/langtools/tools/javacserver/server/SjavacServer.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,13 +23,10 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
+package javacserver.server;
import java.io.FileNotFoundException;
-import java.io.FileWriter;
import java.io.IOException;
-import java.io.PrintStream;
-import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
@@ -40,13 +37,11 @@ import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Util;
-import com.sun.tools.sjavac.client.PortFileInaccessibleException;
-import com.sun.tools.sjavac.comp.PooledSjavac;
-import com.sun.tools.sjavac.comp.SjavacImpl;
+import javacserver.Log;
+import javacserver.Result;
+import javacserver.Util;
+import javacserver.comp.PooledSjavac;
+import javacserver.comp.SjavacImpl;
/**
* The JavacServer class contains methods both to setup a server that responds to requests and methods to connect to this server.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Terminable.java b/make/langtools/tools/javacserver/server/Terminable.java
similarity index 92%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Terminable.java
rename to make/langtools/tools/javacserver/server/Terminable.java
index 430f7353025..5c598ddc420 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/Terminable.java
+++ b/make/langtools/tools/javacserver/server/Terminable.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.server;
+package javacserver.server;
/**
*
This is NOT part of any supported API.
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LazyInitFileLog.java b/make/langtools/tools/javacserver/server/log/LazyInitFileLog.java
similarity index 94%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LazyInitFileLog.java
rename to make/langtools/tools/javacserver/server/log/LazyInitFileLog.java
index 2b6cf9cee65..5471b8f0196 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LazyInitFileLog.java
+++ b/make/langtools/tools/javacserver/server/log/LazyInitFileLog.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,9 +23,7 @@
* questions.
*/
-package com.sun.tools.sjavac.server.log;
-
-import com.sun.tools.sjavac.Log;
+package javacserver.server.log;
import java.io.FileWriter;
import java.io.IOException;
@@ -34,6 +32,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import javacserver.Log;
+
public class LazyInitFileLog extends Log {
String baseFilename;
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LoggingOutputStream.java b/make/langtools/tools/javacserver/server/log/LoggingOutputStream.java
similarity index 94%
rename from src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LoggingOutputStream.java
rename to make/langtools/tools/javacserver/server/log/LoggingOutputStream.java
index 56b048376ce..6df616bd5e2 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/log/LoggingOutputStream.java
+++ b/make/langtools/tools/javacserver/server/log/LoggingOutputStream.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,15 +23,15 @@
* questions.
*/
-package com.sun.tools.sjavac.server.log;
-
-import com.sun.tools.sjavac.Log;
+package javacserver.server.log;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
+import javacserver.Log;
+
public class LoggingOutputStream extends FilterOutputStream {
private static final byte[] LINE_SEP = System.lineSeparator().getBytes();
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java
index ab7582e7ced..21a29ac8e82 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java
@@ -214,8 +214,6 @@ public class ClassFinder {
}
if (fm instanceof JavacFileManager javacFileManager) {
useCtProps = javacFileManager.isDefaultBootClassPath() && javacFileManager.isSymbolFileEnabled();
- } else if (fm.getClass().getName().equals("com.sun.tools.sjavac.comp.SmartFileManager")) {
- useCtProps = !options.isSet("ignore.symbol.file");
} else {
useCtProps = false;
}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/BuildState.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/BuildState.java
deleted file mode 100644
index fdfa48eb04b..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/BuildState.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import com.sun.tools.javac.util.Assert;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The build state class captures the source code and generated artifacts
- * from a build. There are usually two build states, the previous one (prev),
- * loaded from the javac_state file, and the current one (now).
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class BuildState {
- private Map modules = new HashMap<>();
- private Map packages = new HashMap<>();
- private Map sources = new HashMap<>();
- private Map artifacts = new HashMap<>();
- // Map from package to a set of packages that depend on said package.
- private Map> dependents = new HashMap<>();
-
- public Map modules() { return modules; }
- public Map packages() { return packages; }
- public Map sources() { return sources; }
- public Map artifacts() { return artifacts; }
- public Map> dependents() { return dependents; }
-
- /**
- * Lookup a module from a name. Create the module if it does
- * not exist yet.
- */
- public Module lookupModule(String mod) {
- Module m = modules.get(mod);
- if (m == null) {
- m = new Module(mod, "???");
- modules.put(mod, m);
- }
- return m;
- }
-
- /**
- * Find a module from a given package name. For example:
- * The package name "base:java.lang" will fetch the module named "base".
- * The package name ":java.net" will fetch the default module.
- */
- Module findModuleFromPackageName(String pkg) {
- int cp = pkg.indexOf(':');
- Assert.check(cp != -1, "Could not find package name");
- String mod = pkg.substring(0, cp);
- return lookupModule(mod);
- }
-
- /**
- * Store references to all packages, sources and artifacts for all modules
- * into the build state. I.e. flatten the module tree structure
- * into global maps stored in the BuildState for easy access.
- *
- * @param m The set of modules.
- */
- public void flattenPackagesSourcesAndArtifacts(Map m) {
- modules = m;
- // Extract all the found packages.
- for (Module i : modules.values()) {
- for (Map.Entry j : i.packages().entrySet()) {
- Package p = packages.get(j.getKey());
- // Check that no two different packages are stored under same name.
- Assert.check(p == null || p == j.getValue());
- if (p == null) {
- p = j.getValue();
- packages.put(j.getKey(),j.getValue());
- }
- for (Map.Entry k : p.sources().entrySet()) {
- Source s = sources.get(k.getKey());
- // Check that no two different sources are stored under same name.
- Assert.check(s == null || s == k.getValue());
- if (s == null) {
- s = k.getValue();
- sources.put(k.getKey(), k.getValue());
- }
- }
- for (Map.Entry g : p.artifacts().entrySet()) {
- File f = artifacts.get(g.getKey());
- // Check that no two artifacts are stored under the same file.
- Assert.check(f == null || f == g.getValue());
- if (f == null) {
- f = g.getValue();
- artifacts.put(g.getKey(), g.getValue());
- }
- }
- }
- }
- }
-
- /**
- * Store references to all artifacts found in the module tree into the maps
- * stored in the build state.
- *
- * @param m The set of modules.
- */
- public void flattenArtifacts(Map m) {
- modules = m;
- // Extract all the found packages.
- for (Module i : modules.values()) {
- for (Map.Entry j : i.packages().entrySet()) {
- Package p = packages.get(j.getKey());
- // Check that no two different packages are stored under same name.
- Assert.check(p == null || p == j.getValue());
- p = j.getValue();
- packages.put(j.getKey(),j.getValue());
- for (Map.Entry g : p.artifacts().entrySet()) {
- File f = artifacts.get(g.getKey());
- // Check that no two artifacts are stored under the same file.
- Assert.check(f == null || f == g.getValue());
- artifacts.put(g.getKey(), g.getValue());
- }
- }
- }
- }
-
- /**
- * Calculate the package dependents (ie the reverse of the dependencies).
- */
- public void calculateDependents() {
- dependents = new HashMap<>();
-
- for (String s : packages.keySet()) {
- Package p = packages.get(s);
-
- // Collect all dependencies of the classes in this package
- Set deps = p.typeDependencies() // maps fqName -> set of dependencies
- .values()
- .stream()
- .reduce(Collections.emptySet(), Util::union);
-
- // Now reverse the direction
-
- for (String dep : deps) {
- // Add the dependent information to the global dependent map.
- String depPkgStr = ":" + dep.substring(0, dep.lastIndexOf('.'));
- dependents.merge(depPkgStr, Collections.singleton(s), Util::union);
-
- // Also add the dependent information to the package specific map.
- // Normally, you do not compile java.lang et al. Therefore
- // there are several packages that p depends upon that you
- // do not have in your state database. This is perfectly fine.
- Package dp = packages.get(depPkgStr);
- if (dp != null) {
- // But this package did exist in the state database.
- dp.addDependent(p.name());
- }
- }
- }
- }
-
- /**
- * Verify that the setModules method above did the right thing when
- * running through the {@literal module->package->source} structure.
- */
- public void checkInternalState(String msg, boolean linkedOnly, Map srcs) {
- boolean baad = false;
- Map original = new HashMap<>();
- Map calculated = new HashMap<>();
-
- for (String s : sources.keySet()) {
- Source ss = sources.get(s);
- if (ss.isLinkedOnly() == linkedOnly) {
- calculated.put(s,ss);
- }
- }
- for (String s : srcs.keySet()) {
- Source ss = srcs.get(s);
- if (ss.isLinkedOnly() == linkedOnly) {
- original.put(s,ss);
- }
- }
- if (original.size() != calculated.size()) {
- Log.error("INTERNAL ERROR "+msg+" original and calculated are not the same size!");
- baad = true;
- }
- if (!original.keySet().equals(calculated.keySet())) {
- Log.error("INTERNAL ERROR "+msg+" original and calculated do not have the same domain!");
- baad = true;
- }
- if (!baad) {
- for (String s : original.keySet()) {
- Source s1 = original.get(s);
- Source s2 = calculated.get(s);
- if (s1 == null || s2 == null || !s1.equals(s2)) {
- Log.error("INTERNAL ERROR "+msg+" original and calculated have differing elements for "+s);
- }
- baad = true;
- }
- }
- if (baad) {
- for (String s : original.keySet()) {
- Source ss = original.get(s);
- Source sss = calculated.get(s);
- if (sss == null) {
- Log.error("The file "+s+" does not exist in calculated tree of sources.");
- }
- }
- for (String s : calculated.keySet()) {
- Source ss = calculated.get(s);
- Source sss = original.get(s);
- if (sss == null) {
- Log.error("The file "+s+" does not exist in original set of found sources.");
- }
- }
- }
- }
-
- /**
- * Load a module from the javac state file.
- */
- public Module loadModule(String l) {
- Module m = Module.load(l);
- modules.put(m.name(), m);
- return m;
- }
-
- /**
- * Load a package from the javac state file.
- */
- public Package loadPackage(Module lastModule, String l) {
- Package p = Package.load(lastModule, l);
- lastModule.addPackage(p);
- packages.put(p.name(), p);
- return p;
- }
-
- /**
- * Load a source from the javac state file.
- */
- public Source loadSource(Package lastPackage, String l, boolean is_generated) {
- Source s = Source.load(lastPackage, l, is_generated);
- lastPackage.addSource(s);
- sources.put(s.name(), s);
- return s;
- }
-
- /**
- * During an incremental compile we need to copy the old javac state
- * information about packages that were not recompiled.
- */
- public void copyPackagesExcept(BuildState prev, Set recompiled, Set removed) {
- for (String pkg : prev.packages().keySet()) {
- // Do not copy recompiled or removed packages.
- if (recompiled.contains(pkg) || removed.contains(pkg))
- continue;
-
- Module mnew = findModuleFromPackageName(pkg);
- Package pprev = prev.packages().get(pkg);
-
- // Even though we haven't recompiled this package, we may have
- // information about its public API: It may be a classpath dependency
- if (packages.containsKey(pkg)) {
- pprev.setPubapi(PubApi.mergeTypes(pprev.getPubApi(),
- packages.get(pkg).getPubApi()));
- }
-
- mnew.addPackage(pprev);
- // Do not forget to update the flattened data. (See JDK-8071904)
- packages.put(pkg, pprev);
- }
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CleanProperties.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CleanProperties.java
deleted file mode 100644
index ef1602eb396..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CleanProperties.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The clean properties transform should not be necessary.
- * Eventually we will cleanup the property file sources in the OpenJDK instead.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class CleanProperties implements Transformer {
- public void setExtra(String e) {
- // Any extra information is ignored for clean properties.
- }
-
- public void setExtra(Options a) {
- // Any extra information is ignored for clean properties.
- }
-
- public boolean transform(CompilationService sjavac,
- Map> pkgSrcs,
- Set visibleSrcs,
- Map> oldPackageDependencies,
- URI destRoot,
- Map> packageArtifacts,
- Map>> packageDependencies,
- Map>> packageCpDependencies,
- Map packagePublicApis,
- Map dependencyPublicApis,
- int debugLevel,
- boolean incremental,
- int numCores) {
- boolean rc = true;
- for (String pkgName : pkgSrcs.keySet()) {
- String pkgNameF = pkgName.replace('.',File.separatorChar);
- for (URI u : pkgSrcs.get(pkgName)) {
- File src = new File(u);
- boolean r = clean(pkgName, pkgNameF, src, new File(destRoot), debugLevel,
- packageArtifacts);
- if (r == false) {
- rc = false;
- }
- }
- }
- return rc;
- }
-
- boolean clean(String pkgName,
- String pkgNameF,
- File src,
- File destRoot,
- int debugLevel,
- Map> packageArtifacts) {
- // Load the properties file.
- Properties p = new Properties();
- try {
- p.load(new FileInputStream(src));
- } catch (IOException e) {
- Log.error("Error reading file "+src.getPath());
- return false;
- }
-
- // Sort the properties in increasing key order.
- List sortedKeys = new ArrayList<>();
- for (Object key : p.keySet()) {
- sortedKeys.add((String)key);
- }
- Collections.sort(sortedKeys);
-
- // Collect the properties into a string buffer.
- StringBuilder data = new StringBuilder();
- for (String key : sortedKeys) {
- data.append(CompileProperties.escape(key))
- .append(":")
- .append(CompileProperties.escape((String) p.get(key)))
- .append("\n");
- }
-
- String destFilename = destRoot.getPath()+File.separator+pkgNameF+File.separator+src.getName();
- File dest = new File(destFilename);
-
- // Make sure the dest directories exist.
- if (!dest.getParentFile().isDirectory()) {
- if (!dest.getParentFile().mkdirs()) {
- Log.error("Could not create the directory "+dest.getParentFile().getPath());
- return false;
- }
- }
-
- Set as = packageArtifacts.get(pkgName);
- if (as == null) {
- as = new HashSet<>();
- packageArtifacts.put(pkgName, as);
- }
- as.add(dest.toURI());
-
- if (dest.exists() && dest.lastModified() > src.lastModified()) {
- // A cleaned property file exists, and its timestamp is newer than the source.
- // Assume that we do not need to clean!
- // Thus we are done.
- return true;
- }
-
- Log.info("Cleaning property file "+pkgNameF+File.separator+src.getName());
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)))) {
- writer.write(data.toString());
- } catch ( IOException e ) {
- Log.error("Could not write file "+dest.getPath());
- return false;
- }
- return true;
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileChunk.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileChunk.java
deleted file mode 100644
index d8db6b05bbc..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileChunk.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.net.URI;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * A compile chunk is a list of sources/packages to be compiled. Possibly a subset of
- * the total number of sources/packages to be compiled for this sjavac invocation.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class CompileChunk implements Comparable {
- public int numPackages;
- public int numDependents;
- public Set srcs = new HashSet<>();
- public StringBuilder pkgNames = new StringBuilder();
- public String pkgFromTos = "";
-
- public int compareTo(CompileChunk c) {
- if (numDependents == c.numDependents) return 0;
- if (numDependents > c.numDependents) return -1;
- return -1;
- }
-
- boolean equal(CompileChunk c) {
- return numDependents == c.numDependents;
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileJavaPackages.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileJavaPackages.java
deleted file mode 100644
index 9da65c566a2..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileJavaPackages.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-import com.sun.tools.sjavac.server.CompilationSubResult;
-import com.sun.tools.sjavac.server.SysInfo;
-
-/**
- * This transform compiles a set of packages containing Java sources.
- * The compile request is divided into separate sets of source files.
- * For each set a separate request thread is dispatched to a javac server
- * and the meta data is accumulated. The number of sets correspond more or
- * less to the number of cores. Less so now, than it will in the future.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own
- * risk. This code and its internal interfaces are subject to change
- * or deletion without notice.
- */
-public class CompileJavaPackages implements Transformer {
-
- // The current limited sharing of data between concurrent JavaCompilers
- // in the server will not give speedups above 3 cores. Thus this limit.
- // We hope to improve this in the future.
- static final int limitOnConcurrency = 3;
-
- Options args;
-
- public void setExtra(String e) {
- }
-
- public void setExtra(Options a) {
- args = a;
- }
-
- public boolean transform(final CompilationService sjavac,
- Map> pkgSrcs,
- final Set visibleSources,
- Map> oldPackageDependents,
- URI destRoot,
- final Map> packageArtifacts,
- final Map>> packageDependencies,
- final Map>> packageCpDependencies,
- final Map packagePubapis,
- final Map dependencyPubapis,
- int debugLevel,
- boolean incremental,
- int numCores) {
-
- Log.debug("Performing CompileJavaPackages transform...");
-
- boolean rc = true;
- boolean concurrentCompiles = true;
-
- // Fetch the id.
- final String id = String.valueOf(new Random().nextInt());
- // Only keep portfile and sjavac settings..
- //String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), sjavac.serverSettings());
-
- SysInfo sysinfo = sjavac.getSysInfo();
- int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024)));
- Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores");
-
- if (numCores <= 0) {
- // Set the requested number of cores to the number of cores on the server.
- numCores = sysinfo.numCores;
- Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores);
- } else if (sysinfo.numCores < numCores) {
- // Set the requested number of cores to the number of cores on the server.
- Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores);
- numCores = sysinfo.numCores;
- } else {
- Log.debug("Number of jobs explicitly set to "+numCores);
- }
- // More than three concurrent cores does not currently give a speedup, at least for compiling the jdk
- // in the OpenJDK. This will change in the future.
- int numCompiles = numCores;
- if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency;
- // Split the work up in chunks to compiled.
-
- int numSources = 0;
- for (String s : pkgSrcs.keySet()) {
- Set ss = pkgSrcs.get(s);
- numSources += ss.size();
- }
-
- int sourcesPerCompile = numSources / numCompiles;
-
- // For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap
- // in a single chunk, with reasonable performance.
- // For 32 bit java, it seems we need 1G of heap.
- // Number experimentally determined when compiling the OpenJDK.
- // Includes space for reasonably efficient garbage collection etc,
- // Calculating backwards gives us a requirement of
- // 1500M/8800 = 175 KiB for 64 bit platforms
- // and 1G/8800 = 119 KiB for 32 bit platform
- // for each compile.....
- int kbPerFile = 175;
- String osarch = System.getProperty("os.arch");
- String dataModel = System.getProperty("sun.arch.data.model");
- if ("32".equals(dataModel)) {
- // For 32 bit platforms, assume it is slightly smaller
- // because of smaller object headers and pointers.
- kbPerFile = 119;
- }
- int numRequiredMBytes = (kbPerFile*numSources)/1024;
- Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");
- Log.debug("Server has "+numMBytes+"MiB of heap.");
- Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");
- // Perform heuristics to see how many cores we can use,
- // or if we have to the work serially in smaller chunks.
- if (numMBytes < numRequiredMBytes) {
- // Ouch, cannot fit even a single compile into the heap.
- // Split it up into several serial chunks.
- concurrentCompiles = false;
- // Limit the number of sources for each compile to 500.
- if (numSources < 500) {
- numCompiles = 1;
- sourcesPerCompile = numSources;
- Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");
- } else if (sourcesPerCompile > 500) {
- // This number is very low, and tuned to dealing with the OpenJDK
- // where the source is >very< circular! In normal application,
- // with less circularity the number could perhaps be increased.
- numCompiles = numSources / 500;
- sourcesPerCompile = numSources/numCompiles;
- Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");
- }
- } else {
- if (numCompiles > 1) {
- // Ok, we can fit at least one full compilation on the heap.
- float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);
- int usage = (int)(usagePerCompile * (float)numCompiles);
- Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");
- if (usage > numMBytes) {
- // Ouch it does not fit. Reduce to a single chunk.
- numCompiles = 1;
- sourcesPerCompile = numSources;
- // What if the relationship between number of compile_chunks and num_required_mbytes
- // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is
- // something to experiment upon in the future.
- Log.debug("Limiting compile to a single thread to stay within heap size limitations!");
- }
- }
- }
-
- Log.debug("Compiling sources in "+numCompiles+" chunk(s)");
-
- // Create the chunks to be compiled.
- final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,
- numCompiles, sourcesPerCompile);
-
- if (Log.isDebugging()) {
- int cn = 1;
- for (CompileChunk cc : compileChunks) {
- Log.debug("Chunk "+cn+" for "+id+" ---------------");
- cn++;
- for (URI u : cc.srcs) {
- Log.debug(""+u);
- }
- }
- }
-
- long start = System.currentTimeMillis();
-
- // Prepare compilation calls
- List> compilationCalls = new ArrayList<>();
- final Object lock = new Object();
- for (int i = 0; i < numCompiles; i++) {
- CompileChunk cc = compileChunks[i];
- if (cc.srcs.isEmpty()) {
- continue;
- }
-
- String chunkId = id + "-" + String.valueOf(i);
- Log log = Log.get();
- compilationCalls.add(() -> {
- Log.setLogForCurrentThread(log);
- CompilationSubResult result = sjavac.compile("n/a",
- chunkId,
- args.prepJavacArgs(),
- Collections.emptyList(),
- cc.srcs,
- visibleSources);
- synchronized (lock) {
- Util.getLines(result.stdout).forEach(Log::info);
- Util.getLines(result.stderr).forEach(Log::error);
- }
- return result;
- });
- }
-
- // Perform compilations and collect results
- List subResults = new ArrayList<>();
- List> futs = new ArrayList<>();
- ExecutorService exec = Executors.newFixedThreadPool(concurrentCompiles ? compilationCalls.size() : 1);
- for (Callable compilationCall : compilationCalls) {
- futs.add(exec.submit(compilationCall));
- }
- for (Future fut : futs) {
- try {
- subResults.add(fut.get());
- } catch (ExecutionException ee) {
- Log.error("Compilation failed: " + ee.getMessage());
- Log.error(ee);
- } catch (InterruptedException ie) {
- Log.error("Compilation interrupted: " + ie.getMessage());
- Log.error(ie);
- Thread.currentThread().interrupt();
- }
- }
- exec.shutdownNow();
-
- // Process each sub result
- for (CompilationSubResult subResult : subResults) {
- for (String pkg : subResult.packageArtifacts.keySet()) {
- Set pkgArtifacts = subResult.packageArtifacts.get(pkg);
- packageArtifacts.merge(pkg, pkgArtifacts, Util::union);
- }
-
- for (String pkg : subResult.packageDependencies.keySet()) {
- packageDependencies.putIfAbsent(pkg, new HashMap<>());
- packageDependencies.get(pkg).putAll(subResult.packageDependencies.get(pkg));
- }
-
- for (String pkg : subResult.packageCpDependencies.keySet()) {
- packageCpDependencies.putIfAbsent(pkg, new HashMap<>());
- packageCpDependencies.get(pkg).putAll(subResult.packageCpDependencies.get(pkg));
- }
-
- for (String pkg : subResult.packagePubapis.keySet()) {
- packagePubapis.merge(pkg, subResult.packagePubapis.get(pkg), PubApi::mergeTypes);
- }
-
- for (String pkg : subResult.dependencyPubapis.keySet()) {
- dependencyPubapis.merge(pkg, subResult.dependencyPubapis.get(pkg), PubApi::mergeTypes);
- }
-
- // Check the return values.
- if (subResult.result != Result.OK) {
- rc = false;
- }
- }
-
- long duration = System.currentTimeMillis() - start;
- long minutes = duration/60000;
- long seconds = (duration-minutes*60000)/1000;
- Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");
-
- return rc;
- }
-
- /**
- * Split up the sources into compile chunks. If old package dependents information
- * is available, sort the order of the chunks into the most dependent first!
- * (Typically that chunk contains the java.lang package.) In the future
- * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
- * Now the package are simple sorted in alphabetical order and chunked, then the chunks
- * are sorted on how dependent they are.
- *
- * @param pkgSrcs The sources to compile.
- * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
- * @param numCompiles The number of chunks.
- * @param sourcesPerCompile The number of sources per chunk.
- * @return
- */
- CompileChunk[] createCompileChunks(Map> pkgSrcs,
- Map> oldPackageDependents,
- int numCompiles,
- int sourcesPerCompile) {
-
- CompileChunk[] compileChunks = new CompileChunk[numCompiles];
- for (int i=0; i s = pkgSrcs.get(pkgName);
- if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
- from = null;
- ci++;
- cc = compileChunks[ci];
- }
- cc.numPackages++;
- cc.srcs.addAll(s);
-
- // Calculate nice package names to use as information when compiling.
- String justPkgName = Util.justPackageName(pkgName);
- // Fetch how many packages depend on this package from the old build state.
- Set ss = oldPackageDependents.get(pkgName);
- if (ss != null) {
- // Accumulate this information onto this chunk.
- cc.numDependents += ss.size();
- }
- if (from == null || from.trim().equals("")) from = justPkgName;
- cc.pkgNames.append(justPkgName+"("+s.size()+") ");
- cc.pkgFromTos = from+" to "+justPkgName;
- }
- // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
- // containing java.lang.Object, is to be compiled first!
- // For concurrent compilation, this does not matter.
- Arrays.sort(compileChunks);
- return compileChunks;
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileProperties.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileProperties.java
deleted file mode 100644
index 7045bc14afd..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileProperties.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PrintStream;
-import java.io.Writer;
-import java.net.URI;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * Compile properties transform a properties file into a Java source file.
- * Java has built in support for reading properties from either a text file
- * in the source or a compiled java source file.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class CompileProperties implements Transformer {
- // Any extra information passed from the command line, for example if:
- // -tr .proppp=com.sun.tools.javac.smart.CompileProperties,sun.util.resources.LocaleNamesBundle
- // then extra will be "sun.util.resources.LocaleNamesBundle"
- String extra;
-
- public void setExtra(String e) {
- extra = e;
- }
-
- public void setExtra(Options a) {
- }
-
- public boolean transform(CompilationService compilationService,
- Map> pkgSrcs,
- Set visibleSrcs,
- Map> oldPackageDependents,
- URI destRoot,
- Map> packageArtifacts,
- Map>> packageDependencies,
- Map>> packageCpDependencies,
- Map packagePublicApis,
- Map dependencyPublicApis,
- int debugLevel,
- boolean incremental,
- int numCores) {
- boolean rc = true;
- for (String pkgName : pkgSrcs.keySet()) {
- String pkgNameF = Util.toFileSystemPath(pkgName);
- for (URI u : pkgSrcs.get(pkgName)) {
- File src = new File(u);
- boolean r = compile(pkgName, pkgNameF, src, new File(destRoot), debugLevel,
- packageArtifacts);
- if (r == false) {
- rc = false;
- }
- }
- }
- return rc;
- }
-
- boolean compile(String pkgName, String pkgNameF, File src, File destRoot, int debugLevel,
- Map> packageArtifacts)
- {
- String superClass = "java.util.ListResourceBundle";
-
- if (extra != null) {
- superClass = extra;
- }
- // Load the properties file.
- Properties p = new Properties();
- try {
- p.load(new FileInputStream(src));
- } catch (IOException e) {
- Log.error("Error reading file "+src.getPath());
- return false;
- }
-
- // Calculate the name of the Java source file to be generated.
- int dp = src.getName().lastIndexOf(".");
- String classname = src.getName().substring(0,dp);
-
- // Sort the properties in increasing key order.
- List sortedKeys = new ArrayList<>();
- for (Object key : p.keySet()) {
- sortedKeys.add((String)key);
- }
- Collections.sort(sortedKeys);
- Iterator keys = sortedKeys.iterator();
-
- // Collect the properties into a string buffer.
- StringBuilder data = new StringBuilder();
- while (keys.hasNext()) {
- String key = keys.next();
- data.append(" { \"" + escape(key) + "\", \"" +
- escape((String)p.get(key)) + "\" },\n");
- }
-
- // Create dest file name. It is derived from the properties file name.
- String destFilename = destRoot.getPath()+File.separator+pkgNameF+File.separator+classname+".java";
- File dest = new File(destFilename);
-
- // Make sure the dest directories exist.
- if (!dest.getParentFile().isDirectory()) {
- if (!dest.getParentFile().mkdirs()) {
- Log.error("Could not create the directory "+dest.getParentFile().getPath());
- return false;
- }
- }
-
- Set as = packageArtifacts.get(pkgName);
- if (as == null) {
- as = new HashSet<>();
- packageArtifacts.put(pkgName, as);
- }
- as.add(dest.toURI());
-
- if (dest.exists() && dest.lastModified() > src.lastModified()) {
- // A generated file exists, and its timestamp is newer than the source.
- // Assume that we do not need to regenerate the dest file!
- // Thus we are done.
- return true;
- }
-
- String packageString = "package " + pkgNameF.replace(File.separatorChar,'.') + ";\n\n";
-
- Log.info("Compiling property file "+pkgNameF+File.separator+src.getName());
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)))) {
- MessageFormat format = new MessageFormat(FORMAT);
- writer.write(format.format(new Object[] { packageString, classname, superClass, data }));
- } catch ( IOException e ) {
- Log.error("Could not write file "+dest.getPath());
- return false;
- }
- return true;
- }
-
- private static final String FORMAT =
- "{0}" +
- "public final class {1} extends {2} '{'\n" +
- " protected final Object[][] getContents() '{'\n" +
- " return new Object[][] '{'\n" +
- "{3}" +
- " };\n" +
- " }\n" +
- "}\n";
-
- public static String escape(String theString) {
- int len = theString.length();
- StringBuilder outBuffer = new StringBuilder(len*2);
-
- for(int x=0; x 0x007e)) {
- outBuffer.append('\\');
- outBuffer.append('u');
- outBuffer.append(toHex((aChar >> 12) & 0xF));
- outBuffer.append(toHex((aChar >> 8) & 0xF));
- outBuffer.append(toHex((aChar >> 4) & 0xF));
- outBuffer.append(toHex( aChar & 0xF));
- } else {
- if (aChar == '"') {
- outBuffer.append('\\');
- }
- outBuffer.append(aChar);
- }
- }
- }
- return outBuffer.toString();
- }
-
- private static char toHex(int nibble) {
- return hexDigit[(nibble & 0xF)];
- }
-
- private static final char[] hexDigit = {
- '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
- };
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CopyFile.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CopyFile.java
deleted file mode 100644
index 805ea85d32b..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CopyFile.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.nio.file.Files;
-import java.nio.file.StandardCopyOption;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The copy file transform simply copies a matching file from -src to -d .
- * Such files are typically images, xml documents and other data files.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class CopyFile implements Transformer {
-
- public void setExtra(String e) {
- }
-
- public void setExtra(Options a) {
- }
-
- public boolean transform(CompilationService compilationService,
- Map> pkgSrcs,
- Set visibleSrcs,
- Map> oldPackageDependents,
- URI destRoot,
- Map> packageArtifacts,
- Map>> packageDependencies,
- Map>> packageCpDependencies,
- Map packagePubapis,
- Map dependencyPubapis,
- int debugLevel,
- boolean incremental,
- int numCores)
- {
- boolean rc = true;
- String dest_filename;
- File dest;
-
- for (String pkgName : pkgSrcs.keySet()) {
- String pkgNameF = Util.toFileSystemPath(pkgName);
- for (URI u : pkgSrcs.get(pkgName)) {
- File src = new File(u);
- File destDir;
- destDir = new File(destRoot.getPath()+File.separator+pkgNameF);
- dest_filename = destRoot.getPath()+File.separator+pkgNameF+File.separator+src.getName();
- dest = new File(dest_filename);
-
- if (!destDir.isDirectory()) {
- if (!destDir.mkdirs()) {
- Log.error("Error: The copier could not create the directory "+
- destDir.getPath());
- return false;
- }
- }
-
- Set as = packageArtifacts.get(pkgName);
- if (as == null) {
- as = new HashSet<>();
- packageArtifacts.put(pkgName, as);
- }
- as.add(dest.toURI());
-
- if (dest.exists() && dest.lastModified() > src.lastModified()) {
- // A copied file exists, and its timestamp is newer than the source.
- continue;
- }
-
- Log.info("Copying "+pkgNameF+File.separator+src.getName());
-
- try {
- Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
- }
- catch(IOException e){
- Log.error("Could not copy the file "+src.getPath()+" to "+dest.getPath());
- rc = false;
- }
- }
- }
- return rc;
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/JavacState.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/JavacState.java
deleted file mode 100644
index 410767a5c07..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/JavacState.java
+++ /dev/null
@@ -1,974 +0,0 @@
-/*
- * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.Writer;
-import java.net.URI;
-import java.nio.file.NoSuchFileException;
-import java.text.SimpleDateFormat;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The javac state class maintains the previous (prev) and the current (now)
- * build states and everything else that goes into the javac_state file.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class JavacState {
- // The arguments to the compile. If not identical, then it cannot
- // be an incremental build!
- String theArgs;
- // The number of cores limits how many threads are used for heavy concurrent work.
- int numCores;
-
- // The bin_dir/javac_state
- private File javacState;
-
- // The previous build state is loaded from javac_state
- private BuildState prev;
- // The current build state is constructed during the build,
- // then saved as the new javac_state.
- private BuildState now;
-
- // Something has changed in the javac_state. It needs to be saved!
- private boolean needsSaving;
- // If this is a new javac_state file, then do not print unnecessary messages.
- private boolean newJavacState;
-
- // These are packages where something has changed and the package
- // needs to be recompiled. Actions that trigger recompilation:
- // * source belonging to the package has changed
- // * artifact belonging to the package is lost, or its timestamp has been changed.
- // * an unknown artifact has appeared, we simply delete it, but we also trigger a recompilation.
- // * a package that is tainted, taints all packages that depend on it.
- private Set taintedPackages;
- // After a compile, the pubapis are compared with the pubapis stored in the javac state file.
- // Any packages where the pubapi differ are added to this set.
- // Later we use this set and the dependency information to taint dependent packages.
- private Set packagesWithChangedPublicApis;
- // When a module-info.java file is changed, taint the module,
- // then taint all modules that depend on that that module.
- // A module dependency can occur directly through a require, or
- // indirectly through a module that does a public export for the first tainted module.
- // When all modules are tainted, then taint all packages belonging to these modules.
- // Then rebuild. It is perhaps possible (and valuable?) to do a more fine-grained examination of the
- // change in module-info.java, but that will have to wait.
- private Set taintedModules;
- // The set of all packages that has been recompiled.
- // Copy over the javac_state for the packages that did not need recompilation,
- // verbatim from the previous (prev) to the new (now) build state.
- private Set recompiledPackages;
-
- // The output directories filled with tasty artifacts.
- private File binDir, gensrcDir, headerDir, stateDir;
-
- // The current status of the file system.
- private Set binArtifacts;
- private Set gensrcArtifacts;
- private Set headerArtifacts;
-
- // The status of the sources.
- Set removedSources = null;
- Set addedSources = null;
- Set modifiedSources = null;
-
- // Visible sources for linking. These are the only
- // ones that -sourcepath is allowed to see.
- Set visibleSrcs;
-
- // Setup transform that always exist.
- private CompileJavaPackages compileJavaPackages = new CompileJavaPackages();
-
- // Command line options.
- private Options options;
-
- JavacState(Options op, boolean removeJavacState) {
- options = op;
- numCores = options.getNumCores();
- theArgs = options.getStateArgsString();
- binDir = Util.pathToFile(options.getDestDir());
- gensrcDir = Util.pathToFile(options.getGenSrcDir());
- headerDir = Util.pathToFile(options.getHeaderDir());
- stateDir = Util.pathToFile(options.getStateDir());
- javacState = new File(stateDir, "javac_state");
- if (removeJavacState && javacState.exists()) {
- javacState.delete();
- }
- newJavacState = false;
- if (!javacState.exists()) {
- newJavacState = true;
- // If there is no javac_state then delete the contents of all the artifact dirs!
- // We do not want to risk building a broken incremental build.
- // BUT since the makefiles still copy things straight into the bin_dir et al,
- // we avoid deleting files here, if the option --permit-unidentified-classes was supplied.
- if (!options.areUnidentifiedArtifactsPermitted()) {
- deleteContents(binDir);
- deleteContents(gensrcDir);
- deleteContents(headerDir);
- }
- needsSaving = true;
- }
- prev = new BuildState();
- now = new BuildState();
- taintedPackages = new HashSet<>();
- recompiledPackages = new HashSet<>();
- packagesWithChangedPublicApis = new HashSet<>();
- }
-
- public BuildState prev() { return prev; }
- public BuildState now() { return now; }
-
- /**
- * Remove args not affecting the state.
- */
- static String[] removeArgsNotAffectingState(String[] args) {
- String[] out = new String[args.length];
- int j = 0;
- for (int i = 0; i vs) {
- visibleSrcs = new HashSet<>();
- for (String s : vs.keySet()) {
- Source src = vs.get(s);
- visibleSrcs.add(src.file().toURI());
- }
- }
-
- /**
- * Returns true if this is an incremental build.
- */
- public boolean isIncremental() {
- return !prev.sources().isEmpty();
- }
-
- /**
- * Find all artifacts that exists on disk.
- */
- public void findAllArtifacts() {
- binArtifacts = findAllFiles(binDir);
- gensrcArtifacts = findAllFiles(gensrcDir);
- headerArtifacts = findAllFiles(headerDir);
- }
-
- /**
- * Lookup the artifacts generated for this package in the previous build.
- */
- private Map fetchPrevArtifacts(String pkg) {
- Package p = prev.packages().get(pkg);
- if (p != null) {
- return p.artifacts();
- }
- return new HashMap<>();
- }
-
- /**
- * Delete all prev artifacts in the currently tainted packages.
- */
- public void deleteClassArtifactsInTaintedPackages() {
- for (String pkg : taintedPackages) {
- Map arts = fetchPrevArtifacts(pkg);
- for (File f : arts.values()) {
- if (f.exists() && f.getName().endsWith(".class")) {
- f.delete();
- }
- }
- }
- }
-
- /**
- * Mark the javac_state file to be in need of saving and as a side effect,
- * it gets a new timestamp.
- */
- private void needsSaving() {
- needsSaving = true;
- }
-
- /**
- * Save the javac_state file.
- */
- public void save() throws IOException {
- if (!needsSaving)
- return;
- try (FileWriter out = new FileWriter(javacState)) {
- StringBuilder b = new StringBuilder();
- long millisNow = System.currentTimeMillis();
- Date d = new Date(millisNow);
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
- b.append("# javac_state ver 0.4 generated "+millisNow+" "+df.format(d)+"\n");
- b.append("# This format might change at any time. Please do not depend on it.\n");
- b.append("# R arguments\n");
- b.append("# M module\n");
- b.append("# P package\n");
- b.append("# S C source_tobe_compiled timestamp\n");
- b.append("# S L link_only_source timestamp\n");
- b.append("# G C generated_source timestamp\n");
- b.append("# A artifact timestamp\n");
- b.append("# D S dependent -> source dependency\n");
- b.append("# D C dependent -> classpath dependency\n");
- b.append("# I pubapi\n");
- b.append("R ").append(theArgs).append("\n");
-
- // Copy over the javac_state for the packages that did not need recompilation.
- now.copyPackagesExcept(prev, recompiledPackages, new HashSet());
- // Save the packages, ie package names, dependencies, pubapis and artifacts!
- // I.e. the lot.
- Module.saveModules(now.modules(), b);
-
- String s = b.toString();
- out.write(s, 0, s.length());
- }
- }
-
- /**
- * Load a javac_state file.
- */
- public static JavacState load(Options options) {
- JavacState db = new JavacState(options, false);
- Module lastModule = null;
- Package lastPackage = null;
- Source lastSource = null;
- boolean noFileFound = false;
- boolean foundCorrectVerNr = false;
- boolean newCommandLine = false;
- boolean syntaxError = false;
-
- Log.debug("Loading javac state file: " + db.javacState);
-
- try (BufferedReader in = new BufferedReader(new FileReader(db.javacState))) {
- for (;;) {
- String l = in.readLine();
- if (l==null) break;
- if (l.length()>=3 && l.charAt(1) == ' ') {
- char c = l.charAt(0);
- if (c == 'M') {
- lastModule = db.prev.loadModule(l);
- } else
- if (c == 'P') {
- if (lastModule == null) { syntaxError = true; break; }
- lastPackage = db.prev.loadPackage(lastModule, l);
- } else
- if (c == 'D') {
- if (lastModule == null || lastPackage == null) { syntaxError = true; break; }
- char depType = l.charAt(2);
- if (depType != 'S' && depType != 'C')
- throw new RuntimeException("Bad dependency string: " + l);
- lastPackage.parseAndAddDependency(l.substring(4), depType == 'C');
- } else
- if (c == 'I') {
- if (lastModule == null || lastPackage == null) { syntaxError = true; break; }
- lastPackage.getPubApi().appendItem(l.substring(2)); // Strip "I "
- } else
- if (c == 'A') {
- if (lastModule == null || lastPackage == null) { syntaxError = true; break; }
- lastPackage.loadArtifact(l);
- } else
- if (c == 'S') {
- if (lastModule == null || lastPackage == null) { syntaxError = true; break; }
- lastSource = db.prev.loadSource(lastPackage, l, false);
- } else
- if (c == 'G') {
- if (lastModule == null || lastPackage == null) { syntaxError = true; break; }
- lastSource = db.prev.loadSource(lastPackage, l, true);
- } else
- if (c == 'R') {
- String ncmdl = "R "+db.theArgs;
- if (!l.equals(ncmdl)) {
- newCommandLine = true;
- }
- } else
- if (c == '#') {
- if (l.startsWith("# javac_state ver ")) {
- int sp = l.indexOf(" ", 18);
- if (sp != -1) {
- String ver = l.substring(18,sp);
- if (!ver.equals("0.4")) {
- break;
- }
- foundCorrectVerNr = true;
- }
- }
- }
- }
- }
- } catch (FileNotFoundException | NoSuchFileException e) {
- // Silently create a new javac_state file.
- noFileFound = true;
- } catch (IOException e) {
- Log.warn("Dropping old javac_state because of errors when reading it.");
- db = new JavacState(options, true);
- foundCorrectVerNr = true;
- newCommandLine = false;
- syntaxError = false;
- }
- if (foundCorrectVerNr == false && !noFileFound) {
- Log.debug("Dropping old javac_state since it is of an old version.");
- db = new JavacState(options, true);
- } else
- if (newCommandLine == true && !noFileFound) {
- Log.debug("Dropping old javac_state since a new command line is used!");
- db = new JavacState(options, true);
- } else
- if (syntaxError == true) {
- Log.warn("Dropping old javac_state since it contains syntax errors.");
- db = new JavacState(options, true);
- }
- db.prev.calculateDependents();
- return db;
- }
-
- /**
- * Mark a java package as tainted, ie it needs recompilation.
- */
- public void taintPackage(String name, String because) {
- if (!taintedPackages.contains(name)) {
- if (because != null) Log.debug("Tainting "+Util.justPackageName(name)+" because "+because);
- // It has not been tainted before.
- taintedPackages.add(name);
- needsSaving();
- Package nowp = now.packages().get(name);
- if (nowp != null) {
- for (String d : nowp.dependents()) {
- taintPackage(d, because);
- }
- }
- }
- }
-
- /**
- * This packages need recompilation.
- */
- public Set taintedPackages() {
- return taintedPackages;
- }
-
- /**
- * Clean out the tainted package set, used after the first round of compiles,
- * prior to propagating dependencies.
- */
- public void clearTaintedPackages() {
- taintedPackages = new HashSet<>();
- }
-
- /**
- * Go through all sources and check which have been removed, added or modified
- * and taint the corresponding packages.
- */
- public void checkSourceStatus(boolean check_gensrc) {
- removedSources = calculateRemovedSources();
- for (Source s : removedSources) {
- if (!s.isGenerated() || check_gensrc) {
- taintPackage(s.pkg().name(), "source "+s.name()+" was removed");
- }
- }
-
- addedSources = calculateAddedSources();
- for (Source s : addedSources) {
- String msg = null;
- if (isIncremental()) {
- // When building from scratch, there is no point
- // printing "was added" for every file since all files are added.
- // However for an incremental build it makes sense.
- msg = "source "+s.name()+" was added";
- }
- if (!s.isGenerated() || check_gensrc) {
- taintPackage(s.pkg().name(), msg);
- }
- }
-
- modifiedSources = calculateModifiedSources();
- for (Source s : modifiedSources) {
- if (!s.isGenerated() || check_gensrc) {
- taintPackage(s.pkg().name(), "source "+s.name()+" was modified");
- }
- }
- }
-
- /**
- * Acquire the compile_java_packages suffix rule for .java files.
- */
- public Map getJavaSuffixRule() {
- Map sr = new HashMap<>();
- sr.put(".java", compileJavaPackages);
- return sr;
- }
-
-
- /**
- * If artifacts have gone missing, force a recompile of the packages
- * they belong to.
- */
- public void taintPackagesThatMissArtifacts() {
- for (Package pkg : prev.packages().values()) {
- for (File f : pkg.artifacts().values()) {
- if (!f.exists()) {
- // Hmm, the artifact on disk does not exist! Someone has removed it....
- // Lets rebuild the package.
- taintPackage(pkg.name(), ""+f+" is missing.");
- }
- }
- }
- }
-
- /**
- * Propagate recompilation through the dependency chains.
- * Avoid re-tainting packages that have already been compiled.
- */
- public void taintPackagesDependingOnChangedPackages(Set pkgsWithChangedPubApi, Set recentlyCompiled) {
- // For each to-be-recompiled-candidates...
- for (Package pkg : new HashSet<>(prev.packages().values())) {
- // Find out what it depends upon...
- Set deps = pkg.typeDependencies()
- .values()
- .stream()
- .flatMap(Collection::stream)
- .collect(Collectors.toSet());
- for (String dep : deps) {
- String depPkg = ":" + dep.substring(0, dep.lastIndexOf('.'));
- if (depPkg.equals(pkg.name()))
- continue;
- // Checking if that dependency has changed
- if (pkgsWithChangedPubApi.contains(depPkg) && !recentlyCompiled.contains(pkg.name())) {
- taintPackage(pkg.name(), "its depending on " + depPkg);
- }
- }
- }
- }
-
- /**
- * Compare the javac_state recorded public apis of packages on the classpath
- * with the actual public apis on the classpath.
- */
- public void taintPackagesDependingOnChangedClasspathPackages() throws IOException {
-
- // 1. Collect fully qualified names of all interesting classpath dependencies
- Set fqDependencies = new HashSet<>();
- for (Package pkg : prev.packages().values()) {
- // Check if this package was compiled. If it's presence is recorded
- // because it was on the class path and we needed to save it's
- // public api, it's not a candidate for tainting.
- if (pkg.sources().isEmpty())
- continue;
-
- pkg.typeClasspathDependencies().values().forEach(fqDependencies::addAll);
- }
-
- // 2. Extract the public APIs from the on disk .class files
- // (Reason for doing step 1 in a separate phase is to avoid extracting
- // public APIs of the same class twice.)
- PubApiExtractor pubApiExtractor = new PubApiExtractor(options);
- Map onDiskPubApi = new HashMap<>();
- for (String cpDep : fqDependencies) {
- onDiskPubApi.put(cpDep, pubApiExtractor.getPubApi(cpDep));
- }
- pubApiExtractor.close();
-
- // 3. Compare them with the public APIs as of last compilation (loaded from javac_state)
- nextPkg:
- for (Package pkg : prev.packages().values()) {
- // Check if this package was compiled. If it's presence is recorded
- // because it was on the class path and we needed to save it's
- // public api, it's not a candidate for tainting.
- if (pkg.sources().isEmpty())
- continue;
-
- Set cpDepsOfThisPkg = new HashSet<>();
- for (Set cpDeps : pkg.typeClasspathDependencies().values())
- cpDepsOfThisPkg.addAll(cpDeps);
-
- for (String fqDep : cpDepsOfThisPkg) {
-
- String depPkg = ":" + fqDep.substring(0, fqDep.lastIndexOf('.'));
- PubApi prevPkgApi = prev.packages().get(depPkg).getPubApi();
-
- // This PubApi directly lists the members of the class,
- // i.e. [ MEMBER1, MEMBER2, ... ]
- PubApi prevDepApi = prevPkgApi.types.get(fqDep).pubApi;
-
- // In order to dive *into* the class, we need to add
- // .types.get(fqDep).pubApi below.
- PubApi currentDepApi = onDiskPubApi.get(fqDep).types.get(fqDep).pubApi;
-
- if (!currentDepApi.isBackwardCompatibleWith(prevDepApi)) {
- List apiDiff = currentDepApi.diff(prevDepApi);
- taintPackage(pkg.name(), "depends on classpath "
- + "package which has an updated package api: "
- + String.join("\n", apiDiff));
- //Log.debug("========================================");
- //Log.debug("------ PREV API ------------------------");
- //prevDepApi.asListOfStrings().forEach(Log::debug);
- //Log.debug("------ CURRENT API ---------------------");
- //currentDepApi.asListOfStrings().forEach(Log::debug);
- //Log.debug("========================================");
- continue nextPkg;
- }
- }
- }
- }
-
- /**
- * Scan all output dirs for artifacts and remove those files (artifacts?)
- * that are not recognized as such, in the javac_state file.
- */
- public void removeUnidentifiedArtifacts() {
- Set allKnownArtifacts = new HashSet<>();
- for (Package pkg : prev.packages().values()) {
- for (File f : pkg.artifacts().values()) {
- allKnownArtifacts.add(f);
- }
- }
- // Do not forget about javac_state....
- allKnownArtifacts.add(javacState);
-
- for (File f : binArtifacts) {
- if (!allKnownArtifacts.contains(f) &&
- !options.isUnidentifiedArtifactPermitted(f.getAbsolutePath())) {
- Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");
- f.delete();
- }
- }
- for (File f : headerArtifacts) {
- if (!allKnownArtifacts.contains(f)) {
- Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");
- f.delete();
- }
- }
- for (File f : gensrcArtifacts) {
- if (!allKnownArtifacts.contains(f)) {
- Log.debug("Removing "+f.getPath()+" since it is unknown to the javac_state.");
- f.delete();
- }
- }
- }
-
- /**
- * Remove artifacts that are no longer produced when compiling!
- */
- public void removeSuperfluousArtifacts(Set recentlyCompiled) {
- // Nothing to do, if nothing was recompiled.
- if (recentlyCompiled.size() == 0) return;
-
- for (String pkg : now.packages().keySet()) {
- // If this package has not been recompiled, skip the check.
- if (!recentlyCompiled.contains(pkg)) continue;
- Collection arts = now.artifacts().values();
- for (File f : fetchPrevArtifacts(pkg).values()) {
- if (!arts.contains(f)) {
- Log.debug("Removing "+f.getPath()+" since it is now superfluous!");
- if (f.exists()) f.delete();
- }
- }
- }
- }
-
- /**
- * Return those files belonging to prev, but not now.
- */
- private Set calculateRemovedSources() {
- Set removed = new HashSet<>();
- for (String src : prev.sources().keySet()) {
- if (now.sources().get(src) == null) {
- removed.add(prev.sources().get(src));
- }
- }
- return removed;
- }
-
- /**
- * Return those files belonging to now, but not prev.
- */
- private Set calculateAddedSources() {
- Set added = new HashSet<>();
- for (String src : now.sources().keySet()) {
- if (prev.sources().get(src) == null) {
- added.add(now.sources().get(src));
- }
- }
- return added;
- }
-
- /**
- * Return those files where the timestamp is newer.
- * If a source file timestamp suddenly is older than what is known
- * about it in javac_state, then consider it modified, but print
- * a warning!
- */
- private Set calculateModifiedSources() {
- Set modified = new HashSet<>();
- for (String src : now.sources().keySet()) {
- Source n = now.sources().get(src);
- Source t = prev.sources().get(src);
- if (prev.sources().get(src) != null) {
- if (t != null) {
- if (n.lastModified() > t.lastModified()) {
- modified.add(n);
- } else if (n.lastModified() < t.lastModified()) {
- modified.add(n);
- Log.warn("The source file "+n.name()+" timestamp has moved backwards in time.");
- }
- }
- }
- }
- return modified;
- }
-
- /**
- * Recursively delete a directory and all its contents.
- */
- private void deleteContents(File dir) {
- if (dir != null && dir.exists()) {
- for (File f : dir.listFiles()) {
- if (f.isDirectory()) {
- deleteContents(f);
- }
- if (!options.isUnidentifiedArtifactPermitted(f.getAbsolutePath())) {
- Log.debug("Removing "+f.getAbsolutePath());
- f.delete();
- }
- }
- }
- }
-
- /**
- * Run the copy translator only.
- */
- public void performCopying(File binDir, Map suffixRules) {
- Map sr = new HashMap<>();
- for (Map.Entry e : suffixRules.entrySet()) {
- if (e.getValue().getClass().equals(CopyFile.class)) {
- sr.put(e.getKey(), e.getValue());
- }
- }
- perform(null, binDir, sr);
- }
-
- /**
- * Run all the translators that translate into java source code.
- * I.e. all translators that are not copy nor compile_java_source.
- */
- public void performTranslation(File gensrcDir, Map suffixRules) {
- Map sr = new HashMap<>();
- for (Map.Entry e : suffixRules.entrySet()) {
- Class> trClass = e.getValue().getClass();
- if (trClass == CompileJavaPackages.class || trClass == CopyFile.class)
- continue;
-
- sr.put(e.getKey(), e.getValue());
- }
- perform(null, gensrcDir, sr);
- }
-
- /**
- * Compile all the java sources. Return true, if it needs to be called again!
- */
- public boolean performJavaCompilations(CompilationService sjavac,
- Options args,
- Set recentlyCompiled,
- boolean[] rcValue) {
- Map suffixRules = new HashMap<>();
- suffixRules.put(".java", compileJavaPackages);
- compileJavaPackages.setExtra(args);
- rcValue[0] = perform(sjavac, binDir, suffixRules);
- recentlyCompiled.addAll(taintedPackages());
- clearTaintedPackages();
- boolean again = !packagesWithChangedPublicApis.isEmpty();
- taintPackagesDependingOnChangedPackages(packagesWithChangedPublicApis, recentlyCompiled);
- packagesWithChangedPublicApis = new HashSet<>();
- return again && rcValue[0];
-
- // TODO: Figure out why 'again' checks packagesWithChangedPublicAPis.
- // (It shouldn't matter if packages had changed pub apis as long as no
- // one depends on them. Wouldn't it make more sense to let 'again'
- // depend on taintedPackages?)
- }
-
- /**
- * Store the source into the set of sources belonging to the given transform.
- */
- private void addFileToTransform(Map>> gs, Transformer t, Source s) {
- Map> fs = gs.get(t);
- if (fs == null) {
- fs = new HashMap<>();
- gs.put(t, fs);
- }
- Set ss = fs.get(s.pkg().name());
- if (ss == null) {
- ss = new HashSet<>();
- fs.put(s.pkg().name(), ss);
- }
- ss.add(s.file().toURI());
- }
-
- /**
- * For all packages, find all sources belonging to the package, group the sources
- * based on their transformers and apply the transformers on each source code group.
- */
- private boolean perform(CompilationService sjavac,
- File outputDir,
- Map suffixRules) {
- boolean rc = true;
- // Group sources based on transforms. A source file can only belong to a single transform.
- Map>> groupedSources = new HashMap<>();
- for (Source src : now.sources().values()) {
- Transformer t = suffixRules.get(src.suffix());
- if (t != null) {
- if (taintedPackages.contains(src.pkg().name()) && !src.isLinkedOnly()) {
- addFileToTransform(groupedSources, t, src);
- }
- }
- }
- // Go through the transforms and transform them.
- for (Map.Entry>> e : groupedSources.entrySet()) {
- Transformer t = e.getKey();
- Map> srcs = e.getValue();
- // These maps need to be synchronized since multiple threads will be
- // writing results into them.
- Map> packageArtifacts = Collections.synchronizedMap(new HashMap<>());
- Map>> packageDependencies = Collections.synchronizedMap(new HashMap<>());
- Map>> packageCpDependencies = Collections.synchronizedMap(new HashMap<>());
- Map packagePublicApis = Collections.synchronizedMap(new HashMap<>());
- Map dependencyPublicApis = Collections.synchronizedMap(new HashMap<>());
-
- boolean r = t.transform(sjavac,
- srcs,
- visibleSrcs,
- prev.dependents(),
- outputDir.toURI(),
- packageArtifacts,
- packageDependencies,
- packageCpDependencies,
- packagePublicApis,
- dependencyPublicApis,
- 0,
- isIncremental(),
- numCores);
- if (!r)
- rc = false;
-
- for (String p : srcs.keySet()) {
- recompiledPackages.add(p);
- }
- // The transform is done! Extract all the artifacts and store the info into the Package objects.
- for (Map.Entry> a : packageArtifacts.entrySet()) {
- Module mnow = now.findModuleFromPackageName(a.getKey());
- mnow.addArtifacts(a.getKey(), a.getValue());
- }
- // Extract all the dependencies and store the info into the Package objects.
- for (Map.Entry>> a : packageDependencies.entrySet()) {
- Map> deps = a.getValue();
- Module mnow = now.findModuleFromPackageName(a.getKey());
- mnow.setDependencies(a.getKey(), deps, false);
- }
- for (Map.Entry>> a : packageCpDependencies.entrySet()) {
- Map> deps = a.getValue();
- Module mnow = now.findModuleFromPackageName(a.getKey());
- mnow.setDependencies(a.getKey(), deps, true);
- }
-
- // This map contains the public api of the types that this
- // compilation depended upon. This means that it may not contain
- // full packages. In other words, we shouldn't remove knowledge of
- // public apis but merge these with what we already have.
- for (Map.Entry a : dependencyPublicApis.entrySet()) {
- String pkg = a.getKey();
- PubApi packagePartialPubApi = a.getValue();
- Package pkgNow = now.findModuleFromPackageName(pkg).lookupPackage(pkg);
- PubApi currentPubApi = pkgNow.getPubApi();
- PubApi newPubApi = PubApi.mergeTypes(currentPubApi, packagePartialPubApi);
- pkgNow.setPubapi(newPubApi);
-
- // See JDK-8071904
- if (now.packages().containsKey(pkg))
- now.packages().get(pkg).setPubapi(newPubApi);
- else
- now.packages().put(pkg, pkgNow);
- }
-
- // The packagePublicApis cover entire packages (since sjavac compiles
- // stuff on package level). This means that if a type is missing
- // in the public api of a given package, it means that it has been
- // removed. In other words, we should *set* the pubapi to whatever
- // this map contains, and not merge it with what we already have.
- for (Map.Entry a : packagePublicApis.entrySet()) {
- String pkg = a.getKey();
- PubApi newPubApi = a.getValue();
- Module mprev = prev.findModuleFromPackageName(pkg);
- Module mnow = now.findModuleFromPackageName(pkg);
- mnow.setPubapi(pkg, newPubApi);
- if (mprev.hasPubapiChanged(pkg, newPubApi)) {
- // Aha! The pubapi of this package has changed!
- // It can also be a new compile from scratch.
- if (mprev.lookupPackage(pkg).existsInJavacState()) {
- // This is an incremental compile! The pubapi
- // did change. Trigger recompilation of dependents.
- packagesWithChangedPublicApis.add(pkg);
- Log.debug("The API of " + Util.justPackageName(pkg) + " has changed!");
- }
- }
- }
- }
- return rc;
- }
-
- /**
- * Utility method to recursively find all files below a directory.
- */
- private static Set findAllFiles(File dir) {
- Set foundFiles = new HashSet<>();
- if (dir == null) {
- return foundFiles;
- }
- recurse(dir, foundFiles);
- return foundFiles;
- }
-
- private static void recurse(File dir, Set foundFiles) {
- for (File f : dir.listFiles()) {
- if (f.isFile()) {
- foundFiles.add(f);
- } else if (f.isDirectory()) {
- recurse(f, foundFiles);
- }
- }
- }
-
- /**
- * Compare the calculate source list, with an explicit list, usually
- * supplied from the makefile. Used to detect bugs where the makefile and
- * sjavac have different opinions on which files should be compiled.
- */
- public void compareWithMakefileList(File makefileSourceList)
- throws ProblemException {
- // If we are building on win32 using for example cygwin the paths in the
- // makefile source list
- // might be /cygdrive/c/.... which does not match c:\....
- // We need to adjust our calculated sources to be identical, if
- // necessary.
- boolean mightNeedRewriting = File.pathSeparatorChar == ';';
-
- if (makefileSourceList == null)
- return;
-
- Set calculatedSources = new HashSet<>();
- Set listedSources = new HashSet<>();
-
- // Create a set of filenames with full paths.
- for (Source s : now.sources().values()) {
- // Don't include link only sources when comparing sources to compile
- if (!s.isLinkedOnly()) {
- String path = s.file().getPath();
- if (mightNeedRewriting)
- path = Util.normalizeDriveLetter(path);
- calculatedSources.add(path);
- }
- }
- // Read in the file and create another set of filenames with full paths.
- try(BufferedReader in = new BufferedReader(new FileReader(makefileSourceList))) {
- for (;;) {
- String l = in.readLine();
- if (l==null) break;
- l = l.trim();
- if (mightNeedRewriting) {
- if (l.indexOf(":") == 1 && l.indexOf("\\") == 2) {
- // Everything a-ok, the format is already C:\foo\bar
- } else if (l.indexOf(":") == 1 && l.indexOf("/") == 2) {
- // The format is C:/foo/bar, rewrite into the above format.
- l = l.replaceAll("/","\\\\");
- } else if (l.charAt(0) == '/' && l.indexOf("/",1) != -1) {
- // The format might be: /cygdrive/c/foo/bar, rewrite into the above format.
- // Do not hardcode the name cygdrive here.
- int slash = l.indexOf("/",1);
- l = l.replaceAll("/","\\\\");
- l = ""+l.charAt(slash+1)+":"+l.substring(slash+2);
- }
- if (Character.isLowerCase(l.charAt(0))) {
- l = Character.toUpperCase(l.charAt(0))+l.substring(1);
- }
- }
- listedSources.add(l);
- }
- } catch (FileNotFoundException | NoSuchFileException e) {
- throw new ProblemException("Could not open "+makefileSourceList.getPath()+" since it does not exist!");
- } catch (IOException e) {
- throw new ProblemException("Could not read "+makefileSourceList.getPath());
- }
-
- for (String s : listedSources) {
- if (!calculatedSources.contains(s)) {
- throw new ProblemException("The makefile listed source "+s+" was not calculated by the smart javac wrapper!");
- }
- }
-
- for (String s : calculatedSources) {
- if (!listedSources.contains(s)) {
- throw new ProblemException("The smart javac wrapper calculated source "+s+" was not listed by the makefiles!");
- }
- }
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Module.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Module.java
deleted file mode 100644
index 6def9f433b7..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Module.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The module is the root of a set of packages/sources/artifacts.
- * At the moment there is only one module in use, the empty/no-name/default module.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class Module implements Comparable {
- private String name;
- private String dirname;
- private Map packages = new HashMap<>();
- private Map sources = new HashMap<>();
- private Map artifacts = new HashMap<>();
-
- public Module(String n, String dn) {
- name = n;
- dirname = n;
- }
-
- public String name() { return name; }
- public String dirname() { return dirname; }
- public Map packages() { return packages; }
- public Map sources() { return sources; }
- public Map artifacts() { return artifacts; }
-
- @Override
- public boolean equals(Object o) {
- return (o instanceof Module module) && name.equals(module.name);
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
-
- @Override
- public int compareTo(Module o) {
- return name.compareTo(o.name);
- }
-
- public void save(StringBuilder b) {
- b.append("M ").append(name).append(":").append("\n");
- Package.savePackages(packages, b);
- }
-
- public static Module load(String l) {
- int cp = l.indexOf(':',2);
- if (cp == -1) return null;
- String name = l.substring(2,cp);
- return new Module(name, "");
- }
-
- public static void saveModules(Map ms, StringBuilder b) {
- for (Module m : ms.values()) {
- m.save(b);
- }
- }
-
- public void addPackage(Package p) {
- packages.put(p.name(), p);
- }
-
- public Package lookupPackage(String pkg) {
- // See JDK-8071904
- Package p = packages.get(pkg);
- if (p == null) {
- p = new Package(this, pkg);
- packages.put(pkg, p);
- }
- return p;
- }
-
- public void addSource(String pkg, Source src) {
- Package p = lookupPackage(pkg);
- src.setPackage(p);
- p.addSource(src);
- sources.put(src.file().getPath(), src);
- }
-
- public Source lookupSource(String path) {
- return sources.get(path);
- }
-
- public void addArtifacts(String pkg, Set as) {
- Package p = lookupPackage(pkg);
- for (URI u : as) {
- p.addArtifact(new File(u));
- }
- }
-
- public void setDependencies(String pkg, Map> deps, boolean cp) {
- lookupPackage(pkg).setDependencies(deps, cp);
- }
-
- public void setPubapi(String pkg, PubApi ps) {
- Package p = lookupPackage(pkg);
- p.setPubapi(ps);
- }
-
- public boolean hasPubapiChanged(String pkg, PubApi newPubApi) {
- Package p = lookupPackage(pkg);
- return p.hasPubApiChanged(newPubApi);
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Package.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Package.java
deleted file mode 100644
index f10d1b4fa69..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Package.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-
-import com.sun.tools.javac.util.Assert;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The Package class maintains meta information about a package.
- * For example its sources, dependents, its pubapi and its artifacts.
- *
- * It might look odd that we track dependents/pubapi/artifacts on
- * a package level, but it makes sense since recompiling a full package
- * takes as long as recompiling a single java file in that package,
- * if you take into account the startup time of the jvm.
- *
- * Also the dependency information will be much smaller (good for the javac_state file size)
- * and it simplifies tracking artifact generation, you do not always know from which
- * source a class file was generated, but you always know which package it belongs to.
- *
- * It is also educational to see package dependencies triggering recompilation of
- * other packages. Even though the recompilation was perhaps not necessary,
- * the visible recompilation of the dependent packages indicates how much circular
- * dependencies your code has.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class Package implements Comparable {
- // The module this package belongs to. (There is a legacy module with an empty string name,
- // used for all legacy sources.)
- private Module mod;
- // Name of this package, module:pkg
- // ex1 jdk.base:java.lang
- // ex2 :java.lang (when in legacy mode)
- private String name;
- // The directory path to the package. If the package belongs to a module,
- // then that module's file system name is part of the path.
- private String dirname;
- // This package has the following dependents, that depend on this package.
- private Set dependents = new HashSet<>();
-
- // Fully qualified name of class in this package -> fully qualified name of dependency
- private Map> dependencies = new TreeMap<>();
- // Fully qualified name of class in this package -> fully qualified name of dependency on class path
- private Map> cpDependencies = new TreeMap<>();
-
- // This is the public api of this package.
- private PubApi pubApi = new PubApi();
- // Map from source file name to Source info object.
- private Map sources = new HashMap<>();
- // This package generated these artifacts.
- private Map artifacts = new HashMap<>();
-
- public Package(Module m, String n) {
- int c = n.indexOf(":");
- Assert.check(c != -1);
- Assert.check(m.name().equals(m.name()));
- name = n;
- dirname = n.replace('.', File.separatorChar);
- if (m.name().length() > 0) {
- // There is a module here, prefix the module dir name to the path.
- dirname = m.dirname()+File.separatorChar+dirname;
- }
- }
-
- public Module mod() { return mod; }
- public String name() { return name; }
- public String dirname() { return dirname; }
- public Map sources() { return sources; }
- public Map artifacts() { return artifacts; }
- public PubApi getPubApi() { return pubApi; }
-
- public Map> typeDependencies() { return dependencies; }
- public Map> typeClasspathDependencies() { return cpDependencies; }
-
- public Set dependents() { return dependents; }
-
- @Override
- public boolean equals(Object o) {
- return (o instanceof Package pac) && name.equals(pac.name);
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
-
- @Override
- public int compareTo(Package o) {
- return name.compareTo(o.name);
- }
-
- public void addSource(Source s) {
- sources.put(s.file().getPath(), s);
- }
-
- private static Pattern DEP_PATTERN = Pattern.compile("(.*) -> (.*)");
- public void parseAndAddDependency(String d, boolean cp) {
- Matcher m = DEP_PATTERN.matcher(d);
- if (!m.matches())
- throw new IllegalArgumentException("Bad dependency string: " + d);
- addDependency(m.group(1), m.group(2), cp);
- }
-
- public void addDependency(String fullyQualifiedFrom,
- String fullyQualifiedTo,
- boolean cp) {
- Map> map = cp ? cpDependencies : dependencies;
- if (!map.containsKey(fullyQualifiedFrom))
- map.put(fullyQualifiedFrom, new HashSet<>());
- map.get(fullyQualifiedFrom).add(fullyQualifiedTo);
- }
-
- public void addDependent(String d) {
- dependents.add(d);
- }
-
- /**
- * Check if we have knowledge in the javac state that
- * describe the results of compiling this package before.
- */
- public boolean existsInJavacState() {
- return artifacts.size() > 0 || !pubApi.isEmpty();
- }
-
- public boolean hasPubApiChanged(PubApi newPubApi) {
- return !newPubApi.isBackwardCompatibleWith(pubApi);
- }
-
- public void setPubapi(PubApi newPubApi) {
- pubApi = newPubApi;
- }
-
- public void setDependencies(Map> ds, boolean cp) {
- (cp ? cpDependencies : dependencies).clear();
- for (String fullyQualifiedFrom : ds.keySet())
- for (String fullyQualifiedTo : ds.get(fullyQualifiedFrom))
- addDependency(fullyQualifiedFrom, fullyQualifiedTo, cp);
- }
-
- public void save(StringBuilder b) {
- b.append("P ").append(name).append("\n");
- Source.saveSources(sources, b);
- saveDependencies(b);
- savePubapi(b);
- saveArtifacts(b);
- }
-
- public static Package load(Module module, String l) {
- String name = l.substring(2);
- return new Package(module, name);
- }
-
- public void saveDependencies(StringBuilder b) {
-
- // Dependencies where *to* is among sources
- for (String fullyQualifiedFrom : dependencies.keySet()) {
- for (String fullyQualifiedTo : dependencies.get(fullyQualifiedFrom)) {
- b.append(String.format("D S %s -> %s%n", fullyQualifiedFrom, fullyQualifiedTo));
- }
- }
-
- // Dependencies where *to* is on class path
- for (String fullyQualifiedFrom : cpDependencies.keySet()) {
- for (String fullyQualifiedTo : cpDependencies.get(fullyQualifiedFrom)) {
- b.append(String.format("D C %s -> %s%n", fullyQualifiedFrom, fullyQualifiedTo));
- }
- }
- }
-
- public void savePubapi(StringBuilder b) {
- pubApi.asListOfStrings()
- .stream()
- .flatMap(l -> Stream.of("I ", l, "\n"))
- .forEach(b::append);
- }
-
- public static void savePackages(Map packages, StringBuilder b) {
- List sorted_packages = new ArrayList<>();
- for (String key : packages.keySet() ) {
- sorted_packages.add(key);
- }
- Collections.sort(sorted_packages);
- for (String s : sorted_packages) {
- Package p = packages.get(s);
- p.save(b);
- }
- }
-
- public void addArtifact(String a) {
- artifacts.put(a, new File(a));
- }
-
- public void addArtifact(File f) {
- artifacts.put(f.getPath(), f);
- }
-
- public void addArtifacts(Set as) {
- for (URI u : as) {
- addArtifact(new File(u));
- }
- }
-
- public void setArtifacts(Set as) {
- Assert.check(!artifacts.isEmpty());
- artifacts = new HashMap<>();
- addArtifacts(as);
- }
-
- public void loadArtifact(String l) {
- // Find next space after "A ".
- int dp = l.indexOf(' ',2);
- String fn = l.substring(2,dp);
- long last_modified = Long.parseLong(l.substring(dp+1));
- File f = new File(fn);
- if (f.exists() && f.lastModified() != last_modified) {
- // Hmm, the artifact on disk does not have the same last modified
- // timestamp as the information from the build database.
- // We no longer trust the artifact on disk. Delete it.
- // The smart javac wrapper will then rebuild the artifact.
- Log.debug("Removing "+f.getPath()+" since its timestamp does not match javac_state.");
- f.delete();
- }
- artifacts.put(f.getPath(), f);
- }
-
- public void saveArtifacts(StringBuilder b) {
- List sorted_artifacts = new ArrayList<>();
- for (File f : artifacts.values()) {
- sorted_artifacts.add(f);
- }
- Collections.sort(sorted_artifacts);
- for (File f : sorted_artifacts) {
- // The last modified information is only used
- // to detect tampering with the output dir.
- // If the outputdir has been modified, not by javac,
- // then a mismatch will be detected in the last modified
- // timestamps stored in the build database compared
- // to the timestamps on disk and the artifact will be deleted.
-
- b.append("A "+f.getPath()+" "+f.lastModified()+"\n");
- }
- }
-
- /**
- * Always clean out a tainted package before it is recompiled.
- */
- public void deleteArtifacts() {
- for (File a : artifacts.values()) {
- a.delete();
- }
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/ProblemException.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/ProblemException.java
deleted file mode 100644
index b6aa759f600..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/ProblemException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-/**
- * Used to signal serious problems when running sjavac.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class ProblemException extends Exception {
- static final long serialVersionUID = -3387516993124229949L;
- public ProblemException(String s) {
- super(s);
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/PubApiExtractor.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/PubApiExtractor.java
deleted file mode 100644
index d5cb4eac624..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/PubApiExtractor.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Arrays;
-
-import javax.tools.JavaCompiler.CompilationTask;
-import javax.tools.JavaFileManager;
-
-import com.sun.tools.javac.api.JavacTool;
-import com.sun.tools.javac.code.ClassFinder;
-import com.sun.tools.javac.code.Symbol.ClassSymbol;
-import com.sun.tools.javac.code.Symtab;
-import com.sun.tools.javac.main.JavaCompiler;
-import com.sun.tools.javac.util.Context;
-import com.sun.tools.javac.util.Convert;
-import com.sun.tools.javac.util.Name;
-import com.sun.tools.javac.util.Names;
-import com.sun.tools.sjavac.comp.PubapiVisitor;
-import com.sun.tools.sjavac.comp.SmartFileManager;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-public class PubApiExtractor {
- // Setup a compiler context for finding classes in the classpath
- // and to execute annotation processors.
- final Context context;
- final CompilationTask task;
-
- final SmartFileManager fileManager;
-
- /**
- * Setup a compilation context, used for reading public apis of classes on the classpath
- * as well as annotation processors.
- */
- public PubApiExtractor(Options options) {
- JavacTool compiler = com.sun.tools.javac.api.JavacTool.create();
- fileManager = new SmartFileManager(compiler.getStandardFileManager(null, null, null));
- context = new com.sun.tools.javac.util.Context();
- String[] args = options.prepJavacArgs();
- task = compiler.getTask(new PrintWriter(System.err),
- fileManager,
- null,
- Arrays.asList(args),
- null,
- null,
- context);
- // Trigger a creation of the JavaCompiler, necessary to get a sourceCompleter for ClassFinder.
- // The sourceCompleter is used for build situations where a classpath class references other classes
- // that happens to be on the sourcepath.
- JavaCompiler.instance(context);
-
-// context.put(JavaFileManager.class, fileManager);
- }
-
- public PubApi getPubApi(String fullyQualifiedClassName) {
- Symtab syms = Symtab.instance(context);
- ClassFinder cr = ClassFinder.instance(context);
- Names ns = Names.instance(context);
- Name n = ns.fromString(fullyQualifiedClassName);
- ClassSymbol cs = cr.loadClass(syms.inferModule(Convert.packagePart(n)), n);
- PubapiVisitor v = new PubapiVisitor();
- v.visit(cs);
- return v.getCollectedPubApi();
- }
-
- public void close() throws IOException {
- fileManager.close();
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Source.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Source.java
deleted file mode 100644
index 1eb4410d5b0..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Source.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.FileSystem;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.PathMatcher;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.util.Set;
-import java.util.Collections;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.regex.PatternSyntaxException;
-
-/** A Source object maintains information about a source file.
- * For example which package it belongs to and kind of source it is.
- * The class also knows how to find source files (scanRoot) given include/exclude
- * patterns and a root.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class Source implements Comparable {
- // The package the source belongs to.
- private Package pkg;
- // Name of this source file, relative its source root.
- // For example: java/lang/Object.java
- // Or if the source file is inside a module:
- // jdk.base/java/lang/Object.java
- private String name;
- // What kind of file is this.
- private String suffix;
- // When this source file was last_modified
- private long lastModified;
- // The source File.
- private File file;
- // If the source is generated.
- private boolean isGenerated;
- // If the source is only linked to, not compiled.
- private boolean linkedOnly;
-
- @Override
- public boolean equals(Object o) {
- return (o instanceof Source source) && name.equals(source.name);
- }
-
- @Override
- public int compareTo(Source o) {
- return name.compareTo(o.name);
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
-
- public Source(Module m, String n, File f) {
- name = n;
- int dp = n.lastIndexOf(".");
- if (dp != -1) {
- suffix = n.substring(dp);
- } else {
- suffix = "";
- }
- file = f;
- lastModified = f.lastModified();
- linkedOnly = false;
- }
-
- public Source(Package p, String n, long lm) {
- pkg = p;
- name = n;
- int dp = n.lastIndexOf(".");
- if (dp != -1) {
- suffix = n.substring(dp);
- } else {
- suffix = "";
- }
- file = null;
- lastModified = lm;
- linkedOnly = false;
- int ls = n.lastIndexOf('/');
- }
-
- public String name() { return name; }
- public String suffix() { return suffix; }
- public Package pkg() { return pkg; }
- public File file() { return file; }
- public long lastModified() {
- return lastModified;
- }
-
- public void setPackage(Package p) {
- pkg = p;
- }
-
- public void markAsGenerated() {
- isGenerated = true;
- }
-
- public boolean isGenerated() {
- return isGenerated;
- }
-
- public void markAsLinkedOnly() {
- linkedOnly = true;
- }
-
- public boolean isLinkedOnly() {
- return linkedOnly;
- }
-
- private void save(StringBuilder b) {
- String CL = linkedOnly?"L":"C";
- String GS = isGenerated?"G":"S";
- b.append(GS+" "+CL+" "+name+" "+file.lastModified()+"\n");
- }
- // Parse a line that looks like this:
- // S C /code/alfa/A.java 1357631228000
- public static Source load(Package lastPackage, String l, boolean isGenerated) {
- int sp = l.indexOf(' ',4);
- if (sp == -1) return null;
- String name = l.substring(4,sp);
- long last_modified = Long.parseLong(l.substring(sp+1));
-
- boolean isLinkedOnly = false;
- if (l.charAt(2) == 'L') {
- isLinkedOnly = true;
- } else if (l.charAt(2) == 'C') {
- isLinkedOnly = false;
- } else return null;
-
- Source s = new Source(lastPackage, name, last_modified);
- s.file = new File(name);
- if (isGenerated) s.markAsGenerated();
- if (isLinkedOnly) s.markAsLinkedOnly();
- return s;
- }
-
- public static void saveSources(Map sources, StringBuilder b) {
- List sorted_sources = new ArrayList<>();
- for (String key : sources.keySet()) {
- sorted_sources.add(key);
- }
- Collections.sort(sorted_sources);
- for (String key : sorted_sources) {
- Source s = sources.get(key);
- s.save(b);
- }
- }
-
- /**
- * Recurse into the directory root and find all files matching the excl/incl/exclfiles/inclfiles rules.
- * Detects the existence of module-info.java files and presumes that the directory it resides in
- * is the name of the current module.
- */
- public static void scanRoot(File root,
- Set suffixes,
- List excludes,
- List includes,
- Map foundFiles,
- Map foundModules,
- final Module currentModule,
- boolean permitSourcesWithoutPackage,
- boolean inGensrc,
- boolean inLinksrc)
- throws IOException, ProblemException {
-
- if (root == null)
- return;
-
- FileSystem fs = root.toPath().getFileSystem();
-
- if (includes.isEmpty()) {
- includes = Collections.singletonList("**");
- }
-
- List includeMatchers = createPathMatchers(fs, includes);
- List excludeMatchers = createPathMatchers(fs, excludes);
-
- Files.walkFileTree(root.toPath(), new SimpleFileVisitor() {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
-
- Path relToRoot = root.toPath().relativize(file);
-
- if (includeMatchers.stream().anyMatch(im -> im.matches(relToRoot))
- && excludeMatchers.stream().noneMatch(em -> em.matches(relToRoot))
- && suffixes.contains(Util.fileSuffix(file))) {
-
- // TODO: Test this.
- Source existing = foundFiles.get(file);
- if (existing != null) {
- throw new IOException("You have already added the file "+file+" from "+existing.file().getPath());
- }
- existing = currentModule.lookupSource(file.toString());
- if (existing != null) {
-
- // Oops, the source is already added, could be ok, could be not, let's check.
- if (inLinksrc) {
- // So we are collecting sources for linking only.
- if (existing.isLinkedOnly()) {
- // Ouch, this one is also for linking only. Bad.
- throw new IOException("You have already added the link only file " + file + " from " + existing.file().getPath());
- }
- // Ok, the existing source is to be compiled. Thus this link only is redundant
- // since all compiled are also linked to. Continue to the next source.
- // But we need to add the source, so that it will be visible to linking,
- // if not the multi core compile will fail because a JavaCompiler cannot
- // find the necessary dependencies for its part of the source.
- foundFiles.put(file.toString(), existing);
- } else {
- // We are looking for sources to compile, if we find an existing to be compiled
- // source with the same name, it is an internal error, since we must
- // find the sources to be compiled before we find the sources to be linked to.
- throw new IOException("Internal error: Double add of file " + file + " from " + existing.file().getPath());
- }
-
- } else {
-
- //////////////////////////////////////////////////////////////
- // Add source
- Source s = new Source(currentModule, file.toString(), file.toFile());
- if (inGensrc) {
- s.markAsGenerated();
- }
- if (inLinksrc) {
- s.markAsLinkedOnly();
- }
- String pkg = packageOfJavaFile(root.toPath(), file);
- pkg = currentModule.name() + ":" + pkg;
- foundFiles.put(file.toString(), s);
- currentModule.addSource(pkg, s);
- //////////////////////////////////////////////////////////////
- }
- }
-
- return FileVisitResult.CONTINUE;
- }
- });
- }
-
- private static List createPathMatchers(FileSystem fs, List patterns) {
- List matchers = new ArrayList<>();
- for (String pattern : patterns) {
- try {
- matchers.add(fs.getPathMatcher("glob:" + pattern));
- } catch (PatternSyntaxException e) {
- Log.error("Invalid pattern: " + pattern);
- throw e;
- }
- }
- return matchers;
- }
-
- private static String packageOfJavaFile(Path sourceRoot, Path javaFile) {
- Path javaFileDir = javaFile.getParent();
- Path packageDir = sourceRoot.relativize(javaFileDir);
- List separateDirs = new ArrayList<>();
- for (Path pathElement : packageDir) {
- separateDirs.add(pathElement.getFileName().toString());
- }
- return String.join(".", separateDirs);
- }
-
- @Override
- public String toString() {
- return String.format("%s[pkg: %s, name: %s, suffix: %s, file: %s, isGenerated: %b, linkedOnly: %b]",
- getClass().getSimpleName(),
- pkg,
- name,
- suffix,
- file,
- isGenerated,
- linkedOnly);
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Transformer.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Transformer.java
deleted file mode 100644
index 4f2ea5d0c7e..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/Transformer.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac;
-
-import java.io.Writer;
-import java.net.URI;
-import java.util.Map;
-import java.util.Set;
-
-import com.sun.tools.sjavac.comp.CompilationService;
-import com.sun.tools.sjavac.options.Options;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * The transform interface is used to transform content inside a package, from one form to another.
- * Usually the output form is an unpredictable number of output files. (eg class files)
- * but can also be an unpredictable number of generated source files (eg idl2java)
- * or a single predictable output file (eg when copying, cleaning or compiling a properties file).
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public interface Transformer {
- /**
- * The transform method takes a set of package names, mapped to their source files and to the
- * pubapis of the packages.
- *
- * The transform implementation must:
- * store the names of the generated artifacts for each package into package_artifacts
- * store found dependencies to other packages into the supplied set package_dependencies
- * store the public api for a package into the supplied set package_pubapis
- *
- * Any benign messages as a result of running the transform
- * are written into stdout, and errors are written to stderr.
- *
- * The debug_level can be 0=silent (only warnings and errors) 1=normal 2=verbose 3 or greater=debug
- * setExtra is used to set the extra information information that can be passed on
- * the command line to the smart javac wrapper.
- *
- * If sjavac is building incrementally from an existing javac_state, the var incremental is true.
- *
- * The transformer will only be called if some source in the package (or dependency) has
- * a modified timestamp. Thus the transformer might get called with many sources, of which
- * only one has changed. The transformer is allowed to regenerate all artifacts but
- * a better transformer will only write those artifacts that need updating.
- *
- * However the transformer must verify that the existing artifacts really are there!
- * and it must always update package_artifacts, package_dependencies, and package_pubapis correctly.
- * This means that at least for Java source, it will always have to recompile the sources.
- *
- * The transformer is allowed to put files anywhere in the dest_root.
- * An example of this is, can be the META-INF transformer that copy files
- * below META-INF directories to the single META-INF directory below dest_root.
- *
- * False is returned if there was an error that prevented the transform.
- * I.e. something was printed on stderr.
- *
- * If num_cores is set to a non-zero value. The transform should attempt to use no more than these
- * number of threads for heavy work.
- */
- boolean transform(CompilationService sjavac,
- Map> pkgSrcs,
- Set visibleSources,
- Map> oldPackageDependencies,
- URI destRoot,
- Map> packageArtifacts,
- Map>> packageDependencies, // Package name -> Fully Qualified Type [from] -> Set of fully qualified type [to]
- Map>> packageCpDependencies, // Package name -> Fully Qualified Type [from] -> Set of fully qualified type [to]
- Map packagePublicApis,
- Map dependencyApis,
- int debugLevel,
- boolean incremental,
- int numCores);
-
- void setExtra(String e);
- void setExtra(Options args);
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/CompilationService.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/CompilationService.java
deleted file mode 100644
index bf55947827c..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/CompilationService.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac.comp;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.URI;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import javax.tools.JavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.StandardLocation;
-import javax.tools.ToolProvider;
-
-import com.sun.tools.javac.api.JavacTaskImpl;
-import com.sun.tools.javac.api.JavacTool;
-import com.sun.tools.javac.main.Main;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.javac.util.Context;
-import com.sun.tools.javac.util.Dependencies;
-import com.sun.tools.javac.util.ListBuffer;
-import com.sun.tools.sjavac.Log;
-import com.sun.tools.sjavac.Util;
-import com.sun.tools.sjavac.comp.dependencies.NewDependencyCollector;
-import com.sun.tools.sjavac.comp.dependencies.PublicApiCollector;
-import com.sun.tools.sjavac.server.CompilationSubResult;
-import com.sun.tools.sjavac.server.SysInfo;
-
-/**
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class CompilationService {
-
- public SysInfo getSysInfo() {
- return new SysInfo(Runtime.getRuntime().availableProcessors(),
- Runtime.getRuntime().maxMemory());
- }
-
- public CompilationSubResult compile(String protocolId,
- String invocationId,
- String[] args,
- List explicitSources,
- Set sourcesToCompile,
- Set visibleSources) {
-
- JavacTool compiler = (JavacTool) ToolProvider.getSystemJavaCompiler();
- try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
- SmartFileManager sfm = new SmartFileManager(fm);
- Context context = new Context();
-
- Dependencies.GraphDependencies.preRegister(context);
-
- // Now setup the actual compilation
- CompilationSubResult compilationResult = new CompilationSubResult(Result.OK);
-
- // First deal with explicit source files on cmdline and in at file
- ListBuffer explicitJFOs = new ListBuffer<>();
- for (JavaFileObject jfo : fm.getJavaFileObjectsFromFiles(explicitSources)) {
- explicitJFOs.append(SmartFileManager.locWrap(jfo, StandardLocation.SOURCE_PATH));
- }
- // Now deal with sources supplied as source_to_compile
- ListBuffer sourcesToCompileFiles = new ListBuffer<>();
- for (URI u : sourcesToCompile)
- sourcesToCompileFiles.append(new File(u));
-
- for (JavaFileObject jfo : fm.getJavaFileObjectsFromFiles(sourcesToCompileFiles))
- explicitJFOs.append(SmartFileManager.locWrap(jfo, StandardLocation.SOURCE_PATH));
-
- // Create a log to capture compiler output
- StringWriter stderrLog = new StringWriter();
- Result result;
- PublicApiCollector pubApiCollector = new PublicApiCollector(context, explicitJFOs);
- PathAndPackageVerifier papVerifier = new PathAndPackageVerifier();
- NewDependencyCollector depsCollector = new NewDependencyCollector(context, explicitJFOs);
- try {
- if (explicitJFOs.size() > 0) {
- sfm.setVisibleSources(visibleSources);
- sfm.cleanArtifacts();
-
- // Do the compilation!
- JavacTaskImpl task =
- (JavacTaskImpl) compiler.getTask(new PrintWriter(stderrLog),
- sfm,
- null,
- Arrays.asList(args),
- null,
- explicitJFOs,
- context);
- sfm.setSymbolFileEnabled(!com.sun.tools.javac.util.Options.instance(context).isSet("ignore.symbol.file"));
- task.addTaskListener(depsCollector);
- task.addTaskListener(pubApiCollector);
- task.addTaskListener(papVerifier);
- logJavacInvocation(args);
- result = task.doCall();
- Log.debug("javac result: " + result);
- sfm.flush();
- } else {
- result = Result.ERROR;
- }
- } catch (Exception e) {
- Log.error(Util.getStackTrace(e));
- stderrLog.append(Util.getStackTrace(e));
- result = Result.ERROR;
- }
-
- compilationResult.packageArtifacts = sfm.getPackageArtifacts();
-
- if (papVerifier.errorsDiscovered()) {
- result = Result.ERROR;
- }
-
- compilationResult.packageDependencies = depsCollector.getDependencies(false);
- compilationResult.packageCpDependencies = depsCollector.getDependencies(true);
-
- compilationResult.packagePubapis = pubApiCollector.getPubApis(true);
- compilationResult.dependencyPubapis = pubApiCollector.getPubApis(false);
- compilationResult.stderr = stderrLog.toString();
- compilationResult.result = result;
-
- return compilationResult;
- } catch (IOException e) {
- throw new Error(e);
- }
- }
-
- private void logJavacInvocation(String[] args) {
- Log.debug("Invoking javac with args");
- Iterator argIter = Arrays.asList(args).iterator();
- while (argIter.hasNext()) {
- String arg = argIter.next();
- String line = " " + arg;
- if (arg.matches("\\-(d|cp|classpath|sourcepath|source|target)")
- && argIter.hasNext()) {
- line += " " + argIter.next();
- }
- Log.debug(line);
- }
- }
-
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/JavaFileObjectWithLocation.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/JavaFileObjectWithLocation.java
deleted file mode 100644
index 4e1cafb5be6..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/JavaFileObjectWithLocation.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac.comp;
-
-import javax.tools.ForwardingJavaFileObject;
-import javax.tools.JavaFileManager.Location;
-import javax.tools.JavaFileObject;
-
-import com.sun.tools.javac.api.ClientCodeWrapper.Trusted;
-
-@Trusted
-public class JavaFileObjectWithLocation extends ForwardingJavaFileObject {
-
- private final Location loc;
-
- public JavaFileObjectWithLocation(F delegate, Location loc) {
- super(delegate);
- this.loc = loc;
- }
-
- public Location getLocation() {
- return loc;
- }
-
- public F getDelegate() {
- return fileObject;
- }
-
- public String toString() {
- return "JavaFileObjectWithLocation[loc: " + loc + ", " + fileObject + "]";
- }
-
- @Override
- public int hashCode() {
- return loc.hashCode() ^ fileObject.hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- return (obj instanceof JavaFileObjectWithLocation> javaFileObjectWithLocation)
- && loc.equals(javaFileObjectWithLocation.loc)
- && fileObject.equals(javaFileObjectWithLocation.fileObject);
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PathAndPackageVerifier.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PathAndPackageVerifier.java
deleted file mode 100644
index 8ef72426f48..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PathAndPackageVerifier.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac.comp;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.tools.JavaFileObject;
-
-import com.sun.source.tree.CompilationUnitTree;
-import com.sun.source.util.TaskEvent;
-import com.sun.source.util.TaskListener;
-import com.sun.tools.javac.tree.JCTree;
-import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
-import com.sun.tools.javac.tree.JCTree.JCIdent;
-import com.sun.tools.javac.util.DefinedBy;
-import com.sun.tools.javac.util.DefinedBy.Api;
-import com.sun.tools.javac.util.Name;
-import com.sun.tools.sjavac.Log;
-
-public class PathAndPackageVerifier implements TaskListener {
-
- // Stores the set of compilation units whose source file path does not
- // match the package declaration.
- Set misplacedCompilationUnits = new HashSet<>();
-
- @Override
- @DefinedBy(Api.COMPILER_TREE)
- public void finished(TaskEvent e) {
- if (e.getKind() == TaskEvent.Kind.ANALYZE) {
-
- CompilationUnitTree cu = e.getCompilationUnit();
- if (cu == null)
- return;
-
- JavaFileObject jfo = cu.getSourceFile();
- if (jfo == null)
- return; // No source file -> package doesn't matter
-
- JCTree pkg = (JCTree) cu.getPackageName();
- if (pkg == null)
- return; // Default package. See JDK-8048144.
-
- Path dir = Paths.get(jfo.toUri()).normalize().getParent();
- if (!checkPathAndPackage(dir, pkg))
- misplacedCompilationUnits.add(cu);
- }
-
- if (e.getKind() == TaskEvent.Kind.COMPILATION) {
- for (CompilationUnitTree cu : misplacedCompilationUnits) {
- Log.error("Misplaced compilation unit.");
- Log.error(" Directory: " + Paths.get(cu.getSourceFile().toUri()).getParent());
- Log.error(" Package: " + cu.getPackageName());
- }
- }
- }
-
- public boolean errorsDiscovered() {
- return misplacedCompilationUnits.size() > 0;
- }
-
- /* Returns true if dir matches pkgName.
- *
- * Examples:
- * (a/b/c, a.b.c) gives true
- * (i/j/k, i.x.k) gives false
- *
- * Currently (x/a/b/c, a.b.c) also gives true. See JDK-8059598.
- */
- private boolean checkPathAndPackage(Path dir, JCTree pkgName) {
- Iterator pathIter = new ParentIterator(dir);
- Iterator pkgIter = new EnclosingPkgIterator(pkgName);
- while (pathIter.hasNext() && pkgIter.hasNext()) {
- if (!pathIter.next().equals(pkgIter.next()))
- return false;
- }
- return !pkgIter.hasNext(); /*&& !pathIter.hasNext() See JDK-8059598 */
- }
-
- /* Iterates over the names of the parents of the given path:
- * Example: dir1/dir2/dir3 results in dir3 -> dir2 -> dir1
- */
- private static class ParentIterator implements Iterator {
- Path next;
- ParentIterator(Path initial) {
- next = initial;
- }
- @Override
- public boolean hasNext() {
- return next != null;
- }
- @Override
- public String next() {
- String tmp = next.getFileName().toString();
- next = next.getParent();
- return tmp;
- }
- }
-
- /* Iterates over the names of the enclosing packages:
- * Example: pkg1.pkg2.pkg3 results in pkg3 -> pkg2 -> pkg1
- */
- private static class EnclosingPkgIterator implements Iterator {
- JCTree next;
- EnclosingPkgIterator(JCTree initial) {
- next = initial;
- }
- @Override
- public boolean hasNext() {
- return next != null;
- }
- @Override
- public String next() {
- Name name;
- if (next instanceof JCIdent identNext) {
- name = identNext.name;
- next = null;
- } else {
- JCFieldAccess fa = (JCFieldAccess) next;
- name = fa.name;
- next = fa.selected;
- }
- return name.toString();
- }
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubAPIs.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubAPIs.java
deleted file mode 100644
index 21856f95ef5..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubAPIs.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac.comp;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.lang.model.element.Element;
-import javax.tools.JavaFileObject;
-
-import com.sun.tools.javac.code.Symbol.ClassSymbol;
-import com.sun.tools.javac.util.Context;
-import com.sun.tools.javac.util.Log;
-import com.sun.tools.sjavac.pubapi.PubApi;
-
-/**
- * Utility class containing public API information.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class PubAPIs {
- protected static final Context.Key pubApisKey = new Context.Key<>();
-
- // The log to be used for error reporting.
- protected Log log;
-
- // Map from a class name to its public api.
- // Will the Name encode the module in the future?
- // If not, this will have to change to map from Module+Name to public api.
- protected Map publicApiPerClass = new HashMap<>();
-
- public static PubAPIs instance(Context context) {
- PubAPIs instance = context.get(pubApisKey);
- if (instance == null)
- instance = new PubAPIs(context);
- return instance;
- }
-
- private PubAPIs(Context context) {
- context.put(pubApisKey, this);
- log = Log.instance(context);
- }
-
- /**
- * Convert the map from class names to their pubapi to a map
- * from package names to their pubapi.
- */
- public Map getPubapis(Collection explicitJFOs, boolean explicits) {
-
- // Maps ":java.lang" to a package level pub api (with only types on top level)
- Map result = new HashMap<>();
- for (ClassSymbol cs : publicApiPerClass.keySet()) {
-
- boolean amongExplicits = explicitJFOs.contains(cs.sourcefile);
- if (explicits != amongExplicits)
- continue;
-
- String pkg = ":" + cs.packge().fullname;
- PubApi currentPubApi = result.getOrDefault(pkg, new PubApi());
- result.put(pkg, PubApi.mergeTypes(currentPubApi, publicApiPerClass.get(cs)));
- }
-
- return result;
- }
-
- /**
- * Visit the api of a class and construct a pubapi and
- * store it into the pubapi_perclass map.
- */
- @SuppressWarnings("deprecation")
- public void visitPubapi(Element e) {
-
- // Skip anonymous classes for now
- if (e == null)
- return;
-
- PubapiVisitor v = new PubapiVisitor();
- v.visit(e);
- publicApiPerClass.put((ClassSymbol) e, v.getCollectedPubApi());
- }
-}
diff --git a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubapiVisitor.java b/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubapiVisitor.java
deleted file mode 100644
index 5a3785cc299..00000000000
--- a/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/PubapiVisitor.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.tools.sjavac.comp;
-
-import static javax.lang.model.element.Modifier.PRIVATE;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-import javax.lang.model.element.*;
-import javax.lang.model.type.TypeMirror;
-import javax.lang.model.util.ElementScanner14;
-
-import com.sun.tools.javac.code.Symbol.ClassSymbol;
-import com.sun.tools.javac.util.DefinedBy;
-import com.sun.tools.javac.util.DefinedBy.Api;
-import com.sun.tools.sjavac.pubapi.PubApi;
-import com.sun.tools.sjavac.pubapi.PubApiTypeParam;
-import com.sun.tools.sjavac.pubapi.PubMethod;
-import com.sun.tools.sjavac.pubapi.PubType;
-import com.sun.tools.sjavac.pubapi.PubVar;
-import com.sun.tools.sjavac.pubapi.TypeDesc;
-
-/** Utility class that constructs a textual representation
- * of the public api of a class.
- *
- *
This is NOT part of any supported API.
- * If you write code that depends on this, you do so at your own risk.
- * This code and its internal interfaces are subject to change or
- * deletion without notice.
- */
-public class PubapiVisitor extends ElementScanner14 {
-
- private PubApi collectedApi = new PubApi();
-
- private boolean isNonPrivate(Element e) {
- return !e.getModifiers().contains(PRIVATE);
- }
-
- @Override @DefinedBy(Api.LANGUAGE_MODEL)
- public Void visitType(TypeElement e, Void p) {
- if (isNonPrivate(e)) {
- PubApi prevApi = collectedApi;
- collectedApi = new PubApi();
- super.visitType(e, p);
- if (!isAnonymous(e)) {
- String name = ((ClassSymbol) e).flatname.toString();
- PubType t = new PubType(e.getModifiers(),
- name,
- //e.getQualifiedName().toString(),
- collectedApi);
- prevApi.types.put(t.fqName, t);
- }
- collectedApi = prevApi;
- }
- return null;
- }
-
- private boolean isAnonymous(TypeElement e) {
- return e.getQualifiedName().length() == 0;
- }
-
- private static String encodeChar(int c) {
- return String.format("\\u%04x", c);
- }
-
- @Override @DefinedBy(Api.LANGUAGE_MODEL)
- public Void visitVariable(VariableElement e, Void p) {
- if (isNonPrivate(e)) {
- Object constVal = e.getConstantValue();
- String constValStr = null;
- // TODO: This doesn't seem to be entirely accurate. What if I change
- // from, say, 0 to 0L? (And the field is public static final so that
- // it could get inlined.)
- if (constVal != null) {
- if (e.asType().toString().equals("char")) {
- // What type is 'value'? Is it already a char?
- char c = constVal.toString().charAt(0);
- constValStr = "'" + encodeChar(c) + "'";
- } else {
- constValStr = constVal.toString()
- .chars()
- .mapToObj(PubapiVisitor::encodeChar)
- .collect(Collectors.joining("", "\"", "\""));
- }
- }
-
- PubVar v = new PubVar(e.getModifiers(),
- TypeDesc.fromType(e.asType()),
- e.toString(),
- constValStr);
- collectedApi.variables.put(v.identifier, v);
- }
-
- // Safe to not recurse here, because the only thing
- // to visit here is the constructor of a variable declaration.
- // If it happens to contain an anonymous inner class (which it might)
- // then this class is never visible outside of the package anyway, so
- // we are allowed to ignore it here.
- return null;
- }
-
- @Override @DefinedBy(Api.LANGUAGE_MODEL)
- public Void visitRecordComponent(RecordComponentElement e, Void p) {
- PubVar v = new PubVar(e.getModifiers(),
- TypeDesc.fromType(e.asType()),
- e.toString(),
- null);
- collectedApi.recordComponents.put(v.identifier, v);
- return null;
- }
-
- @Override @DefinedBy(Api.LANGUAGE_MODEL)
- public Void visitExecutable(ExecutableElement e, Void p) {
- if (isNonPrivate(e)) {
- PubMethod m = new PubMethod(e.getModifiers(),
- getTypeParameters(e.getTypeParameters()),
- TypeDesc.fromType(e.getReturnType()),
- e.getSimpleName().toString(),
- getTypeDescs(getParamTypes(e)),
- getTypeDescs(e.getThrownTypes()));
- collectedApi.methods.put(m.asSignatureString(), m);
- }
- return null;
- }
-
- private List getTypeParameters(List extends TypeParameterElement> elements) {
- return elements.stream()
- .map(e -> new PubApiTypeParam(e.getSimpleName().toString(), getTypeDescs(e.getBounds())))
- .toList();
- }
-
- private List