Christophe Weblog Wiki Code Publications Music
make swank:listener-eval be a bit more like the CL version
[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 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
63   ok <- FALSE
64   value <- NULL
65   tryCatch({
66     withCallingHandlers({
67       value <- do.call(eval(form[[1]]), c(list(slimeConnection), list(sldbState), form[-1]))
68       ok <- TRUE
69     }, error=function(c) {
70       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
71       withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
72     finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
73 }
74
75 makeSldbState <- function(condition, level, id) {
76   calls <- rev(sys.calls())[-1]
77   frames <- rev(sys.frames())[-1]
78   restarts <- rev(computeRestarts(condition))[-1]
79   ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
80   class(ret) <- c("sldbState", class(ret))
81   ret
82 }
83
84 sldbLoop <- function(slimeConnection, sldbState, id) {
85   tryCatch({
86     io <- slimeConnection$io
87     sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
88     sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
89     while(TRUE) {
90       dispatch(slimeConnection, readPacket(io), sldbState)
91     }
92   }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
93 }
94
95 readPacket <- function(io) {
96   header <- readChunk(io, 6)
97   len <- strtoi(header, base=16)
98   payload <- readChunk(io, len)
99   readSexpFromString(payload)
100 }
101
102 readChunk <- function(io, len) {
103   buffer <- readChar(io, len)
104   if(nchar(buffer) != len) {
105     stop("short read in readChunk")
106   }
107   buffer
108 }
109
110 readSexpFromString <- function(string) {
111   pos <- 1
112   read <- function() {
113     skipWhitespace()
114     char <- substr(string, pos, pos)
115     switch(char,
116            "("=readList(),
117            "\""=readString(),
118            "'"=readQuote(),
119            {
120              if(pos > nchar(string))
121                stop("EOF during read")
122              obj <- readNumberOrSymbol()
123              if(obj == quote(`.`)) {
124                stop("Consing dot not implemented")
125              }
126              obj
127            })
128   }
129   skipWhitespace <- function() {
130     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
131       pos <<- pos + 1
132     }
133   }
134   readList <- function() {
135     ret <- list()
136     pos <<- pos + 1
137     while(TRUE) {
138       skipWhitespace()
139       char <- substr(string, pos, pos)
140       if(char == ")") {
141         pos <<- pos + 1
142         break
143       } else {
144         obj <- read()
145         if(length(obj) == 1 && obj == quote(`.`)) {
146           stop("Consing dot not implemented")
147         }
148         ret <- c(ret, list(obj))
149       }
150     }
151     ret
152   }
153   readString <- function() {
154     ret <- ""
155     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
156     while(TRUE) {
157       pos <<- pos + 1
158       char <- substr(string, pos, pos)
159       switch(char,
160              "\""={ pos <<- pos + 1; break },
161              "\\"={ pos <<- pos + 1
162                     char2 <- substr(string, pos, pos)
163                     switch(char2,
164                            "\""=addChar(char2),
165                            "\\"=addChar(char2),
166                            stop("Unrecognized escape character")) },
167              addChar(char))
168     }
169     ret
170   }
171   readNumberOrSymbol <- function() {
172     token <- readToken()
173     if(nchar(token)==0) {
174       stop("End of file reading token")
175     } else if(grepl("^[0-9]+$", token)) {
176       strtoi(token)
177     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
178       as.double(token)
179     } else {
180       as.name(token)
181     }
182   }
183   readToken <- function() {
184     token <- ""
185     while(TRUE) {
186       char <- substr(string, pos, pos)
187       if(char == "") {
188         break;
189       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
190         break;
191       } else {
192         token <- paste(token, char, sep="")
193         pos <<- pos + 1
194       }
195     }
196     token
197   }
198   read()
199 }
200
201 writeSexpToString <- function(obj) {
202   writeSexpToStringLoop <- function(obj) {
203     switch(typeof(obj),
204            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
205            "list"={ string <- paste(string, "(", sep="")
206                     max <- length(obj)
207                     if(max > 0) {
208                       for(i in 1:max) {
209                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
210                         if(i != max) {
211                           string <- paste(string, " ", sep="")
212                         }
213                       }
214                     }
215                     string <- paste(string, ")", sep="") },
216            "symbol"={ string <- paste(string, as.character(obj), sep="") },
217            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
218            "double"={ string <- paste(string, as.character(obj), sep="") },
219            "integer"={ string <- paste(string, as.character(obj), sep="") },
220            stop(paste("can't write object ", obj, sep="")))
221     string
222   }
223   string <- ""
224   writeSexpToStringLoop(obj)
225 }
226
227 printToString <- function(val) {
228   f <- fifo("")
229   tryCatch({ sink(f); print(val); sink(); readLines(f) },
230            finally=close(f))
231 }
232
233 `swank:connection-info` <- function (slimeConnection, sldbState) {
234   list(quote(`:pid`), Sys.getpid(),
235        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
236        quote(`:lisp-implementation`), list(quote(`:type`), "R",
237                                            quote(`:name`), "R",
238                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
239 }
240
241 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
242   list()
243 }
244
245 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
246   list("R", "R")
247 }
248
249 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
250   val <- eval(parse(text=string), envir = globalenv())
251   string <- printToString(val)
252   sendToEmacs(slimeConnection, list(quote(`:write-string`), paste(string, collapse="\n"), quote(`:repl-result`)))
253   list()
254 }
255
256 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
257   "No Arglist Information"
258 }
259
260 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
261   list()
262 }
263
264 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
265   condition <- simpleCondition("Throw to toplevel")
266   class(condition) <- c("swankTopLevel", class(condition))
267   signalCondition(condition)
268 }
269
270 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
271   calls <- sldbState$calls
272   if(is.null(to)) to <- length(calls)
273   from <- from+1
274   calls <- lapply(calls[from:to],
275                   { frameNumber <- from-1;
276                     function (x) {
277                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
278                       frameNumber <<- 1+frameNumber
279                       ret
280                     }
281                   })
282 }
283
284 computeRestartsForEmacs <- function (sldbState) {
285   lapply(sldbState$restarts,
286          function(x) {
287            ## this is all a little bit internalsy
288            restartName <- x[[1]][[1]]
289            description <- restartDescription(x)
290            list(restartName, if(is.null(description)) restartName else description)
291          })
292 }
293
294 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
295   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
296        computeRestartsForEmacs(sldbState),
297        `swank:backtrace`(slimeConnection, sldbState, from, to),
298        list(sldbState$id))
299 }
300
301 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
302   if(sldbState$level == level) {
303     invokeRestart(sldbState$restarts[[n+1]])
304   }
305 }
306
307 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
308   call <- sldbState$calls[[n+1]]
309   srcref <- attr(call, "srcref")
310   srcfile <- attr(srcref, "srcfile")
311   if(is.null(srcfile)) {
312     list(quote(`:error`), "no srcfile")
313   } else {
314     filename <- get("filename", srcfile)
315     list(quote(`:location`),
316          list(quote(`:file`), filename),
317          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
318          FALSE)
319   }
320 }
321
322 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
323   FALSE
324 }
325
326 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
327   str(sldbState$frames)
328   frame <- sldbState$frames[[1+index]]
329   objs <- ls(envir=frame)
330   list(lapply(objs, function(name) { list(quote(`:name`), name,
331                                           quote(`:id`), 0,
332                                           quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
333        list())
334 }
335
336 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
337   ## fails multiply if prefix contains regexp metacharacters
338   matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
339   nmatches <- length(matches)
340   if(nmatches == 0) {
341     list(list(), "")
342   } else {
343     longest <- matches[order(nchar(matches))][1]
344     while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
345       longest <- substr(longest, 1, nchar(longest)-1)
346     }
347     list(as.list(matches), longest)
348   }
349 }
350
351 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
352   # FIXME: I think in parse() here we can use srcref to associate
353   # buffer/filename/position to the objects.  Or something.
354   withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
355                abort="abort compilation")
356   list(quote(`:compilation-result`), list(), TRUE, times[3])
357 }
358
359 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
360   retry <- TRUE
361   value <- ""
362   while(retry) {
363     retry <- FALSE
364     withRestarts(value <- eval(parse(text=string), envir = globalenv()),
365                  retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))
366   }
367   printToString(value)
368 }
369
370 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
371   retry <- TRUE
372   value <- ""
373   output <- NULL
374   f <- fifo("")
375   tryCatch({
376     sink(f)
377     while(retry) {
378       retry <- FALSE
379       withRestarts(value <- eval(parse(text=string), envir = globalenv()),
380                    retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
381            finally={sink(); output <- readLines(f); close(f)})
382   list(output, printToString(value))
383 }