Christophe Weblog Wiki Code Publications Music
implement swank:find-definitions-for-emacs
[swankr.git] / swank.R
1 ### This program is free software; you can redistribute it and/or
2 ### modify it under the terms of the GNU General Public Licence as
3 ### published by the Free Software Foundation; either version 2 of the
4 ### Licence, or (at your option) any later version.
5 ###
6 ### This program is distributed in the hope that it will be useful,
7 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
8 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 ### GNU General Public Licence for more details.
10 ###
11 ### A copy of version 2 of the GNU General Public Licence is available
12 ### at <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>; the
13 ### latest version of the GNU General Public Licence is available at
14 ### <http://www.gnu.org/licenses/gpl.txt>.
15
16 swank <- function(port=4005) {
17   acceptConnections(port, FALSE)
18 }
19
20 startSwank <- function(portFile) {
21   acceptConnections(FALSE, portFile)
22 }
23
24 acceptConnections <- function(port, portFile) {
25   s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
26   on.exit(close(s))
27   serve(s)
28 }
29
30 serve <- function(io) {
31   mainLoop(io)
32 }
33
34 mainLoop <- function(io) {
35   slimeConnection <- new.env()
36   slimeConnection$io <- io
37   while(TRUE) {
38     withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
39                           swankTopLevel=function(c) NULL),
40                  abort="return to SLIME's toplevel")
41   }
42 }
43
44 dispatch <- function(slimeConnection, event, sldbState=NULL) {
45   str(event)
46   kind <- event[[1]]
47   if(kind == quote(`:emacs-rex`)) {
48     do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
49   }
50 }
51
52 sendToEmacs <- function(slimeConnection, obj) {
53   io <- slimeConnection$io
54   str(obj)
55   payload <- writeSexpToString(obj)
56   writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
57   writeChar(payload, io, eos=NULL)
58   flush(io)
59   cat(sprintf("%06x", nchar(payload)), payload, sep="")
60 }
61
62 callify <- function(form) {
63   ## we implement here the conversion from Lisp S-expression (or list)
64   ## expressions of code into our own, swankr, calling convention,
65   ## with slimeConnection and sldbState as first and second arguments.
66   ## as.call() gets us part of the way, but we need to walk the list
67   ## recursively to mimic CL:EVAL; we need to avoid converting R
68   ## special operators which we are punning (only `quote`, for now)
69   ## into this calling convention.
70   if(is.list(form)) {
71     if(form[[1]] == quote(quote)) {
72       as.call(form)
73     } else {
74       as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
75     }
76   } else {
77     form
78   }
79 }
80
81 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
82   ok <- FALSE
83   value <- NULL
84   tryCatch({
85     withCallingHandlers({
86       call <- callify(form)
87       value <- eval(call)
88       ok <- TRUE
89     }, error=function(c) {
90       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
91       withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
92     finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
93 }
94
95 makeSldbState <- function(condition, level, id) {
96   calls <- rev(sys.calls())[-1]
97   frames <- rev(sys.frames())[-1]
98   restarts <- rev(computeRestarts(condition))[-1]
99   ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
100   class(ret) <- c("sldbState", class(ret))
101   ret
102 }
103
104 sldbLoop <- function(slimeConnection, sldbState, id) {
105   tryCatch({
106     io <- slimeConnection$io
107     sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
108     sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
109     while(TRUE) {
110       dispatch(slimeConnection, readPacket(io), sldbState)
111     }
112   }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
113 }
114
115 readPacket <- function(io) {
116   header <- readChunk(io, 6)
117   len <- strtoi(header, base=16)
118   payload <- readChunk(io, len)
119   readSexpFromString(payload)
120 }
121
122 readChunk <- function(io, len) {
123   buffer <- readChar(io, len)
124   if(nchar(buffer) != len) {
125     stop("short read in readChunk")
126   }
127   buffer
128 }
129
130 readSexpFromString <- function(string) {
131   pos <- 1
132   read <- function() {
133     skipWhitespace()
134     char <- substr(string, pos, pos)
135     switch(char,
136            "("=readList(),
137            "\""=readString(),
138            "'"=readQuote(),
139            {
140              if(pos > nchar(string))
141                stop("EOF during read")
142              obj <- readNumberOrSymbol()
143              if(obj == quote(`.`)) {
144                stop("Consing dot not implemented")
145              }
146              obj
147            })
148   }
149   skipWhitespace <- function() {
150     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
151       pos <<- pos + 1
152     }
153   }
154   readList <- function() {
155     ret <- list()
156     pos <<- pos + 1
157     while(TRUE) {
158       skipWhitespace()
159       char <- substr(string, pos, pos)
160       if(char == ")") {
161         pos <<- pos + 1
162         break
163       } else {
164         obj <- read()
165         if(length(obj) == 1 && obj == quote(`.`)) {
166           stop("Consing dot not implemented")
167         }
168         ret <- c(ret, list(obj))
169       }
170     }
171     ret
172   }
173   readString <- function() {
174     ret <- ""
175     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
176     while(TRUE) {
177       pos <<- pos + 1
178       char <- substr(string, pos, pos)
179       switch(char,
180              "\""={ pos <<- pos + 1; break },
181              "\\"={ pos <<- pos + 1
182                     char2 <- substr(string, pos, pos)
183                     switch(char2,
184                            "\""=addChar(char2),
185                            "\\"=addChar(char2),
186                            stop("Unrecognized escape character")) },
187              addChar(char))
188     }
189     ret
190   }
191   readNumberOrSymbol <- function() {
192     token <- readToken()
193     if(nchar(token)==0) {
194       stop("End of file reading token")
195     } else if(grepl("^[0-9]+$", token)) {
196       strtoi(token)
197     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
198       as.double(token)
199     } else {
200       as.name(token)
201     }
202   }
203   readToken <- function() {
204     token <- ""
205     while(TRUE) {
206       char <- substr(string, pos, pos)
207       if(char == "") {
208         break;
209       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
210         break;
211       } else {
212         token <- paste(token, char, sep="")
213         pos <<- pos + 1
214       }
215     }
216     token
217   }
218   read()
219 }
220
221 writeSexpToString <- function(obj) {
222   writeSexpToStringLoop <- function(obj) {
223     switch(typeof(obj),
224            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
225            "list"={ string <- paste(string, "(", sep="")
226                     max <- length(obj)
227                     if(max > 0) {
228                       for(i in 1:max) {
229                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
230                         if(i != max) {
231                           string <- paste(string, " ", sep="")
232                         }
233                       }
234                     }
235                     string <- paste(string, ")", sep="") },
236            "symbol"={ string <- paste(string, as.character(obj), sep="") },
237            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
238            "double"={ string <- paste(string, as.character(obj), sep="") },
239            "integer"={ string <- paste(string, as.character(obj), sep="") },
240            stop(paste("can't write object ", obj, sep="")))
241     string
242   }
243   string <- ""
244   writeSexpToStringLoop(obj)
245 }
246
247 printToString <- function(val) {
248   f <- fifo("")
249   tryCatch({ sink(f); print(val); sink(); readLines(f) },
250            finally=close(f))
251 }
252
253 `swank:connection-info` <- function (slimeConnection, sldbState) {
254   list(quote(`:pid`), Sys.getpid(),
255        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
256        quote(`:lisp-implementation`), list(quote(`:type`), "R",
257                                            quote(`:name`), "R",
258                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
259 }
260
261 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
262   for(contrib in contribs) {
263     filename <- sprintf("%s.R", as.character(contrib))
264     if(file.exists(filename)) {
265       source(filename, verbose=TRUE)
266     }
267   }
268   list()
269 }
270
271 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
272   list("R", "R")
273 }
274
275 sendReplResult <- function(slimeConnection, value) {
276   string <- printToString(value)
277   sendToEmacs(slimeConnection,
278               list(quote(`:write-string`),
279                    paste(string, collapse="\n"),
280                    quote(`:repl-result`)))
281 }
282
283 sendReplResultFunction <- sendReplResult
284
285 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
286   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
287   expr <- parse(text=string)[[1]]
288   lookedup <- do.call("bquote", list(expr))
289   value <- eval(lookedup, envir = globalenv())
290   sendReplResultFunction(slimeConnection, value)
291   list()
292 }
293
294 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
295   "No Arglist Information"
296 }
297
298 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
299   list()
300 }
301
302 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
303   condition <- simpleCondition("Throw to toplevel")
304   class(condition) <- c("swankTopLevel", class(condition))
305   signalCondition(condition)
306 }
307
308 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
309   calls <- sldbState$calls
310   if(is.null(to)) to <- length(calls)
311   from <- from+1
312   calls <- lapply(calls[from:to],
313                   { frameNumber <- from-1;
314                     function (x) {
315                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
316                       frameNumber <<- 1+frameNumber
317                       ret
318                     }
319                   })
320 }
321
322 computeRestartsForEmacs <- function (sldbState) {
323   lapply(sldbState$restarts,
324          function(x) {
325            ## this is all a little bit internalsy
326            restartName <- x[[1]][[1]]
327            description <- restartDescription(x)
328            list(restartName, if(is.null(description)) restartName else description)
329          })
330 }
331
332 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
333   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
334        computeRestartsForEmacs(sldbState),
335        `swank:backtrace`(slimeConnection, sldbState, from, to),
336        list(sldbState$id))
337 }
338
339 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
340   if(sldbState$level == level) {
341     invokeRestart(sldbState$restarts[[n+1]])
342   }
343 }
344
345 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
346   call <- sldbState$calls[[n+1]]
347   srcref <- attr(call, "srcref")
348   srcfile <- attr(srcref, "srcfile")
349   if(is.null(srcfile)) {
350     list(quote(`:error`), "no srcfile")
351   } else {
352     list(quote(`:location`),
353          list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
354          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
355          FALSE)
356   }
357 }
358
359 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
360   FALSE
361 }
362
363 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
364   str(sldbState$frames)
365   frame <- sldbState$frames[[1+index]]
366   objs <- ls(envir=frame)
367   list(lapply(objs, function(name) { list(quote(`:name`), name,
368                                           quote(`:id`), 0,
369                                           quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
370        list())
371 }
372
373 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
374   ## fails multiply if prefix contains regexp metacharacters
375   matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
376   nmatches <- length(matches)
377   if(nmatches == 0) {
378     list(list(), "")
379   } else {
380     longest <- matches[order(nchar(matches))][1]
381     while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
382       longest <- substr(longest, 1, nchar(longest)-1)
383     }
384     list(as.list(matches), longest)
385   }
386 }
387
388 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
389   # FIXME: I think in parse() here we can use srcref to associate
390   # buffer/filename/position to the objects.  Or something.
391   withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
392                abort="abort compilation")
393   list(quote(`:compilation-result`), list(), TRUE, times[3])
394 }
395
396 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
397   retry <- TRUE
398   value <- ""
399   while(retry) {
400     retry <- FALSE
401     withRestarts(value <- eval(parse(text=string), envir = globalenv()),
402                  retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))
403   }
404   printToString(value)
405 }
406
407 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
408   retry <- TRUE
409   value <- ""
410   output <- NULL
411   f <- fifo("")
412   tryCatch({
413     sink(f)
414     while(retry) {
415       retry <- FALSE
416       withRestarts(value <- eval(parse(text=string), envir = globalenv()),
417                    retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
418            finally={sink(); output <- readLines(f); close(f)})
419   list(output, printToString(value))
420 }
421
422 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
423   if(exists(string, envir = globalenv())) {
424     thing <- get(string, envir = globalenv())
425     if(inherits(thing, "function")) {
426       body <- body(thing)
427       srcref <- attr(body, "srcref")
428       srcfile <- attr(body, "srcfile")
429       if(is.null(srcfile)) {
430         list()
431       } else {
432         filename <- get("filename", srcfile)
433         list(list(sprintf("function %s", string),
434                   list(quote(`:location`),
435                        list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
436                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
437                        list())))
438       }
439     } else {
440       list()
441     }
442   } else {
443     list()
444   }
445 }