-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLSP.scala
More file actions
363 lines (325 loc) · 11 KB
/
LSP.scala
File metadata and controls
363 lines (325 loc) · 11 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import langoustine.lsp.*
import cats.effect.*
import jsonrpclib.fs2.*
import fs2.io.file.Files
import fs2.text
import fs2.io.file.Path
import cats.parse.Parser
import QuickmaffsCompiler.CompileError
import QuickmaffsCompiler.Index
import langoustine.lsp.runtime.DocumentUri
import langoustine.lsp.runtime.Opt
import langoustine.lsp.runtime.uinteger
import cats.syntax.all.*
import langoustine.lsp.app.LangoustineApp
import langoustine.lsp.tools.SemanticTokensEncoder
import langoustine.lsp.tools.SemanticToken
import cats.effect.std.Semaphore
object LSP extends LangoustineApp:
import QuickmaffsLSP.{server, State}
def server(
args: List[String]
): Resource[cats.effect.IO, LSPBuilder[cats.effect.IO]] =
Resource
.eval(IO.ref(Map.empty[DocumentUri, State]))
.map { state =>
QuickmaffsLSP.server(state)
}
.onFinalize(IO.consoleForIO.errorln("Terminating server"))
end LSP
object QuickmaffsLSP:
import requests.*
import aliases.*
import enumerations.*
import structures.*
enum State:
case Empty
case InvalidCode(err: QuickmaffsParser.ParsingError)
case InvalidProgram(errors: Vector[CompileError])
case RuntimeError(error: QuickmaffsEvaluator.EvaluationError)
case Ok(
idx: Index,
interpreted: Map[String, Int],
program: Program[WithSpan]
)
end State
extension (s: cats.parse.Caret)
def toPosition: Position =
Position(line = s.line, character = s.col)
extension (s: Span)
def toRange: Range = Range(s.from.toPosition, s.to.toPosition)
extension (s: Position)
def toCaret = cats.parse.Caret(s.line.value, s.character.value, -1)
def server(state: Ref[IO, Map[DocumentUri, State]]) =
import QuickmaffsCompiler.*
def process(s: String) =
QuickmaffsParser.parse(s) match
case Left(e) => State.InvalidCode(e)
case Right(parsed) =>
compile(parsed) match
case Left(errs) => State.InvalidProgram(errs)
case Right(idx) =>
QuickmaffsEvaluator.evaluate(parsed) match
case Left(err) => State.RuntimeError(err)
case Right(ok) => State.Ok(idx, ok, parsed)
end process
def processFile(path: Path) =
Files[IO].readAll(path).through(text.utf8.decode).compile.string.map {
contents =>
process(contents)
}
def processUri(uri: DocumentUri) =
val path = uri.value.drop("file://".length)
processFile(Path(path))
def set(u: DocumentUri)(st: State) =
state.update(_.updated(u, st)) <* IO.consoleForIO.errorln(
s"State update: $u is set to ${st.getClass}"
)
def get(u: DocumentUri) =
state.get.map(_.get(u))
def recompile(uri: DocumentUri, back: Communicate[IO]) =
def publish(vec: Vector[Diagnostic]) =
back.notification(
textDocument.publishDiagnostics,
PublishDiagnosticsParams(uri, diagnostics = vec)
)
processUri(uri)
.flatTap(set(uri))
.flatTap {
case _: State.Ok | State.Empty => publish(Vector.empty)
case State.InvalidProgram(errs) =>
val diags = errs.map { case CompileError(span, msg) =>
Diagnostic(
range = span.toRange,
message = msg,
severity = Some(DiagnosticSeverity.Error)
)
}
publish(diags)
case State.InvalidCode(parseError) =>
publish(
Vector(
Diagnostic(
range = Span(parseError.caret, parseError.caret).toRange,
message = "Parsing failed",
severity = Some(DiagnosticSeverity.Error)
)
)
)
case State.RuntimeError(err) =>
val zero = 0
publish(
Vector(
Diagnostic(
range = Range(Position(zero, zero), Position(zero, zero)),
message = s"Runtime: ${err.message}",
severity = Some(DiagnosticSeverity.Error)
)
)
)
}
.void
end recompile
def variableUnderCursor(doc: DocumentUri, position: Position) =
get(doc).map {
case Some(State.Ok(idx, _, _)) =>
idx.variables
.find { case (name, vdf) =>
vdf.references.exists(_.contains(position.toCaret))
}
case _ => None
}
val encoder = SemanticTokensEncoder(
tokenTypes = Vector(
SemanticTokenTypes.variable,
SemanticTokenTypes.number,
SemanticTokenTypes.operator
),
modifiers = Vector.empty
)
LSPBuilder
.create[IO]
.handleRequest(initialize) { (in, back) =>
back.notification(
window.showMessage,
ShowMessageParams(
message = "Hello from Quickmaffs",
`type` = enumerations.MessageType.Info
)
) *>
IO {
InitializeResult(
ServerCapabilities(
hoverProvider = Some(true),
definitionProvider = Some(true),
documentSymbolProvider = Some(true),
renameProvider = Some(true),
semanticTokensProvider = Some(
SemanticTokensOptions(
legend = encoder.legend,
full = Some(true)
)
),
textDocumentSync = Some(
TextDocumentSyncOptions(
openClose = Some(true),
save = Some(true)
)
)
),
Some(
InitializeResult
.ServerInfo(name = "Quickmaffs LSP", version = Some("0.0.1"))
)
)
}
}
.handleNotification(textDocument.didOpen) { (in, back) =>
recompile(in.textDocument.uri, back)
}
.handleNotification(textDocument.didSave) { (in, back) =>
recompile(in.textDocument.uri, back)
}
.handleRequest(textDocument.semanticTokens.full) { (in, back) =>
get(in.textDocument.uri).flatMap {
case Some(State.Ok(idx, values, program)) =>
val tokens = Vector.newBuilder[SemanticToken]
program.statements.map(_.value).foreach { st =>
st match
case Statement.Ass(name, e) =>
inline def nameToken(tok: Expr.Name[WithSpan]) =
tokenFromSpan(tok.value.span, SemanticTokenTypes.variable)
inline def tokenFromSpan(
span: Span,
tpe: SemanticTokenTypes
) =
SemanticToken.fromRange(
span.toRange,
tokenType = tpe
)
tokens += nameToken(name)
def go(expr: Expr[WithSpan]): Unit =
expr match
case Expr.Add(l, r, operator) =>
go(l)
go(r)
tokens += tokenFromSpan(
operator.span,
SemanticTokenTypes.operator
)
case Expr.Mul(l, r, operator) =>
go(l)
go(r)
tokens += tokenFromSpan(
operator.span,
SemanticTokenTypes.operator
)
case n @ Expr.Name(_) =>
tokens += nameToken(n)
case Expr.Lit(value) =>
tokens += tokenFromSpan(
value.span,
SemanticTokenTypes.number
)
go(e)
}
IO.consoleForIO
.errorln(
s"Sending over the following tokens: ${tokens.result().map(_.toString)}"
) *>
IO.fromEither(encoder.encode(tokens.result())).map(Some(_))
case other =>
IO.consoleForIO
.errorln(
s"Got weird state for ${in.textDocument.uri}: $other"
)
.as(Opt.empty)
}
}
.handleRequest(textDocument.definition) { (in, back) =>
variableUnderCursor(in.textDocument.uri, in.position).map {
foundMaybe =>
foundMaybe
.map(_._2)
.map { vdf =>
Some(
Definition(
Location(in.textDocument.uri, vdf.definedAt.toRange)
)
)
}
.getOrElse(Opt.empty)
}
}
.handleRequest(textDocument.hover) { (in, back) =>
get(in.textDocument.uri).map {
case Some(State.Ok(idx, values, program)) =>
idx.variables
.find { case (name, vdf) =>
vdf.references.exists(_.contains(in.position.toCaret))
}
.map { case (varName, vdf) =>
val value = values(varName)
val text = program.text.slice(
vdf.fullDefinition.from.offset,
vdf.fullDefinition.to.offset
)
Opt {
Hover(
MarkupContent(
kind = MarkupKind.Markdown,
s"""
|`$varName`
|---
|
|**Value**: $value
|
|**Formula**: $text
""".stripMargin.trim
)
)
}
}
.getOrElse(Opt.empty)
case _ => Opt.empty
}
}
.handleRequest(textDocument.documentSymbol) { (in, back) =>
get(in.textDocument.uri).map {
case Some(State.Ok(idx, _, _)) =>
Opt {
idx.variables.toVector.sortBy(_._1).map { case (n, df) =>
SymbolInformation(
location =
Location(in.textDocument.uri, df.definedAt.toRange),
name = n,
kind = enumerations.SymbolKind.Variable
)
}
}
case _ => Some(Vector.empty)
}
}
.handleRequest(textDocument.rename) { (in, back) =>
variableUnderCursor(in.textDocument.uri, in.position).map {
foundMaybe =>
foundMaybe
.map { case (oldName, vdf) =>
val edits = (vdf.definedAt +: vdf.references).map { span =>
TextEdit(range = span.toRange, newText = in.newName)
}
Opt {
WorkspaceEdit(
changes = Some(
Map(
in.textDocument.uri -> edits
)
)
)
}
}
.getOrElse(None)
}
}
end server
end QuickmaffsLSP