forked from typesafehub/zinc
/
Compiler.scala
227 lines (197 loc) · 8.7 KB
/
Compiler.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/**
* Copyright (C) 2012 Typesafe, Inc. <http://www.typesafe.com>
*/
package com.typesafe.zinc
import java.io.File
import java.net.URLClassLoader
import sbt.{ ClasspathOptions, CompileOptions, CompileSetup, LoggerReporter, ScalaInstance }
import sbt.compiler.{ AggressiveCompile, AnalyzingCompiler, CompilerCache, CompileOutput, IC }
import sbt.inc.{ Analysis, AnalysisStore, FileBasedStore }
import sbt.Path._
import xsbti.compile.{ JavaCompiler, GlobalsCache }
import xsbti.Logger
object Compiler {
val CompilerInterfaceId = "compiler-interface"
val JavaClassVersion = System.getProperty("java.class.version")
/**
* Static cache for zinc compilers.
*/
val compilerCache = Cache[Setup, Compiler](Setup.Defaults.compilerCacheLimit)
/**
* Static cache for resident scala compilers.
*/
val residentCache: GlobalsCache = createResidentCache(Setup.Defaults.residentCacheLimit)
/**
* Static cache for compile analyses. Values must be Options because in get() we don't yet know if, on
* a cache miss, the underlying file will yield a valid Analysis.
*/
val analysisCache = Cache[FileFPrint, Option[(Analysis, CompileSetup)]](Setup.Defaults.analysisCacheLimit)
private val classLoaderCache: /*ClassLoaderCache*/ Any = ClassLoaderCacheAccess.newClassLoaderCache()
/**
* Get or create a zinc compiler based on compiler setup.
*/
def apply(setup: Setup, log: Logger): Compiler = {
compilerCache.get(setup)(create(setup, log))
}
/**
* Java API for creating compiler.
*/
def getOrCreate(setup: Setup, log: Logger): Compiler = apply(setup, log)
/**
* Create a new zinc compiler based on compiler setup.
*/
def create(setup: Setup, log: Logger): Compiler = {
val instance = scalaInstance(setup)
val interfaceJar = compilerInterface(setup, instance, log)
val scalac = newScalaCompiler(instance, interfaceJar, log)
val javac = newJavaCompiler(instance, setup.javaHome, setup.forkJava)
new Compiler(scalac, javac)
}
/**
* Create a new scala compiler.
*/
def newScalaCompiler(instance: ScalaInstance, interfaceJar: File, log: Logger): AnalyzingCompiler = {
val compiler = IC.newScalaCompiler(instance, interfaceJar, ClasspathOptions.boot, log)
// This cache, new in SBT 0.13.13, avoids repeatedly classloading the compiler interface's CallbackGlobal,
// which was bad for performance. The layer of compiler caching here in Zinc probably mitigated that ill effect,
// so long as the caller needed fewer than `Setup.Defaults.compilerCacheLimit` compilers at a time.
ClassLoaderCacheAccess.withClassLoaderCache(compiler, classLoaderCache)
}
/**
* Create a new java compiler.
*/
def newJavaCompiler(instance: ScalaInstance, javaHome: Option[File], fork: Boolean): JavaCompiler = {
val options = ClasspathOptions.javac(false)
if (fork || javaHome.isDefined)
sbt.compiler.JavaCompiler.fork(options, instance)(AggressiveCompile.forkJavac(javaHome))
else
sbt.compiler.JavaCompiler.directOrFork(options, instance)(AggressiveCompile.forkJavac(None))
}
/**
* Create new globals cache.
*/
def createResidentCache(maxCompilers: Int): GlobalsCache = {
if (maxCompilers <= 0) CompilerCache.fresh else CompilerCache(maxCompilers)
}
/**
* Create an analysis store backed by analysisCache.
*/
def analysisStore(cacheFile: File): AnalysisStore = {
val fileStore = AnalysisStore.cached(FileBasedStore(cacheFile))
val fprintStore = new AnalysisStore {
def set(analysis: Analysis, setup: CompileSetup) {
fileStore.set(analysis, setup)
FileFPrint.fprint(cacheFile) foreach { analysisCache.put(_, Some((analysis, setup))) }
}
def get(): Option[(Analysis, CompileSetup)] = {
FileFPrint.fprint(cacheFile) flatMap { fprint => analysisCache.get(fprint)(fileStore.get) }
}
}
AnalysisStore.sync(AnalysisStore.cached(fprintStore))
}
/**
* Get an analysis, lookup by cache file.
*/
def analysis(cacheFile: File): Analysis = {
analysisStore(cacheFile).get map (_._1) getOrElse Analysis.Empty
}
/**
* Check whether an analysis is empty.
*/
def analysisIsEmpty(cacheFile: File): Boolean = {
analysis(cacheFile) eq Analysis.Empty
}
/**
* Create the scala instance for the compiler. Includes creating the classloader.
*/
def scalaInstance(setup: Setup): ScalaInstance = {
import setup.{ scalaCompiler, scalaLibrary, scalaExtra}
val loader = scalaLoader(scalaLibrary +: scalaCompiler +: scalaExtra)
val version = scalaVersion(loader)
new ScalaInstance(version.getOrElse("unknown"), loader, scalaLibrary, scalaCompiler, scalaExtra, version)
}
/**
* Create a new classloader with the root loader as parent (to avoid zinc itself being included).
*/
def scalaLoader(jars: Seq[File]) = new URLClassLoader(toURLs(jars), sbt.classpath.ClasspathUtilities.rootLoader)
/**
* Get the actual scala version from the compiler.properties in a classloader.
* The classloader should only contain one version of scala.
*/
def scalaVersion(scalaLoader: ClassLoader): Option[String] = {
Util.propertyFromResource("compiler.properties", "version.number", scalaLoader)
}
/**
* Get the compiler interface for this compiler setup. Compile it if not already cached.
*/
def compilerInterface(setup: Setup, scalaInstance: ScalaInstance, log: Logger): File = {
val dir = setup.cacheDir / interfaceId(scalaInstance.actualVersion)
val interfaceJar = dir / (CompilerInterfaceId + ".jar")
if (!interfaceJar.exists) {
dir.mkdirs()
IC.compileInterfaceJar(CompilerInterfaceId, setup.compilerInterfaceSrc, interfaceJar, setup.sbtInterface, scalaInstance, log)
}
interfaceJar
}
def interfaceId(scalaVersion: String) = CompilerInterfaceId + "-" + scalaVersion + "-" + JavaClassVersion
}
/**
* A zinc compiler for incremental recompilation.
*/
class Compiler(scalac: AnalyzingCompiler, javac: JavaCompiler) {
/**
* Run a compile. The resulting analysis is also cached in memory.
* Note: This variant automatically contructs an error-reporter.
*/
def compile(inputs: Inputs)(log: Logger): Analysis = compile(inputs, None)(log)
/**
* Run a compile. The resulting analysis is also cached in memory.
*
* Note: This variant automatically contructs an error-reporter.
*/
def compile(inputs: Inputs, cwd: Option[File])(log: Logger): Analysis = {
val maxErrors = 100
compile(inputs, cwd, new LoggerReporter(maxErrors, log, identity))(log)
}
/**
* Run a compile. The resulting analysis is also cached in memory.
*
* Note: This variant does not report progress updates
*/
def compile(inputs: Inputs, cwd: Option[File], reporter: xsbti.Reporter)(log: Logger): Analysis = {
compile(inputs, cwd, reporter, progress = None)(log)
}
/**
* Run a compile. The resulting analysis is also cached in memory.
*/
def compile(inputs: Inputs, cwd: Option[File], reporter: xsbti.Reporter, progress: Option[xsbti.compile.CompileProgress])(log: Logger): Analysis = {
import inputs._
if (forceClean && Compiler.analysisIsEmpty(cacheFile)) Util.cleanAllClasses(classesDirectory)
val getAnalysis: File => Option[Analysis] = analysisMap.get _
val aggressive = new AggressiveCompile(cacheFile)
val cp = autoClasspath(classesDirectory, scalac.scalaInstance.allJars, javaOnly, classpath)
val compileOutput = CompileOutput(classesDirectory)
val globalsCache = Compiler.residentCache
val skip = false
val incOpts = incOptions.options
val compileSetup = new CompileSetup(compileOutput, new CompileOptions(scalacOptions, javacOptions), scalac.scalaInstance.actualVersion, compileOrder, incOpts.nameHashing)
val analysisStore = Compiler.analysisStore(cacheFile)
val analysis = aggressive.compile1(sources, cp, compileSetup, progress, analysisStore, getAnalysis, definesClass, scalac, javac, reporter, skip, globalsCache, incOpts)(log)
if (mirrorAnalysis) {
SbtAnalysis.printRelations(analysis, Some(new File(cacheFile.getPath() + ".relations")), cwd)
}
SbtAnalysis.printOutputs(analysis, outputRelations, outputProducts, cwd, classesDirectory)
analysis
}
/**
* Automatically add the output directory and scala library to the classpath.
*/
def autoClasspath(classesDirectory: File, allScalaJars: Seq[File], javaOnly: Boolean, classpath: Seq[File]): Seq[File] = {
if (javaOnly) classesDirectory +: classpath
else Setup.splitScala(allScalaJars) match {
case Some(scalaJars) => classesDirectory +: scalaJars.library +: classpath
case None => classesDirectory +: classpath
}
}
override def toString = "Compiler(Scala %s)" format scalac.scalaInstance.actualVersion
}