This repository has been archived by the owner on Sep 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
CompilationUnitDependencies.scala
347 lines (283 loc) · 11 KB
/
CompilationUnitDependencies.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
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
* Copyright 2005-2010 LAMP/EPFL
*/
package scala.tools.refactoring
package analysis
import scala.tools.refactoring.common.CompilerApiExtensions
trait CompilationUnitDependencies extends CompilerApiExtensions with ScalaVersionAdapters.CompilerApiAdapters {
// we need to interactive compiler because we work with RangePositions
this: common.InteractiveScalaCompiler with common.TreeTraverser with common.TreeExtractors with common.PimpedTrees =>
import global._
def isQualifierDefaultImported(t: Tree) = t match {
case t: Select =>
val Scala = newTypeName("scala")
t.qualifier match {
case Select(This(Scala), _) => true
case qual if qual.nameString == "ClassTag" => true
case q => q.symbol.isOmittablePrefix
}
case _ => false
}
/**
* Helper function to filter out trees that we don't need
* to import, for example because they come from Predef.
*/
def isImportReallyNeeded(t: Select) = {
val lastSymbol = t.filter(_ => true).last.symbol
if(lastSymbol != NoSymbol && lastSymbol.isLocal) {
// Our import "chain" starts from a local value,
// so we cannot import `t` globally.
false
} else {
!isQualifierDefaultImported(t)
}
}
/**
* Finds the last "visible" (with a range position) select in some tree selection.
*
* Selects are usually only partly written down in source code (except when we write
* down the full name to some identifier), so there exists a select at which the tree
* turns from being visible to being invisible. We need to find this tree to determine
* whether we need do make an import with the minimally required path.
*
* This function also already filters trees that we don't need to import, e.g. from the
* Predef or the scala package.
*/
def findDeepestNeededSelect(t: Tree): Option[Select] = t match {
case selected @ Select(qual @ Select(underlying, _), _) if qual.symbol.isPackageObject && underlying.pos.isRange =>
/* When importing from a package object, e.g. scala.sys.`package`.error, the `package` select
* doesn't have a position. So we "skip" this package object and continue with the underlying
* select, which might again reveal a range position.
*/
findDeepestNeededSelect(underlying)
case s @ Select(qual, name) if s.pos.isRange && !qual.pos.isOpaqueRange =>
Some(s)
case s: Select =>
findDeepestNeededSelect(s.qualifier)
case _ =>
None
}
/**
* Calculates a list of all needed imports for the given Tree.
*/
def neededImports(t: Tree): List[Select] = {
val deps = dependencies(t)
val neededDependencies = deps.flatMap {
case t: Select if !t.pos.isRange => Some(t)
case t => findDeepestNeededSelect(t)
}.filter(isImportReallyNeeded).distinct
// Eliminate duplicates by converting them to strings.
neededDependencies.groupBy(asSelectorString).map(_._2.head).toList filterNot (_.symbol == t.symbol)
}
/**
* Calculates all the external dependencies the given Tree has.
* Compared to `neededImports`, this function might also return
* trees that don't need to be explicitly imported, for example
* because they are defined in the same compilation unit.
*/
def dependencies(t: Tree): List[Select] = {
val wholeTree = t
def qualifierIsEnclosingPackage(t: Select) = {
enclosingPackage(wholeTree, t.pos) match {
case pkgDef: PackageDef =>
t.qualifier.nameString == pkgDef.nameString
case _ => false
}
}
def isDefinedLocally(t: Tree): Boolean = isSymDefinedLocally(t.symbol)
def isSymDefinedLocally(sym: Symbol): Boolean = wholeTree.exists {
case defTree: DefTree if sym == defTree.symbol => true
case _ => false
}
def isDefinedLocallyAndQualifiedWithEnclosingPackage(t: Select) = {
qualifierIsEnclosingPackage(t) && isDefinedLocally(t)
}
val result = new collection.mutable.HashMap[String, Select]
def addToResult(t1: Select) = {
val key = t1.toString
result.get(key) match {
case None =>
result += (key -> t1)
case Some(t2) =>
val lengthOfVisibleQualifiers1 = t1.filter(_.pos.isRange)
val lengthOfVisibleQualifiers2 = t2.filter(_.pos.isRange)
if(lengthOfVisibleQualifiers1.size < lengthOfVisibleQualifiers2.size) {
// If we have an imported type that is used with the full package
// name but also with the imported name, we keep the one without the
// package so we don't incorrectly remove the import.
result += (key -> t1)
}
}
}
val traverser = new TraverserWithFakedTrees {
var annotationTree: Option[Tree] = None
def traversingAnnotation() = annotationTree.isDefined
def tryFindTpeAndSymFor(ident: Ident) = {
Option(ident.tpe).map((_, ident.symbol)).orElse {
annotationTree.flatMap { tree =>
val name = ident.name
tree.collect {
case Literal(Constant(tpe @ TypeRef(_, sym, _))) if (sym.name == name) => (tpe, sym)
}.headOption
}
}
}
def isSelectFromInvisibleThis(t: Tree) = {
val isInTopLevelPackage = Set("java", "scala").contains _
t.exists {
case t: This if isInTopLevelPackage(t.qual.toString) =>
false
case t: This =>
!t.pos.isOpaqueRange
case _ => false
}
}
def foundPotentialTree(t: Tree) = {
t match {
case Select(Ident(name), _) if name startsWith nme.EVIDENCE_PARAM_PREFIX =>
()
case t: Select =>
addToResult(t)
case _ =>
()
}
}
def handleSelectFromImplicit(t: Tree) = {
val selects = t.find {
case t: Select =>
!isSelectFromInvisibleThis(t)
case _ => false
}
selects foreach foundPotentialTree
}
// we don't need to add a dependency for method calls where the receiver
// is explicit in the source code.
def isMethodCallFromExplicitReceiver(t: Select) = t match {
case Select(qual, nme.apply) =>
t.qualifier.pos.isRange
case t =>
t.qualifier.pos.isRange && t.symbol.isMethod &&
!(t.qualifier.pos.sameRange(t.pos) && t.qualifier.pos.isTransparent)
}
def hasStableQualifier(t: Select) = {
t.qualifier.symbol != null && (!t.qualifier.symbol.isTerm || t.qualifier.symbol.isStable)
}
val language = newTermName("language")
override def traverse(tree: Tree) = tree match {
// Always add the SIP 18 language imports as required until we can handle them properly
case Import(select @ Select(Ident(nme.scala_), `language`), feature) =>
feature foreach (selector => addToResult(Select(select, selector.name)))
case Import(_, _) => ()
case Select(Ident(Names.scala), _) => ()
case Select(Select(Ident(Names.scala), Names.pkg), _) => ()
case t: Template =>
// The primary constructor can have visible annotations even
// if its DefDef has an OffsetPosition.
t.primaryConstructor foreach {
case primaryConstructor: DefDef =>
handleAnnotations(primaryConstructor.symbol.annotations)
}
super.traverse(tree)
case t : ApplyImplicitView =>
val hasSelectFromNonPackageThis = t.fun exists {
case Select(ths: This, _) if !ths.symbol.isPackageClass =>
true
case _ =>
false
}
if(hasSelectFromNonPackageThis) {
// We can ignore this tree because it is selected from a
// non-package instance, so there's nothing useful to import.
} else {
t.fun find {
case t: Select =>
!isMethodCallFromExplicitReceiver(t) && !t.pos.isTransparent && hasStableQualifier(t)
case _ =>
false
} foreach foundPotentialTree
}
t.args foreach traverse
case t : ApplyToImplicitArgs =>
traverse(t.fun)
t.args foreach handleSelectFromImplicit
case Select(New(qual), _) =>
traverse(qual)
// workaround for SI-5064
case t @ Select(qual: This, _) if qual.pos.sameRange(t.pos) =>
()
// workaround for SI-5064
case t @ Select(qual: Select, nme.apply) if (qual.pos.isTransparent && t.pos.isOpaqueRange) || qual.pos.isOpaqueRange =>
if(hasStableQualifier(qual) && !isSelectFromInvisibleThis(qual.qualifier)) {
addToResult(qual)
}
case t @ Select(qual, _) if t.pos.isOpaqueRange =>
if (!isMethodCallFromExplicitReceiver(t)
&& !isSelectFromInvisibleThis(qual)
&& t.name != nme.WILDCARD
&& hasStableQualifier(t)
&& !isDefinedLocallyAndQualifiedWithEnclosingPackage(t)) {
addToResult(t)
}
super.traverse(t)
// workaround for Assembla ticket #1002402
case t @ ValDef(modifiers, _, tpe: TypeTree, rhs) if modifiers.isLazy =>
tpe.original match {
case s @ Select(qualifier, _) =>
addToResult(s)
super.traverse(rhs)
case _ => super.traverse(t)
}
/*
* classOf[some.Type] is represented by a Literal
* */
case t @ Literal(c @ Constant(value)) =>
value match {
case tpe @ TypeRef(_, sym, _) =>
fakeSelectTreeFromType(tpe, sym, t.pos) match {
case s: Select if !isDefinedLocallyAndQualifiedWithEnclosingPackage(s) =>
addToResult(s)
case _ => ()
}
case _ => ()
}
case t: Ident if t.name != nme.EMPTY_PACKAGE_NAME =>
tryFindTpeAndSymFor(t) match {
case Some((tpe, sym)) =>
fakeSelectTree(tpe, sym, t) match {
// only repeat if it's a Select, if it's an Ident,
// otherwise we risk to loop endlessly
case select: Select =>
traverse(select)
case _ =>
super.traverse(tree)
}
case _ =>
super.traverse(tree)
}
case t: Ident => {
super.traverse(tree)
}
case _ =>
super.traverse(tree)
}
override def handleAnnotations(as: List[AnnotationInfo]) {
val recusing = annotationTree.isDefined
if (!recusing) {
try {
as.foreach { a =>
val tree = annotationInfoTree(a)
val orig = a.original
annotationTree = Some(tree)
traverse(orig)
}
} finally {
annotationTree = None
}
}
}
}
traverser.traverse(t)
val deps = result.values.toList
deps.filterNot(_.symbol.isPackage).toList
}
}