-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathHoverProvider.scala
254 lines (231 loc) · 9.1 KB
/
HoverProvider.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
package dotty.tools.pc
import java.util as ju
import scala.meta.internal.metals.Report
import scala.meta.internal.metals.ReportContext
import scala.meta.internal.pc.ScalaHover
import scala.meta.pc.ContentType
import scala.meta.pc.HoverSignature
import scala.meta.pc.OffsetParams
import scala.meta.pc.SymbolSearch
import dotty.tools.dotc.ast.tpd.*
import dotty.tools.dotc.core.Constants.*
import dotty.tools.dotc.core.Contexts.*
import dotty.tools.dotc.core.Flags.*
import dotty.tools.dotc.core.Names.*
import dotty.tools.dotc.core.StdNames.*
import dotty.tools.dotc.core.Symbols.*
import dotty.tools.dotc.core.Types.*
import dotty.tools.dotc.interactive.Interactive
import dotty.tools.dotc.interactive.InteractiveDriver
import dotty.tools.dotc.util.SourceFile
import dotty.tools.dotc.util.SourcePosition
import dotty.tools.pc.printer.ShortenedTypePrinter
import dotty.tools.pc.printer.ShortenedTypePrinter.IncludeDefaultParam
import dotty.tools.pc.utils.InteractiveEnrichments.*
import dotty.tools.dotc.ast.untpd.InferredTypeTree
import dotty.tools.dotc.core.StdNames
object HoverProvider:
def hover(
params: OffsetParams,
driver: InteractiveDriver,
search: SymbolSearch,
contentType: ContentType
)(implicit reportContext: ReportContext): ju.Optional[HoverSignature] =
val uri = params.uri().nn
val text = params.text().nn
val sourceFile = SourceFile.virtual(uri, text)
driver.run(uri, sourceFile)
val unit = driver.compilationUnits.get(uri)
given ctx: Context =
val ctx = driver.currentCtx
unit.map(ctx.fresh.setCompilationUnit).getOrElse(ctx)
val pos = driver.sourcePosition(params)
val path = unit
.map(unit => Interactive.pathTo(unit.tpdTree, pos.span))
.getOrElse(Interactive.pathTo(driver.openedTrees(uri), pos))
val indexedContext = IndexedContext(pos)(using ctx)
def typeFromPath(path: List[Tree]) =
if path.isEmpty then NoType else path.head.typeOpt
val tp = typeFromPath(path)
val tpw = tp.widenTermRefExpr
// For expression we need to find all enclosing applies to get the exact generic type
val enclosing = path.expandRangeToEnclosingApply(pos)
if tp.isError || tpw == NoType || tpw.isError || path.isEmpty
then
def report =
val posId =
if path.isEmpty || !path.head.sourcePos.exists
then pos.start
else path.head.sourcePos.start
Report(
"empty-hover-scala3",
s"""|$uri
|pos: ${pos.toLsp}
|
|tp: $tp
|has error: ${tp.isError}
|
|tpw: $tpw
|has error: ${tpw.isError}
|
|path:
|- ${path.map(_.toString()).mkString("\n- ")}
|trees:
|- ${unit
.map(u => List(u.tpdTree))
.getOrElse(driver.openedTrees(uri).map(_.tree))
.map(_.toString()).mkString("\n- ")}
|""".stripMargin,
s"$uri::$posId"
)
end report
reportContext.unsanitized.create(report, ifVerbose = true)
ju.Optional.empty().nn
else
val skipCheckOnName =
!pos.isPoint // don't check isHoveringOnName for RangeHover
val printerCtx = Interactive.contextOfPath(path)
val printer = ShortenedTypePrinter(search, IncludeDefaultParam.Include)(
using IndexedContext(pos)(using printerCtx)
)
MetalsInteractive.enclosingSymbolsWithExpressionType(
enclosing,
pos,
indexedContext,
skipCheckOnName
) match
case Nil =>
fallbackToDynamics(path, printer, contentType)
case (symbol, tpe, _) :: _
if symbol.name == nme.selectDynamic || symbol.name == nme.applyDynamic =>
fallbackToDynamics(path, printer, contentType)
case symbolTpes @ ((symbol, tpe, None) :: _) =>
val exprTpw = tpe.widenTermRefExpr.deepDealias
val hoverString =
tpw match
// https://github.com/scala/scala3/issues/8891
case tpw: ImportType =>
printer.hoverSymbol(symbol, symbol.paramRef)
case _ =>
val (tpe, sym) =
if symbol.isType then (symbol.typeRef, symbol)
else enclosing.head.seenFrom(symbol)
val finalTpe =
if tpe != NoType then tpe
else tpw
printer.hoverSymbol(sym, finalTpe.deepDealias)
end match
end hoverString
val docString = symbolTpes
.flatMap(symTpe => search.symbolDocumentation(symTpe._1, contentType))
.map(_.docstring())
.mkString("\n")
val expresionTypeOpt =
if symbol.name == StdNames.nme.??? then
InferExpectedType(search, driver, params).infer()
else printer.expressionType(exprTpw)
expresionTypeOpt match
case Some(expressionType) =>
val forceExpressionType =
!pos.span.isZeroExtent || (
!hoverString.endsWith(expressionType) &&
!symbol.isType &&
!symbol.is(Module) &&
!symbol.flags.isAllOf(EnumCase)
)
ju.Optional.of(
new ScalaHover(
expressionType = Some(expressionType),
symbolSignature = Some(hoverString),
docstring = Some(docString),
forceExpressionType = forceExpressionType,
contextInfo = printer.getUsedRenamesInfo,
contentType = contentType
)
).nn
case _ =>
ju.Optional.empty().nn
end match
case (_, tpe, Some(namedTupleArg)) :: _ =>
val exprTpw = tpe.widenTermRefExpr.deepDealias
printer.expressionType(exprTpw) match
case Some(tpe) =>
ju.Optional.of(
new ScalaHover(
expressionType = Some(tpe),
symbolSignature = Some(s"$namedTupleArg: $tpe"),
docstring = None,
forceExpressionType = false,
contextInfo = printer.getUsedRenamesInfo,
contentType = contentType
)
).nn
case _ => ju.Optional.empty().nn
end match
end if
end hover
extension (pos: SourcePosition)
private def isPoint: Boolean = pos.start == pos.end
private def fallbackToDynamics(
path: List[Tree],
printer: ShortenedTypePrinter,
contentType: ContentType
)(using Context): ju.Optional[HoverSignature] = path match
case SelectDynamicExtractor(sel, n, name, rest) =>
def findRefinement(tp: Type): Option[HoverSignature] =
tp match
case RefinedType(_, refName, tpe) if (name == refName.toString() || refName.toString() == nme.Fields.toString()) =>
val resultType =
rest match
case Select(_, asInstanceOf) :: TypeApply(_, List(tpe)) :: _ if asInstanceOf == nme.asInstanceOfPM =>
tpe.tpe.widenTermRefExpr.deepDealias
case _ if n == nme.selectDynamic => tpe.resultType
case _ => tpe
val tpeString =
if n == nme.selectDynamic then s": ${printer.tpe(resultType)}"
else printer.tpe(resultType)
val valOrDef =
if refName.toString() == nme.Fields.toString() then ""
else if n == nme.selectDynamic && !tpe.isInstanceOf[ExprType]
then "val "
else "def "
Some(
new ScalaHover(
expressionType = Some(tpeString),
symbolSignature = Some(s"$valOrDef$name$tpeString"),
contextInfo = printer.getUsedRenamesInfo,
contentType = contentType
)
)
case RefinedType(parent, _, _) =>
findRefinement(parent)
case _ => None
val refTpe = sel.typeOpt.widen.deepDealias match
case r: RefinedType => Some(r)
case t: (TermRef | TypeProxy) => Some(t.termSymbol.info.deepDealias)
case _ => None
refTpe.flatMap(findRefinement).asJava
case _ =>
ju.Optional.empty().nn
end HoverProvider
object SelectDynamicExtractor:
def unapply(path: List[Tree])(using Context) =
path match
// tests `structural-types` and `structural-types1` in HoverScala3TypeSuite
case Select(_, _) :: Apply(
Select(Apply(reflSel, List(sel)), n),
List(Literal(Constant(name: String)))
) :: rest
if (n == nme.selectDynamic || n == nme.applyDynamic) &&
nme.reflectiveSelectable == reflSel.symbol.name =>
Some(sel, n, name, rest)
// tests `selectable`, `selectable2` and `selectable-full` in HoverScala3TypeSuite
case Select(_, _) :: Apply(
Select(sel, n),
List(Literal(Constant(name: String)))
) :: rest if n == nme.selectDynamic || n == nme.applyDynamic =>
Some(sel, n, name, rest)
case _ => None
end match
end unapply
end SelectDynamicExtractor