-
Notifications
You must be signed in to change notification settings - Fork 217
/
CompiledFile.kt
193 lines (164 loc) · 8.54 KB
/
CompiledFile.kt
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
package org.javacs.kt
import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.com.intellij.psi.PsiIdentifier
import org.javacs.kt.position.changedRegion
import org.javacs.kt.position.position
import org.javacs.kt.util.findParent
import org.javacs.kt.util.nullResult
import org.javacs.kt.util.toPath
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.KotlinType
import java.nio.file.Paths
class CompiledFile(
val content: String,
val parse: KtFile,
val compile: BindingContext,
val container: ComponentProvider,
val sourcePath: Collection<KtFile>,
val classPath: CompilerClassPath,
val isScript: Boolean = false,
val kind: CompilationKind = CompilationKind.DEFAULT
) {
/**
* Find the type of the expression at `cursor`
*/
fun typeAtPoint(cursor: Int): KotlinType? {
var cursorExpr = parseAtPoint(cursor)?.findParent<KtExpression>() ?: return nullResult("Couldn't find expression at ${describePosition(cursor)}")
val surroundingExpr = expandForType(cursor, cursorExpr)
val scope = scopeAtPoint(cursor) ?: return nullResult("Couldn't find scope at ${describePosition(cursor)}")
return typeOfExpression(surroundingExpr, scope)
}
fun typeOfExpression(expression: KtExpression, scopeWithImports: LexicalScope): KotlinType? =
bindingContextOf(expression, scopeWithImports).getType(expression)
fun bindingContextOf(expression: KtExpression, scopeWithImports: LexicalScope): BindingContext =
classPath.compiler.compileExpression(expression, scopeWithImports, sourcePath, kind).first
private fun expandForType(cursor: Int, surroundingExpr: KtExpression): KtExpression {
val dotParent = surroundingExpr.parent as? KtDotQualifiedExpression
if (dotParent != null && dotParent.selectorExpression?.textRange?.contains(cursor) ?: false) {
return expandForType(cursor, dotParent)
}
else return surroundingExpr
}
fun referenceAtPoint(cursor: Int): Pair<KtExpression, DeclarationDescriptor>? {
val element = parseAtPoint(cursor)
var cursorExpr = element?.findParent<KtExpression>() ?: return nullResult("Couldn't find expression at ${describePosition(cursor)} (only found $element)")
val surroundingExpr = expandForReference(cursor, cursorExpr)
val scope = scopeAtPoint(cursor) ?: return nullResult("Couldn't find scope at ${describePosition(cursor)}")
val context = bindingContextOf(surroundingExpr, scope)
LOG.info("Hovering {}", surroundingExpr)
return referenceFromContext(cursor, context)
}
private fun referenceFromContext(cursor: Int, context: BindingContext): Pair<KtExpression, DeclarationDescriptor>? {
val targets = context.getSliceContents(BindingContext.REFERENCE_TARGET)
return targets.asSequence()
.filter { cursor in it.key.textRange }
.sortedBy { it.key.textRange.length }
.map { it.toPair() }
.firstOrNull()
}
private fun expandForReference(cursor: Int, surroundingExpr: KtExpression): KtExpression {
val parent: KtExpression? =
(surroundingExpr.parent as? KtDotQualifiedExpression)?.let { it as KtExpression } // foo.bar
?: (surroundingExpr.parent as? KtSafeQualifiedExpression)?.let { it as KtExpression } // foo?.bar
?: (surroundingExpr.parent as? KtCallExpression)?.let { it as KtExpression } // foo()
return parent?.let { expandForReference(cursor, it) } ?: surroundingExpr
}
/**
* Parse the expression at `cursor`
*/
fun parseAtPoint(cursor: Int): KtElement? {
val oldCursor = oldOffset(cursor)
val oldChanged = changedRegion(parse.text, content)?.first ?: TextRange(cursor, cursor)
val psi = parse.findElementAt(oldCursor) ?: return nullResult("Couldn't find anything at ${describePosition(cursor)}")
val oldParent = psi.parentsWithSelf
.filterIsInstance<KtDeclaration>()
.firstOrNull { it.textRange.contains(oldChanged) } ?: parse
LOG.debug { "PSI path: ${psi.parentsWithSelf.toList()}" }
var surroundingContent: String
var offset: Int
if (oldParent is KtClass) {
// Parsing class, currently only identifiers are supported
if (psi.node.elementType != KtTokens.IDENTIFIER) return null
// Parsing class name identifier: Use a fake property with the class name as type
// Otherwise the compiler/analyzer would throw an exception due to a missing TopLevelDescriptorProvider
val recoveryRange = psi.textRange
LOG.info("Re-parsing {}", describeRange(recoveryRange, true))
val prefix = "val x: "
surroundingContent = prefix + psi.text
offset = recoveryRange.startOffset - prefix.length
} else {
// Parsing some other expression
val recoveryRange = oldParent.textRange
LOG.info("Re-parsing {}", describeRange(recoveryRange, true))
surroundingContent = content.substring(recoveryRange.startOffset, content.length - (parse.text.length - recoveryRange.endOffset))
offset = recoveryRange.startOffset
if (!((oldParent as? KtParameter)?.hasValOrVar() ?: true)) {
// Prepend 'val' to (e.g. function) parameters
val prefix = "val "
surroundingContent = prefix + surroundingContent
offset -= prefix.length
}
}
val padOffset = " ".repeat(offset)
val recompile = classPath.compiler.createFile(padOffset + surroundingContent, Paths.get("dummy.virtual" + if (isScript) ".kts" else ".kt"), kind)
return recompile.findElementAt(cursor)?.findParent<KtElement>()
}
/**
* Get the typed, compiled element at `cursor`.
* This may be out-of-date if the user is typing quickly.
*/
fun elementAtPoint(cursor: Int): KtElement? {
val oldCursor = oldOffset(cursor)
val psi = parse.findElementAt(oldCursor) ?: return nullResult("Couldn't find anything at ${describePosition(cursor)}")
return psi.findParent<KtElement>()
}
/**
* Find the lexical-scope surrounding `cursor`.
* This may be out-of-date if the user is typing quickly.
*/
fun scopeAtPoint(cursor: Int): LexicalScope? {
val oldCursor = oldOffset(cursor)
return compile.getSliceContents(BindingContext.LEXICAL_SCOPE).asSequence()
.filter { it.key.textRange.startOffset <= oldCursor && oldCursor <= it.key.textRange.endOffset }
.sortedBy { it.key.textRange.length }
.map { it.value }
.firstOrNull()
}
fun lineBefore(cursor: Int): String = content.substring(0, cursor).substringAfterLast('\n')
fun lineAfter(cursor: Int): String = content.substring(cursor).substringBefore('\n')
private fun oldOffset(cursor: Int): Int {
val (oldChanged, newChanged) = changedRegion(parse.text, content) ?: return cursor
return when {
cursor <= newChanged.startOffset -> cursor
cursor < newChanged.endOffset -> {
val newRelative = cursor - newChanged.startOffset
val oldRelative = newRelative * oldChanged.length / newChanged.length
oldChanged.startOffset + oldRelative
}
else -> parse.text.length - (content.length - cursor)
}
}
fun describePosition(offset: Int, oldContent: Boolean = false): String {
val c = if (oldContent) parse.text else content
val pos = position(c, offset)
val file = parse.toPath().fileName
return "$file ${pos.line + 1}:${pos.character + 1}"
}
private fun describeRange(range: TextRange, oldContent: Boolean = false): String {
val c = if (oldContent) parse.text else content
val start = position(c, range.startOffset)
val end = position(c, range.endOffset)
val file = parse.toPath().fileName
return "$file ${start.line}:${start.character + 1}-${end.line + 1}:${end.character + 1}"
}
}
private fun fileName(file: KtFile): String {
val parts = file.name.split('/')
return parts.last()
}