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