-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathPlugins.scala
More file actions
275 lines (230 loc) · 9.79 KB
/
Plugins.scala
File metadata and controls
275 lines (230 loc) · 9.79 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package dotty.tools.dotc
package plugins
import core.*
import Contexts.*
import Decorators.em
import config.PathResolver
import dotty.tools.io.*
import Phases.*
import config.Printers.plugins.{ println => debug }
import config.Properties
/** Support for run-time loading of compiler plugins.
*
* @author Lex Spoon
* @version 1.1, 2009/1/2
* Updated 2009/1/2 by Anders Bach Nielsen: Added features to implement SIP 00002
*/
trait Plugins {
self: ContextBase =>
/** Load a rough list of the plugins. For speed, it
* does not instantiate a compiler run. Therefore it cannot
* test for same-named phases or other problems that are
* filtered from the final list of plugins.
*/
protected def loadRoughPluginsList(using Context): List[Plugin] = {
def asPath(p: String) = ClassPath.split(p)
val paths = ctx.settings.plugin.value
.filter (_ != "")
.map(s => asPath(s).map(Path.apply))
val dirs = {
def injectDefault(s: String) = if (s.isEmpty) PathResolver.Defaults.scalaPluginPath else s
asPath(ctx.settings.pluginsDir.value) map injectDefault map Path.apply
}
val maybes = Plugin.loadAllFrom(paths, dirs, ctx.settings.disable.value)
val (goods, errors) = maybes partition (_.isSuccess)
// Explicit parameterization of recover to avoid -Wshadow warning about inferred Any
errors foreach (_.recover[Any] {
// legacy behavior ignores altogether, so at least warn devs
case e: MissingPluginException => report.warning(e.getMessage)
case e: Exception => report.inform(e.getMessage)
})
goods map (_.get)
}
private var _roughPluginsList: List[Plugin] | Null = null
protected def roughPluginsList(using Context): List[Plugin] =
if (_roughPluginsList == null) {
_roughPluginsList = loadRoughPluginsList
}
_roughPluginsList.nn
/** Load all available plugins. Skips plugins that
* either have the same name as another one, or which
* define a phase name that another one does.
*/
protected def loadPlugins(using Context): List[Plugin] = {
// remove any with conflicting names or subcomponent names
def pick(
plugins: List[Plugin],
plugNames: Set[String]): List[Plugin] = {
if (plugins.isEmpty) return Nil // early return
val plug :: tail = plugins: @unchecked
def withoutPlug = pick(tail, plugNames)
def withPlug = plug :: pick(tail, plugNames + plug.name)
def note(msg: String): Unit = if (ctx.settings.verbose.value) report.inform(msg format plug.name)
def fail(msg: String) = { note(msg) ; withoutPlug }
if (plugNames contains plug.name)
fail("[skipping a repeated plugin: %s]")
else if (ctx.settings.disable.value contains plug.name)
fail("[disabling plugin: %s]")
else {
note("[loaded plugin %s]")
withPlug
}
}
val plugs = pick(roughPluginsList, ctx.base.phasePlan.flatten.map(_.phaseName).toSet)
// Verify required plugins are present.
for (req <- ctx.settings.require.value ; if !(plugs exists (_.name == req)))
report.error(em"Missing required plugin: $req")
// Verify no non-existent plugin given with -P
for
opt <- ctx.settings.pluginOptions.value
if !plugs.exists(plug => opt.startsWith(plug.name + ":"))
do
report.error(em"bad option: -P:$opt")
plugs
}
private var _plugins: List[Plugin] | Null = null
def plugins(using Context): List[Plugin] =
if (_plugins == null) {
_plugins = loadPlugins
}
_plugins.nn
/** A description of all the plugins that are loaded */
def pluginDescriptions(using Context): String =
roughPluginsList map (x => "%s - %s".format(x.name, x.description)) mkString "\n"
/** Summary of the options for all loaded plugins */
def pluginOptionsHelp(using Context): String =
(for (plug <- roughPluginsList ; help <- plug.optionsHelp) yield {
"\nOptions for plugin '%s':\n%s\n".format(plug.name, help)
}).mkString
/** Add plugin phases to phase plan */
def addPluginPhases(plan: List[List[Phase]])(using Context): List[List[Phase]] = {
def options(plugin: Plugin): List[String] =
def namec = plugin.name + ":"
ctx.settings.pluginOptions.value
.filter(_.startsWith(namec))
.map(_.stripPrefix(namec))
// schedule plugins according to ordering constraints
val pluginPhases = plugins.collect { case p: StandardPlugin => p }.flatMap { plug => plug.initialize(options(plug)) }
val updatedPlan = Plugins.schedule(plan, pluginPhases)
// add research plugins
if Properties.researchPluginEnabled then
plugins.collect { case p: ResearchPlugin => p }.foldRight(updatedPlan) {
(plug, plan) => plug.init(options(plug), plan)
}
else
updatedPlan
}
}
object Plugins {
/** Insert plugin phases in the right place of the phase plan
*
* The scheduling makes sure the ordering constraints of plugin phases are satisfied.
* If the ordering constraints are unsatisfiable, an exception is thrown.
*
* Note: this algorithm is factored out for unit test.
*/
def schedule(plan: List[List[Phase]], pluginPhases: List[PluginPhase]): List[List[Phase]] = {
import scala.collection.mutable.{ Map => MMap }
type OrderingReq = (Set[String], Set[String])
val orderRequirements = MMap[String, OrderingReq]()
// 1. already inserted phases don't need constraints themselves.
// 2. no need to propagate beyond boundary of inserted phases, as the information
// beyond boundary is less useful than the boundary.
// 3. unsatisfiable constraints will still be exposed by the first plugin in a loop
// due to its conflicting `runAfter` and `runBefore` after propagation. The ordering
// of primitive phases (`plan`) are used to check `runAfter` and `runBefore`, thus
// there is no need to propagate the primitive phases.
var insertedPhase = plan.flatMap(ps => ps.map(_.phaseName)).toSet
def isInserted(phase: String): Boolean = insertedPhase.contains(phase)
var updatedPlan = plan
def constraintConflict(phase: Phase): String = {
val (runsAfter, runsBefore) = orderRequirements(phase.phaseName)
s"""
|Ordering conflict for phase ${phase.phaseName}
|after: ${runsAfter.mkString("[", ", ", "]")}
|before: ${runsBefore.mkString("[", ", ", "]")}
""".stripMargin
}
// init ordering map, no propagation
pluginPhases.foreach { phase =>
val runsAfter = phase.runsAfter
val runsBefore = phase.runsBefore
orderRequirements.update(phase.phaseName, (runsAfter, runsBefore))
}
// propagate ordering constraint : reflexivity
pluginPhases.foreach { phase =>
var (runsAfter, runsBefore) = orderRequirements(phase.phaseName)
// propagate transitive constraints to related phases
runsAfter.filter(!isInserted(_)).foreach { phaseName =>
val (runsAfter1, runsBefore1) = orderRequirements(phaseName)
orderRequirements.update(phaseName, (runsAfter1, runsBefore1 + phase.phaseName))
}
runsBefore.filter(!isInserted(_)).foreach { phaseName =>
val (runsAfter1, runsBefore1) = orderRequirements(phaseName)
orderRequirements.update(phaseName, (runsAfter1 + phase.phaseName, runsBefore1))
}
}
debug(
s""" reflexive constraints:
| ${orderRequirements.mkString("\n")}
""".stripMargin
)
// propagate constraints from related phases to current phase: transitivity
def propagate(phase: Phase): OrderingReq = {
def propagateRunsBefore(beforePhase: String): Set[String] =
if (beforePhase == phase.phaseName)
throw new Exception(constraintConflict(phase))
else if (isInserted(beforePhase))
Set(beforePhase)
else {
val (_, runsBefore) = orderRequirements(beforePhase)
runsBefore.flatMap(propagateRunsBefore) + beforePhase
}
def propagateRunsAfter(afterPhase: String): Set[String] =
if (afterPhase == phase.phaseName)
throw new Exception(constraintConflict(phase))
else if (isInserted(afterPhase))
Set(afterPhase)
else {
val (runsAfter, _) = orderRequirements(afterPhase)
runsAfter.flatMap(propagateRunsAfter) + afterPhase
}
var (runsAfter, runsBefore) = orderRequirements(phase.phaseName)
runsAfter = runsAfter.flatMap(propagateRunsAfter)
runsBefore = runsBefore.flatMap(propagateRunsBefore)
(runsAfter, runsBefore)
}
pluginPhases.sortBy(_.phaseName).foreach { phase =>
var (runsAfter1, runsBefore1) = propagate(phase)
debug(
s"""propagated constraints for ${phase}:
|after: ${runsAfter1.mkString("[", ", ", "]")}
|before: ${runsBefore1.mkString("[", ", ", "]")}
""".stripMargin
)
var runsAfter = runsAfter1 & insertedPhase
val runsBefore = runsBefore1 & insertedPhase
// runsBefore met after the split
val (before, after) = updatedPlan.span { ps =>
val phases = ps.map(_.phaseName)
val runsAfterSat = runsAfter.isEmpty
runsAfter = runsAfter -- phases
// Prefer the point immediately before the first runsBefore.
// If runsBefore not specified, insert at the point immediately
// after the last afterPhases.
!phases.exists(runsBefore.contains) &&
!(runsBefore.isEmpty && runsAfterSat)
}
// check runsAfter
// error can occur if: a < b, b < c, c < a
after.foreach { ps =>
val phases = ps.map(_.phaseName)
if (phases.exists(runsAfter)) // afterReq satisfied
throw new Exception(s"Ordering conflict for phase ${phase.phaseName}")
}
insertedPhase = insertedPhase + phase.phaseName
updatedPlan = before ++ (List(phase) :: after)
}
updatedPlan
}
}