firefly-compiler 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/.firefly-workspace +1 -0
  2. package/.vscode/settings.json +5 -0
  3. package/LICENSE.txt +21 -0
  4. package/README.md +96 -0
  5. package/bin/firefly.mjs +2 -0
  6. package/compiler/.firefly/package.ff +1 -0
  7. package/compiler/Builder.ff +218 -0
  8. package/compiler/Compiler.ff +241 -0
  9. package/compiler/Dependencies.ff +179 -0
  10. package/compiler/Deriver.ff +647 -0
  11. package/compiler/Dictionaries.ff +205 -0
  12. package/compiler/Environment.ff +166 -0
  13. package/compiler/Inference.ff +1117 -0
  14. package/compiler/JsEmitter.ff +861 -0
  15. package/compiler/JsImporter.ff +56 -0
  16. package/compiler/LspHook.ff +188 -0
  17. package/compiler/Main.ff +237 -0
  18. package/compiler/Parser.ff +1383 -0
  19. package/compiler/Patterns.ff +111 -0
  20. package/compiler/Resolver.ff +620 -0
  21. package/compiler/Substitution.ff +178 -0
  22. package/compiler/Syntax.ff +299 -0
  23. package/compiler/Token.ff +180 -0
  24. package/compiler/Tokenizer.ff +278 -0
  25. package/compiler/Unification.ff +220 -0
  26. package/compiler/Wildcards.ff +50 -0
  27. package/compiler/Workspace.ff +88 -0
  28. package/core/.firefly/package.ff +2 -0
  29. package/core/Any.ff +30 -0
  30. package/core/Array.ff +249 -0
  31. package/core/AssetSystem.ff +61 -0
  32. package/core/Atomic.ff +64 -0
  33. package/core/Bool.ff +13 -0
  34. package/core/BrowserSystem.ff +14 -0
  35. package/core/Buffer.ff +211 -0
  36. package/core/BuildSystem.ff +144 -0
  37. package/core/Channel.ff +131 -0
  38. package/core/Char.ff +18 -0
  39. package/core/Core.ff +58 -0
  40. package/core/Duration.ff +15 -0
  41. package/core/Equal.ff +52 -0
  42. package/core/Error.ff +20 -0
  43. package/core/FileHandle.ff +41 -0
  44. package/core/Float.ff +41 -0
  45. package/core/HttpClient.ff +84 -0
  46. package/core/Instant.ff +9 -0
  47. package/core/Int.ff +61 -0
  48. package/core/IntMap.ff +85 -0
  49. package/core/JsSystem.ff +66 -0
  50. package/core/JsValue.ff +240 -0
  51. package/core/List.ff +440 -0
  52. package/core/Lock.ff +144 -0
  53. package/core/Log.ff +24 -0
  54. package/core/Map.ff +126 -0
  55. package/core/NodeSystem.ff +88 -0
  56. package/core/Nothing.ff +1 -0
  57. package/core/Option.ff +133 -0
  58. package/core/Ordering.ff +157 -0
  59. package/core/Pair.ff +55 -0
  60. package/core/Path.ff +393 -0
  61. package/core/RbMap.ff +216 -0
  62. package/core/Serializable.ff +173 -0
  63. package/core/Set.ff +38 -0
  64. package/core/Show.ff +43 -0
  65. package/core/Stack.ff +263 -0
  66. package/core/Stream.ff +406 -0
  67. package/core/String.ff +175 -0
  68. package/core/StringMap.ff +85 -0
  69. package/core/Task.ff +138 -0
  70. package/core/Try.ff +81 -0
  71. package/core/Unit.ff +3 -0
  72. package/experimental/random/AltGeneric.ff +44 -0
  73. package/experimental/random/Async.ff +68 -0
  74. package/experimental/random/Buffer2.ff +77 -0
  75. package/experimental/random/Cat.ff +12 -0
  76. package/experimental/random/Dictionary.ff +52 -0
  77. package/experimental/random/Example.ff +46 -0
  78. package/experimental/random/Generic.ff +102 -0
  79. package/experimental/random/HappyEyeballs.ff +40 -0
  80. package/experimental/random/HashMap.ff +72 -0
  81. package/experimental/random/IfElseUnit.ff +9 -0
  82. package/experimental/random/InputOutput.ff +23 -0
  83. package/experimental/random/ListVsArray.ff +45 -0
  84. package/experimental/random/Main.ff +44 -0
  85. package/experimental/random/MapTest.ff +67 -0
  86. package/experimental/random/OldTaskSystem.ff +210 -0
  87. package/experimental/random/PatternTest.ff +39 -0
  88. package/experimental/random/Patterns.ff +226 -0
  89. package/experimental/random/ReadBytesTest.ff +10 -0
  90. package/experimental/random/RunLength.ff +65 -0
  91. package/experimental/random/Scrape.ff +51 -0
  92. package/experimental/random/Serialization.ff +217 -0
  93. package/experimental/random/SerializationTest.ff +46 -0
  94. package/experimental/random/Serializer.ff +36 -0
  95. package/experimental/random/StdInOutErr.ff +4 -0
  96. package/experimental/random/Symbols.ff +74 -0
  97. package/experimental/random/Tag.ff +49 -0
  98. package/experimental/random/Tensor.ff +52 -0
  99. package/experimental/random/Try.ff +56 -0
  100. package/experimental/random/Tsv.ff +9 -0
  101. package/experimental/random/TypesAreModules.ff +87 -0
  102. package/experimental/random/blueprints/Blueprint.ff +52 -0
  103. package/experimental/random/blueprints/Main.ff +11 -0
  104. package/experimental/random/blueprints/Pretty.ff +58 -0
  105. package/experimental/random/blueprints/User.ff +64 -0
  106. package/experimental/random/blueprintsystem/BlueprintSystem.ff +48 -0
  107. package/experimental/random/blueprintsystem/Deserialize.ff +53 -0
  108. package/experimental/random/blueprintsystem/ReadJs.ff +13 -0
  109. package/experimental/random/blueprintsystem/User.ff +2 -0
  110. package/experimental/random/kahrs/Kahrs.ff +112 -0
  111. package/experimental/random/kahrs/TestKahrs.ff +22 -0
  112. package/experimental/random/kahrs/TestMap.ff +18 -0
  113. package/experimental/random/streaming/Gzip.ff +3 -0
  114. package/experimental/random/streaming/Main.ff +34 -0
  115. package/experimental/random/streaming/S3Bucket.ff +11 -0
  116. package/experimental/random/streaming/Tar.ff +5 -0
  117. package/experimental/rhymeapp/Main.ff +81 -0
  118. package/experimental/rhymeapp/index.html +14 -0
  119. package/firefly.sh +5 -0
  120. package/fireflysite/Main.ff +13 -0
  121. package/httpserver/.firefly/package.ff +1 -0
  122. package/httpserver/HttpServer.ff +184 -0
  123. package/lsp/.firefly/package.ff +1 -0
  124. package/lsp/CompletionHandler.ff +814 -0
  125. package/lsp/Handler.ff +551 -0
  126. package/lsp/HoverHandler.ff +82 -0
  127. package/lsp/LanguageServer.ff +229 -0
  128. package/lsp/SignatureHelpHandler.ff +55 -0
  129. package/lsp/SymbolHandler.ff +167 -0
  130. package/output/js/ff/compiler/Builder.mjs +483 -0
  131. package/output/js/ff/compiler/Compiler.mjs +410 -0
  132. package/output/js/ff/compiler/Dependencies.mjs +388 -0
  133. package/output/js/ff/compiler/Deriver.mjs +1166 -0
  134. package/output/js/ff/compiler/Dictionaries.mjs +1305 -0
  135. package/output/js/ff/compiler/Environment.mjs +1005 -0
  136. package/output/js/ff/compiler/Inference.mjs +4264 -0
  137. package/output/js/ff/compiler/JsEmitter.mjs +5353 -0
  138. package/output/js/ff/compiler/JsImporter.mjs +262 -0
  139. package/output/js/ff/compiler/LspHook.mjs +789 -0
  140. package/output/js/ff/compiler/Main.mjs +1695 -0
  141. package/output/js/ff/compiler/Parser.mjs +4004 -0
  142. package/output/js/ff/compiler/Patterns.mjs +923 -0
  143. package/output/js/ff/compiler/Resolver.mjs +2303 -0
  144. package/output/js/ff/compiler/Substitution.mjs +1146 -0
  145. package/output/js/ff/compiler/Syntax.mjs +12430 -0
  146. package/output/js/ff/compiler/Token.mjs +3092 -0
  147. package/output/js/ff/compiler/Tokenizer.mjs +589 -0
  148. package/output/js/ff/compiler/Unification.mjs +1748 -0
  149. package/output/js/ff/compiler/Wildcards.mjs +604 -0
  150. package/output/js/ff/compiler/Workspace.mjs +683 -0
  151. package/output/js/ff/core/Any.mjs +139 -0
  152. package/output/js/ff/core/Array.mjs +594 -0
  153. package/output/js/ff/core/AssetSystem.mjs +270 -0
  154. package/output/js/ff/core/Atomic.mjs +186 -0
  155. package/output/js/ff/core/Bool.mjs +141 -0
  156. package/output/js/ff/core/BrowserSystem.mjs +122 -0
  157. package/output/js/ff/core/Buffer.mjs +467 -0
  158. package/output/js/ff/core/BuildSystem.mjs +320 -0
  159. package/output/js/ff/core/Channel.mjs +268 -0
  160. package/output/js/ff/core/Char.mjs +145 -0
  161. package/output/js/ff/core/Core.mjs +300 -0
  162. package/output/js/ff/core/Duration.mjs +112 -0
  163. package/output/js/ff/core/Equal.mjs +175 -0
  164. package/output/js/ff/core/Error.mjs +138 -0
  165. package/output/js/ff/core/FileHandle.mjs +164 -0
  166. package/output/js/ff/core/Float.mjs +214 -0
  167. package/output/js/ff/core/HttpClient.mjs +210 -0
  168. package/output/js/ff/core/Instant.mjs +105 -0
  169. package/output/js/ff/core/Int.mjs +254 -0
  170. package/output/js/ff/core/IntMap.mjs +282 -0
  171. package/output/js/ff/core/JsSystem.mjs +234 -0
  172. package/output/js/ff/core/JsValue.mjs +678 -0
  173. package/output/js/ff/core/List.mjs +2335 -0
  174. package/output/js/ff/core/Lock.mjs +322 -0
  175. package/output/js/ff/core/Log.mjs +159 -0
  176. package/output/js/ff/core/Map.mjs +358 -0
  177. package/output/js/ff/core/NodeSystem.mjs +288 -0
  178. package/output/js/ff/core/Nothing.mjs +100 -0
  179. package/output/js/ff/core/Option.mjs +1002 -0
  180. package/output/js/ff/core/Ordering.mjs +734 -0
  181. package/output/js/ff/core/Pair.mjs +318 -0
  182. package/output/js/ff/core/Path.mjs +768 -0
  183. package/output/js/ff/core/RbMap.mjs +1936 -0
  184. package/output/js/ff/core/Serializable.mjs +434 -0
  185. package/output/js/ff/core/Set.mjs +250 -0
  186. package/output/js/ff/core/Show.mjs +201 -0
  187. package/output/js/ff/core/Stack.mjs +595 -0
  188. package/output/js/ff/core/Stream.mjs +1300 -0
  189. package/output/js/ff/core/String.mjs +433 -0
  190. package/output/js/ff/core/StringMap.mjs +282 -0
  191. package/output/js/ff/core/Task.mjs +345 -0
  192. package/output/js/ff/core/Try.mjs +503 -0
  193. package/output/js/ff/core/Unit.mjs +103 -0
  194. package/package.json +29 -0
  195. package/postgresql/.firefly/include/package-lock.json +250 -0
  196. package/postgresql/.firefly/include/package.json +5 -0
  197. package/postgresql/.firefly/include/prepare.sh +2 -0
  198. package/postgresql/.firefly/package.ff +3 -0
  199. package/postgresql/Pg.ff +530 -0
  200. package/unsafejs/.firefly/package.ff +1 -0
  201. package/unsafejs/UnsafeJs.ff +19 -0
  202. package/vscode/.vscode/launch.json +18 -0
  203. package/vscode/.vscode/tasks.json +33 -0
  204. package/vscode/LICENSE.txt +21 -0
  205. package/vscode/Prepublish.ff +15 -0
  206. package/vscode/README.md +17 -0
  207. package/vscode/client/package-lock.json +544 -0
  208. package/vscode/client/package.json +22 -0
  209. package/vscode/client/src/extension.ts +64 -0
  210. package/vscode/client/tsconfig.json +12 -0
  211. package/vscode/icons/firefly-icon.png +0 -0
  212. package/vscode/icons/firefly-icon.svg +10 -0
  213. package/vscode/icons/firefly-logo-notext.png +0 -0
  214. package/vscode/icons/firefly-logo.png +0 -0
  215. package/vscode/language-configuration.json +39 -0
  216. package/vscode/package-lock.json +3623 -0
  217. package/vscode/package.json +144 -0
  218. package/vscode/snippets-none.json +1 -0
  219. package/vscode/snippets.json +241 -0
  220. package/vscode/syntaxes/firefly.tmLanguage.json +294 -0
  221. package/vscode/tsconfig.json +20 -0
@@ -0,0 +1,229 @@
1
+ import Handler
2
+
3
+ class LanguageServer(
4
+ mutable openFiles: Map[String, String]
5
+ )
6
+
7
+ data BadRequestException(reason: String)
8
+
9
+ capability Request(
10
+ headers: Map[String, String]
11
+ object: JsValue
12
+ )
13
+
14
+ capability RequestMessage(
15
+ id: Option[MessageId] // None when the request is a Notification Message
16
+ method: String
17
+ parameters: Map[String, JsValue]
18
+ )
19
+
20
+
21
+ main(system: NodeSystem) {
22
+ let fireflyPath = system.path(".")
23
+ let handler = Handler(fireflyPath, None, Map.empty(), [].toSet(), Map.empty(), Map.empty())
24
+ try {
25
+ mutable input = system.readStream()
26
+ let responseChannel: Channel[JsValue] = system.mainTask().channel()
27
+ system.mainTask().spawn {_ =>
28
+ while {True} {
29
+ let body = responseChannel.read()
30
+ let json = body.toJson(Some(" ")).toBuffer()
31
+ system.writeText("Content-Length: " + json.size() + "\r\n\r\n")
32
+ system.writeBuffer(json)
33
+ }
34
+ }
35
+ taskGroup(system.mainTask()) {spawn, abort =>
36
+ while {True} {
37
+ let requestPair = parseRequest(system, input)
38
+ input = requestPair.second
39
+ let request = requestPair.first
40
+ let message = parseRequestMessage(request.object)
41
+ spawn(message.id) {_ =>
42
+ if(message.method == "$/cancelRequest") {
43
+ abort(Some(parseMessageId(message.parameters.grab("id"))))
44
+ }
45
+ try {
46
+ handleRequestMessage(system, handler, message).each {body =>
47
+ responseChannel.write(body)
48
+ }
49
+ } catchAny {error =>
50
+ let problem = if(error.name() == "AbortError") {
51
+ Error(-32800, "Request cancelled")
52
+ } else {
53
+ Log.trace("ERROR: " + error.message())
54
+ Log.trace(error.stack())
55
+ Error(-32603, "Internal error")
56
+ }
57
+ message.id.each {id =>
58
+ responseChannel.write(makeResponseMessage(system.js(), id, problem))
59
+ }
60
+ } grab()
61
+ }
62
+ }
63
+ }
64
+ } catch {| BadRequestException(reason), error =>
65
+ Log.trace(reason)
66
+ } grab()
67
+ }
68
+
69
+ taskGroup[K: Order, R](
70
+ parentTask: Task,
71
+ groupBody: ((K, Task => Unit) => Task, K => Unit) => R
72
+ ): R {
73
+ let lock = parentTask.lock()
74
+ mutable tasks = [].toMap()
75
+ function spawn(key: K, body: Task => Unit): Task {
76
+ let body2 = {task =>
77
+ lock.do {tasks = tasks.add(key, task)}
78
+ try {
79
+ body(task)
80
+ } finally {
81
+ lock.do {tasks = tasks.remove(key)}
82
+ } grab()
83
+ }
84
+ parentTask.spawn(body2)
85
+ }
86
+ function abort(key: K): Unit {
87
+ lock.do {tasks.get(key).each {_.abort()}}
88
+ }
89
+ groupBody(spawn, abort)
90
+ }
91
+
92
+ parseRequest(system: NodeSystem, input: Stream[Buffer]): Pair[Request, Stream[Buffer]] {
93
+ let headersPair = parseRequestHeaders(input)
94
+ let headers = headersPair.first
95
+ let contentLength = headers
96
+ .get("content-length").else {throw(BadRequestException("'content-length' header is missing"))}
97
+ .getInt().else {throw(BadRequestException("Value for 'content-length' is not an integer"))}
98
+ let bodyPair = parseRequestBody(system.js(), contentLength, headersPair.second)
99
+ bodyPair.mapFirst {body => Request(headers, body)}
100
+ }
101
+
102
+ parseRequestHeaders(input: Stream[Buffer]): Pair[Map[String, String], Stream[Buffer]] {
103
+ let buffers = Stack.make()
104
+ mutable buffer = input.next().else {
105
+ throw(BadRequestException("End of input while parsing request headers"))
106
+ }
107
+ mutable offset = 0
108
+ mutable droppingInitialNewlines = True
109
+ mutable lastWasNewline = False
110
+ mutable done = False
111
+ while {!done} {
112
+ if(offset == buffer.size()) {
113
+ offset = 0
114
+ buffers.push(buffer)
115
+ buffer = input.next().else {
116
+ throw(BadRequestException("End of input while parsing request headers"))
117
+ }
118
+ }
119
+ let byte = buffer.grabUint8(offset)
120
+ if(droppingInitialNewlines && (byte == '\n'.codeUnit || byte == '\r'.codeUnit)) {
121
+ // Skip
122
+ } elseIf {byte == '\n'.codeUnit} {
123
+ if(lastWasNewline) {
124
+ done = True
125
+ } else {
126
+ lastWasNewline = True
127
+ }
128
+ } elseIf {byte != '\r'.codeUnit && lastWasNewline} {
129
+ lastWasNewline = False
130
+ } else {
131
+ droppingInitialNewlines = False
132
+ }
133
+ offset += 1
134
+ }
135
+ buffers.push(buffer.view(0, offset))
136
+ let headers = Buffer.fromBufferArray(buffers.drain()).toString()
137
+ let map = headers.lines().pairs().filter {_.second.size() != 0}.map {| Pair(i, line) =>
138
+ line.splitFirst(':').else {
139
+ throw(BadRequestException("Invalid header at line " + i + " '" + line + "'"))
140
+ }.mapFirst {_.lower()} //.mapSecond {_.trim()}
141
+ }.toMap()
142
+ Pair(map, [buffer.view(offset, buffer.size())].toStream().addAll(input))
143
+ }
144
+
145
+ parseRequestBody(js: JsSystem, contentLength: Int, input: Stream[Buffer]): Pair[JsValue, Stream[Buffer]] {
146
+ let bodyPair = try {
147
+ input.readBytes(contentLength) // Should Stream.readBytes return an option?
148
+ } catchAny {error =>
149
+ throw(BadRequestException("End of input while parsing request body"))
150
+ } grab()
151
+ let body = Buffer.fromBufferArray(bodyPair.first).toString()
152
+ let json = try {
153
+ js.parseJson(body)
154
+ } catchAny {error =>
155
+ throw(BadRequestException("Invalid JSON in request body: " + body))
156
+ } grab()
157
+ Pair(json, bodyPair.second)
158
+ }
159
+
160
+ parseRequestMessage(object: JsValue): RequestMessage {
161
+ let id = object.getOwn("id").map {parseMessageId(_)}
162
+
163
+ let method = object.getOwn("method").{
164
+ | None => throw(BadRequestException("Bad JSON-RPC, missing method"))
165
+ | Some(m) {!m.isString()} => throw(BadRequestException("Bad JSON-RPC method, string expected"))
166
+ | Some(m) => m.grabString()
167
+ }
168
+
169
+ let parameters = object.getOwn("params").{
170
+ | None => [].toMap()
171
+ | Some(o) {!o.isObject()} => throw(BadRequestException("Bad JSON-RPC params, object expected"))
172
+ | Some(o) => o.grabMap()
173
+ }
174
+
175
+ RequestMessage(id, method, parameters)
176
+ }
177
+
178
+ parseMessageId(id: JsValue): MessageId {
179
+ if(id.isInt()) {
180
+ MessageIdInt(id.grabInt())
181
+ } elseIf {id.isString()} {
182
+ MessageIdString(id.grabString())
183
+ } else {
184
+ throw(BadRequestException("Bad JSON-RPC id, int or string expected"))
185
+ }
186
+ }
187
+
188
+ handleRequestMessage(system: NodeSystem, handler: Handler, message: RequestMessage): Option[JsValue] {
189
+ try {
190
+ message.id.{
191
+ | None {message.method == "$/cancelRequest"} => // TODO: Needs to read ahead to cancel anything
192
+ handler.cancelledRequests = handler.cancelledRequests.add(
193
+ parseMessageId(message.parameters.grab("id"))
194
+ )
195
+ None
196
+ | None =>
197
+ handler.handleNotification(system, message.method, message.parameters)
198
+ None
199
+ | Some(id) {handler.cancelledRequests.contains(id)} =>
200
+ handler.cancelledRequests = handler.cancelledRequests.remove(id)
201
+ Some(makeResponseMessage(system.js(), id, Error(-32800, "Request cancelled")))
202
+ | Some(id) =>
203
+ let result = handler.handleRequest(system, message.method, message.parameters)
204
+ Some(makeResponseMessage(system.js(), id, result))
205
+ }
206
+ } catchAny {error =>
207
+ //system.files().writeText("lsp-failure.txt", error.name() + ": " + error.message())
208
+ error.rethrow()
209
+ } grab()
210
+ }
211
+
212
+ makeResponseMessage(js: JsSystem, id: MessageId, result: ResultOrError): JsValue {
213
+ let o = js.object()
214
+ o.set("jsonrpc", "2.0")
215
+ id.{
216
+ | MessageIdInt(id) => o.set("id", id)
217
+ | MessageIdString(id) => o.set("id", id)
218
+ }
219
+ result.{
220
+ | Result(result) =>
221
+ o.set("result", js.parseJson(result))
222
+ | Error(code, message) =>
223
+ let e = js.object()
224
+ e.set("code", code)
225
+ e.set("message", message)
226
+ o.set("error", e)
227
+ }
228
+ o
229
+ }
@@ -0,0 +1,55 @@
1
+ import LspHook from ff:compiler
2
+ import Unification from ff:compiler
3
+ import Environment from ff:compiler
4
+ import Syntax from ff:compiler
5
+ import Handler
6
+ import CompletionHandler
7
+
8
+ handleSignatureHelp(system: NodeSystem, lspHook: LspHook): JsValue {
9
+ let signatureAndUnification = lspHook.results().collectFirst {
10
+ | InferLookupHook h =>
11
+ let isMember = h.symbol.value.qualifiedName.contains("_")
12
+ h.instantiated.value.map {i =>
13
+ let signature = if(!isMember) {i.scheme.signature} else {
14
+ i.scheme.signature.Signature(parameters = i.scheme.signature.parameters.dropFirst())
15
+ }
16
+ Pair(signature, h.unification)
17
+ }
18
+ | _ => None
19
+ }
20
+ let js = system.js()
21
+ signatureAndUnification.map {| Pair(s, unification) =>
22
+ let shownTypes = [...s.parameters.map {_.valueType}, s.returnType].map {unification.substitute(_)}
23
+ let realGenerics = s.generics.filter {_ != "Q$"}
24
+ let generics = if(realGenerics.isEmpty()) {""} else {"[" + realGenerics.join(", ") + "]"}
25
+ // TODO only instantiate acording to self. Eg. Some("foo").map {...}
26
+ let parameters = s.parameters.map {p =>
27
+ CompletionHandler.showCompletionParameter("", p.Parameter(valueType = unification.substitute(p.valueType)))
28
+ }
29
+ let label =
30
+ s.name + generics + "(" + parameters.join(", ") + "): " + unification.substitute(s.returnType).show(shownTypes)
31
+ js.object()
32
+ .with("signatures", js.array([js.object()
33
+ .with("label", label)
34
+ .with("parameters", js.array([
35
+ ...parameters.map {p =>
36
+ js.object().with("label", p)
37
+ }
38
+ // Fake parameter to trick the client into remembering the call position
39
+ js.object().with("label", "/* Call " + lspHook.at.show() + " */")
40
+ ]))
41
+ ]))
42
+ .with("activeSignature", 0)
43
+ }.else {js.null()}
44
+ }
45
+
46
+ pickActiveParameter(help: JsValue, argumentIndex: Int, parameterName: Option[String]): JsValue {
47
+ parameterName.flatMap {name =>
48
+ let parameters = help.get("signatures").get(0).get("parameters").grabArray().toList()
49
+ parameters.pairs().collectFirst {| Pair(i, p) =>
50
+ if(name == p.get("label").grabString().takeWhile {_.isAsciiLetterOrDigit()}) {
51
+ help.with("activeParameter", i)
52
+ }
53
+ }
54
+ }.else {help.with("activeParameter", argumentIndex)}
55
+ }
@@ -0,0 +1,167 @@
1
+ import LspHook from ff:compiler
2
+ import Syntax from ff:compiler
3
+
4
+ data DocumentSymbol(
5
+ name: String
6
+ kind: Int
7
+ selectionStart: Location
8
+ selectionEnd: Location
9
+ start: Location
10
+ end: Location
11
+ children: List[DocumentSymbol]
12
+ )
13
+
14
+ data WorkspaceSymbol(
15
+ name: String
16
+ kind: Int
17
+ containerName: Option[String]
18
+ selectionStart: Location
19
+ selectionEnd: Location
20
+ )
21
+
22
+ class Result[T](
23
+ result: T
24
+ remaining: List[ResultHook]
25
+ )
26
+
27
+ data ReadSymbolsError()
28
+
29
+ readAllSymbols(hooks: List[ResultHook]): List[DocumentSymbol] {
30
+ let result = readSymbols(hooks)
31
+ if(!result.remaining.isEmpty()) {throw(ReadSymbolsError())}
32
+ result.result
33
+ }
34
+
35
+ readSymbols(hooks: List[ResultHook]): Result[List[DocumentSymbol]] {
36
+ | [ParseSymbolBegin, ...rest] =>
37
+ let symbol = readSymbol(rest)
38
+ let symbols = readSymbols(symbol.remaining)
39
+ Result([symbol.result, ...symbols.result], symbols.remaining)
40
+ | _ => Result([], hooks)
41
+ }
42
+
43
+ readSymbol(hooks: List[ResultHook]): Result[DocumentSymbol] {
44
+ let children = readSymbols(hooks)
45
+ children.remaining.{
46
+ | [ParseSymbolEnd(name, kind, selectionStart, selectionEnd, start, end), ...rest] =>
47
+ let symbol = DocumentSymbol(name, kind, selectionStart, selectionEnd, start, end, children.result)
48
+ Result(symbol, rest)
49
+ | _ => throw(ReadSymbolsError())
50
+ }
51
+ }
52
+
53
+ handleDocumentSymbol(system: NodeSystem, resultHooks: List[ResultHook]): List[JsValue] {
54
+ let symbols = readAllSymbols(resultHooks)
55
+ symbols.map {documentSymbolToLsp(system.js(), _)}
56
+ }
57
+
58
+ handleWorkspaceSymbol(system: NodeSystem, resultHooks: List[ResultHook], query: String): List[JsValue] {
59
+ let documentSymbols = readAllSymbols(resultHooks)
60
+ let workspaceSymbols = documentSymbols.flatMap {documentToWorkspaceSymbols(_, None)}
61
+ let foundSymbols = workspaceSymbols.filter {_.name.startsWith(query)}
62
+ //Log.trace("handleWorkspaceSymbol")
63
+ //workspaceSymbols.each {Log.show(_)}
64
+ let jsSymbols = foundSymbols.map {workspaceSymbolToLsp(system.js(), system.path("."), _)}
65
+ //workspaceSymbolsJs.each {Log.trace(_.toJson(None))}
66
+ jsSymbols
67
+ }
68
+
69
+ documentToWorkspaceSymbols(symbol: DocumentSymbol, parentName: Option[String]): List[WorkspaceSymbol] {
70
+ let s = WorkspaceSymbol(
71
+ symbol.name
72
+ kind = symbol.kind
73
+ containerName = parentName
74
+ selectionStart = symbol.selectionEnd
75
+ selectionEnd = symbol.selectionEnd
76
+ )
77
+ let children = symbol.children.flatMap {documentToWorkspaceSymbols(_, Some(symbol.name))}
78
+ [s, ... children]
79
+ }
80
+
81
+ showHook(lspHook: ResultHook): String {
82
+ | ParseSymbolBegin => "ParseSymbolBegin"
83
+ | ParseSymbolEnd(name, kind, _, _, _, _) => "ParseSymbolEnd("+Show.show(name)+", "+Show.show(kind)+")"
84
+ //| ParseSymbolBegin => "("
85
+ //| ParseSymbolEnd(name, kind, symbolStart, selectionStart, selectionEnd) => ") " + name + " " + showPosition(selectionStart) + " - " + showPosition(selectionEnd)
86
+ | _ => "other"
87
+ }
88
+
89
+ showPosition(at: Location): String {
90
+ at.line + ":" + at.column
91
+ }
92
+
93
+ documentSymbolToLsp(js: JsSystem, symbol: DocumentSymbol): JsValue {
94
+ js.object()
95
+ .with("name", symbol.name)
96
+ .with("kind", symbol.kind)
97
+ .with("range", locationsToLspRange(js, symbol.start, symbol.end))
98
+ .with("selectionRange", locationsToLspRange(js, symbol.selectionStart, symbol.selectionEnd))
99
+ .with("children", js.array(symbol.children.map {documentSymbolToLsp(js, _)}))
100
+ }
101
+
102
+ workspaceSymbolToLsp(js: JsSystem, rootPath: Path, symbol: WorkspaceSymbol): JsValue {
103
+ let o = js.object()
104
+ .with("name", symbol.name)
105
+ .with("kind", symbol.kind)
106
+ .with("location", js.object()
107
+ .with("uri", rootPath.path(symbol.selectionStart.file).url())
108
+ .with("range", locationsToLspRange(js, symbol.selectionStart, symbol.selectionEnd))
109
+ )
110
+ symbol.containerName.{
111
+ | Some(n) => o.with("containerName", n)
112
+ | None => o
113
+ }
114
+ }
115
+
116
+ locationsToLspRange(js: JsSystem, start: Location, end: Location): JsValue {
117
+ js.object()
118
+ .with("start", js.object()
119
+ .with("line", start.line - 1)
120
+ .with("character", start.column - 1)
121
+ )
122
+ .with("end", js.object()
123
+ .with("line", end.line - 1)
124
+ .with("character", end.column - 1)
125
+ )
126
+ }
127
+
128
+ symbolFilter(symbol: WorkspaceSymbol, query: String): Bool {
129
+ let symbolWords = splitCamelCased(symbol.name.takeWhile {_.isAsciiLetterOrDigit()})
130
+ matchSymbol(symbolWords, query)
131
+ }
132
+
133
+ matchSymbol(symbolWords: List[String], query: String): Bool {
134
+ let memo = IntMap.make()
135
+ function go(wordIndex: Int, queryOffset: Int): Bool {
136
+ memo.getOrSet(wordIndex) {IntMap.make()}.getOrSet(queryOffset):
137
+ if(queryOffset >= query.size()) {True} else:
138
+ if(wordIndex >= symbolWords.size()) {False} else:
139
+ prefixes(query.dropFirst(queryOffset)).any {prefix =>
140
+ symbolWords.grab(wordIndex).startsWith(prefix) &&
141
+ go(wordIndex + 1, queryOffset + prefix.size())
142
+ }
143
+ }
144
+ go(0, 0)
145
+ }
146
+
147
+ prefixes(string: String): List[String] {
148
+ if(string == "") {[""]} else:
149
+ function go(rest: String): List[String] {
150
+ if(rest == "") {
151
+ [""]
152
+ } else {
153
+ [rest, ...go(rest.dropLast())]
154
+ }
155
+ }
156
+ go(string.grab(0).toString().lower() + string.dropFirst().takeWhile {!_.isAsciiUpper()})
157
+ }
158
+
159
+ splitCamelCased(name: String): List[String] {
160
+ name.first().{
161
+ | None => []
162
+ | Some(c) =>
163
+ let word = c.toString().lower() + name.dropFirst().takeWhile {_.isAsciiLower()}
164
+ let rest = name.dropFirst(word.size())
165
+ [word, ...splitCamelCased(rest)]
166
+ }
167
+ }