Skip to content

Commit

Permalink
Add support for Java 9+ (#182)
Browse files Browse the repository at this point in the history
Add support for Java 9+
  • Loading branch information
olafurpg authored Aug 19, 2019
2 parents cba7690 + 264dddf commit 364ebde
Showing 1 changed file with 44 additions and 4 deletions.
48 changes: 44 additions & 4 deletions mdoc/src/main/scala/mdoc/internal/markdown/MarkdownCompiler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import mdoc.internal.document.MdocNonFatal
import mdoc.internal.pos.PositionSyntax
import mdoc.internal.pos.PositionSyntax._
import mdoc.internal.pos.TokenEditDistance
import scala.collection.JavaConverters._
import scala.meta._
import scala.meta.inputs.Input
import scala.meta.inputs.Position
Expand All @@ -25,6 +26,7 @@ import scala.tools.nsc.Global
import scala.tools.nsc.Settings
import scala.tools.nsc.io.AbstractFile
import scala.tools.nsc.io.VirtualDirectory
import sun.misc.Unsafe

object MarkdownCompiler {

Expand Down Expand Up @@ -90,14 +92,52 @@ object MarkdownCompiler {

private def defaultClasspath(fn: Path => Boolean): Classpath = {
val paths =
getClass.getClassLoader
.asInstanceOf[URLClassLoader]
.getURLs
.iterator
getURLs(getClass.getClassLoader)
.map(url => AbsolutePath(Paths.get(url.toURI)))
Classpath(paths.toList)
}

/**
* Utility to get SystemClassLoader/ClassLoader urls in java8 and java9+
* Based upon: https://gist.github.com/hengyunabc/644f8e84908b7b405c532a51d8e34ba9
*/
private def getURLs(classLoader: ClassLoader): Seq[URL] = {
if (classLoader.isInstanceOf[URLClassLoader]) {
classLoader.asInstanceOf[URLClassLoader].getURLs()
// java9+
} else if (classLoader
.getClass()
.getName()
.startsWith("jdk.internal.loader.ClassLoaders$")) {
try {
val field = classOf[Unsafe].getDeclaredField("theUnsafe")
field.setAccessible(true)
val unsafe = field.get(null).asInstanceOf[Unsafe]

// jdk.internal.loader.ClassLoaders.AppClassLoader.ucp
val ucpField = classLoader.getClass().getDeclaredField("ucp")
val ucpFieldOffset: Long = unsafe.objectFieldOffset(ucpField)
val ucpObject = unsafe.getObject(classLoader, ucpFieldOffset)

// jdk.internal.loader.URLClassPath.path
val pathField = ucpField.getType().getDeclaredField("path")
val pathFieldOffset = unsafe.objectFieldOffset(pathField)
val paths: Seq[URL] = unsafe
.getObject(ucpObject, pathFieldOffset)
.asInstanceOf[java.util.ArrayList[URL]]
.asScala

paths
} catch {
case ex: Exception =>
ex.printStackTrace()
Nil
}
} else {
Nil
}
}

}

class MarkdownCompiler(
Expand Down

0 comments on commit 364ebde

Please sign in to comment.