Christophe Weblog Wiki Code Publications Music
c0adff899a9a8b895f06cf692d53a21cf0b9c6ed
[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   socketSelect(list(io))
117   header <- readChunk(io, 6)
118   len <- strtoi(header, base=16)
119   payload <- readChunk(io, len)
120   readSexpFromString(payload)
121 }
122
123 readChunk <- function(io, len) {
124   buffer <- readChar(io, len)
125   if(nchar(buffer) != len) {
126     stop("short read in readChunk")
127   }
128   buffer
129 }
130
131 readSexpFromString <- function(string) {
132   pos <- 1
133   read <- function() {
134     skipWhitespace()
135     char <- substr(string, pos, pos)
136     switch(char,
137            "("=readList(),
138            "\""=readString(),
139            "'"=readQuote(),
140            {
141              if(pos > nchar(string))
142                stop("EOF during read")
143              obj <- readNumberOrSymbol()
144              if(obj == quote(`.`)) {
145                stop("Consing dot not implemented")
146              }
147              obj
148            })
149   }
150   skipWhitespace <- function() {
151     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
152       pos <<- pos + 1
153     }
154   }
155   readList <- function() {
156     ret <- list()
157     pos <<- pos + 1
158     while(TRUE) {
159       skipWhitespace()
160       char <- substr(string, pos, pos)
161       if(char == ")") {
162         pos <<- pos + 1
163         break
164       } else {
165         obj <- read()
166         if(length(obj) == 1 && obj == quote(`.`)) {
167           stop("Consing dot not implemented")
168         }
169         ret <- c(ret, list(obj))
170       }
171     }
172     ret
173   }
174   readString <- function() {
175     ret <- ""
176     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
177     while(TRUE) {
178       pos <<- pos + 1
179       char <- substr(string, pos, pos)
180       switch(char,
181              "\""={ pos <<- pos + 1; break },
182              "\\"={ pos <<- pos + 1
183                     char2 <- substr(string, pos, pos)
184                     switch(char2,
185                            "\""=addChar(char2),
186                            "\\"=addChar(char2),
187                            stop("Unrecognized escape character")) },
188              addChar(char))
189     }
190     ret
191   }
192   readNumberOrSymbol <- function() {
193     token <- readToken()
194     if(nchar(token)==0) {
195       stop("End of file reading token")
196     } else if(grepl("^[0-9]+$", token)) {
197       strtoi(token)
198     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
199       as.double(token)
200     } else {
201       as.name(token)
202     }
203   }
204   readToken <- function() {
205     token <- ""
206     while(TRUE) {
207       char <- substr(string, pos, pos)
208       if(char == "") {
209         break;
210       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
211         break;
212       } else {
213         token <- paste(token, char, sep="")
214         pos <<- pos + 1
215       }
216     }
217     token
218   }
219   read()
220 }
221
222 writeSexpToString <- function(obj) {
223   writeSexpToStringLoop <- function(obj) {
224     switch(typeof(obj),
225            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
226            "list"={ string <- paste(string, "(", sep="")
227                     max <- length(obj)
228                     if(max > 0) {
229                       for(i in 1:max) {
230                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
231                         if(i != max) {
232                           string <- paste(string, " ", sep="")
233                         }
234                       }
235                     }
236                     string <- paste(string, ")", sep="") },
237            "symbol"={ string <- paste(string, as.character(obj), sep="") },
238            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
239            "double"={ string <- paste(string, as.character(obj), sep="") },
240            "integer"={ string <- paste(string, as.character(obj), sep="") },
241            stop(paste("can't write object ", obj, sep="")))
242     string
243   }
244   string <- ""
245   writeSexpToStringLoop(obj)
246 }
247
248 withOutputToString <- function(expr) {
249   call <- substitute(expr)
250   f <- fifo("")
251   sink(f)
252   tryCatch({ tryCatch(eval.parent(call), finally=sink())
253              readLines(f) },
254            finally=close(f))
255 }
256
257 printToString <- function(val) {
258   withOutputToString(str(val, indent.str="", list.len=5, max.level=2))
259 }
260
261 `swank:connection-info` <- function (slimeConnection, sldbState) {
262   list(quote(`:pid`), Sys.getpid(),
263        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
264        quote(`:lisp-implementation`), list(quote(`:type`), "R",
265                                            quote(`:name`), "R",
266                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
267 }
268
269 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
270   for(contrib in contribs) {
271     filename <- sprintf("%s.R", as.character(contrib))
272     if(file.exists(filename)) {
273       source(filename, verbose=TRUE)
274     }
275   }
276   list()
277 }
278
279 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
280   list("R", "R")
281 }
282
283 makeReplResult <- function(value) {
284   string <- printToString(value)
285   list(quote(`:write-string`), paste(string, collapse="\n"),
286        quote(`:repl-result`))
287 }
288
289 makeReplResultFunction <- makeReplResult
290
291 sendReplResult <- function(slimeConnection, value) {
292   result <- makeReplResultFunction(value)
293   sendToEmacs(slimeConnection, result)
294 }
295
296 sendReplResultFunction <- sendReplResult
297
298 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
299   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
300   expr <- parse(text=string)[[1]]
301   lookedup <- do.call("bquote", list(expr))
302   value <- eval(lookedup, envir = globalenv())
303   sendReplResultFunction(slimeConnection, value)
304   list()
305 }
306
307 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
308   "No Arglist Information"
309 }
310
311 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
312   list()
313 }
314
315 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
316   condition <- simpleCondition("Throw to toplevel")
317   class(condition) <- c("swankTopLevel", class(condition))
318   signalCondition(condition)
319 }
320
321 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
322   calls <- sldbState$calls
323   if(is.null(to)) to <- length(calls)
324   from <- from+1
325   calls <- lapply(calls[from:to],
326                   { frameNumber <- from-1;
327                     function (x) {
328                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
329                       frameNumber <<- 1+frameNumber
330                       ret
331                     }
332                   })
333 }
334
335 computeRestartsForEmacs <- function (sldbState) {
336   lapply(sldbState$restarts,
337          function(x) {
338            ## this is all a little bit internalsy
339            restartName <- x[[1]][[1]]
340            description <- restartDescription(x)
341            list(restartName, if(is.null(description)) restartName else description)
342          })
343 }
344
345 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
346   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
347        computeRestartsForEmacs(sldbState),
348        `swank:backtrace`(slimeConnection, sldbState, from, to),
349        list(sldbState$id))
350 }
351
352 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
353   if(sldbState$level == level) {
354     invokeRestart(sldbState$restarts[[n+1]])
355   }
356 }
357
358 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
359   call <- sldbState$calls[[n+1]]
360   srcref <- attr(call, "srcref")
361   srcfile <- attr(srcref, "srcfile")
362   if(is.null(srcfile)) {
363     list(quote(`:error`), "no srcfile")
364   } else {
365     list(quote(`:location`),
366          list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
367          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
368          FALSE)
369   }
370 }
371
372 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
373   FALSE
374 }
375
376 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
377   frame <- sldbState$frames[[1+index]]
378   withRetryRestart("retry SLIME interactive evaluation request",
379                    value <- eval(parse(text=string), envir=frame))
380   printToString(value)
381 }
382
383 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
384   str(sldbState$frames)
385   frame <- sldbState$frames[[1+index]]
386   objs <- ls(envir=frame)
387   list(lapply(objs, function(name) { list(quote(`:name`), name,
388                                           quote(`:id`), 0,
389                                           quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
390        list())
391 }
392
393 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
394   ## fails multiply if prefix contains regexp metacharacters
395   matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
396   nmatches <- length(matches)
397   if(nmatches == 0) {
398     list(list(), "")
399   } else {
400     longest <- matches[order(nchar(matches))][1]
401     while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
402       longest <- substr(longest, 1, nchar(longest)-1)
403     }
404     list(as.list(matches), longest)
405   }
406 }
407
408 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
409   # FIXME: I think in parse() here we can use srcref to associate
410   # buffer/filename/position to the objects.  Or something.
411   withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
412                abort="abort compilation")
413   list(quote(`:compilation-result`), list(), TRUE, times[3])
414 }
415
416 withRetryRestart <- function(description, expr) {
417   call <- substitute(expr)
418   retry <- TRUE
419   while(retry) {
420     retry <- FALSE
421     withRestarts(eval.parent(call),
422                  retry=list(description=description,
423                    handler=function() retry <<- TRUE))
424   }
425 }
426
427 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
428   withRetryRestart("retry SLIME interactive evaluation request",
429                    value <- eval(parse(text=string), envir=globalenv()))
430   printToString(value)
431 }
432
433 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
434   withRetryRestart("retry SLIME interactive evaluation request",
435                    { output <-
436                        withOutputToString(value <- eval(parse(text=string),
437                                                         envir=globalenv())) })
438   list(output, printToString(value))
439 }
440
441 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
442   if(exists(string, envir = globalenv())) {
443     thing <- get(string, envir = globalenv())
444     if(inherits(thing, "function")) {
445       body <- body(thing)
446       srcref <- attr(body, "srcref")
447       srcfile <- attr(body, "srcfile")
448       if(is.null(srcfile)) {
449         list()
450       } else {
451         filename <- get("filename", srcfile)
452         list(list(sprintf("function %s", string),
453                   list(quote(`:location`),
454                        list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
455                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
456                        list())))
457       }
458     } else {
459       list()
460     }
461   } else {
462     list()
463   }
464 }
465
466 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
467   paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
468         collapse="\n", sep="")
469 }
470
471 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
472   eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
473   TRUE
474 }
475
476 resetInspector <- function(slimeConnection) {
477   assign("istate", list(), envir=slimeConnection)
478   assign("inspectorHistory", NULL, envir=slimeConnection)
479 }
480
481 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
482   withRetryRestart("retry SLIME inspection request",
483                    { resetInspector(slimeConnection)
484                      value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
485                    })
486   value
487 }
488
489 inspectObject <- function(slimeConnection, object) {
490   previous <- slimeConnection$istate
491   slimeConnection$istate <- new.env()
492   slimeConnection$istate$object <- object
493   slimeConnection$istate$previous <- previous
494   slimeConnection$istate$content <- emacsInspect(object)
495   if(!(object %in% slimeConnection$inspectorHistory)) {
496     slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
497   }
498   if(!is.null(slimeConnection$istate$previous)) {
499     slimeConnection$istate$previous$`next` <- slimeConnection$istate
500   }
501   istateToElisp(slimeConnection$istate)
502 }
503
504 valuePart <- function(istate, object, string) {
505   list(quote(`:value`),
506        if(is.null(string)) paste(printToString(object),collapse=" ") else string,
507        assignIndexInParts(object, istate))
508 }
509
510 preparePart <- function(istate, part) {
511   if(is.character(part)) {
512     list(part)
513   } else {
514     switch(as.character(part[[1]]),
515            `:newline` = list("\n"),
516            `:value` = valuePart(istate, part[[2]], part[[3]]),
517            `:line` = list(printToString(part[[2]]), ": ",
518              valuePart(istate, part[[3]], NULL), "\n"))
519   }
520 }
521
522 prepareRange <- function(istate, start, end) {
523   range <- istate$content[start+1:min(end+1, length(istate$content))]
524   ps <- NULL
525   for(part in range) {
526     ps <- c(ps, preparePart(istate, part))
527   }
528   list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
529        start, end)
530 }
531
532 assignIndexInParts <- function(object, istate) {
533   ret <- 1+length(istate$parts)
534   istate$parts <- c(istate$parts, list(object))
535   ret
536 }
537
538 istateToElisp <- function(istate) {
539   list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
540        quote(`:id`), assignIndexInParts(istate$object, istate),
541        quote(`:content`), prepareRange(istate, 0, 500))
542 }
543
544 emacsInspect <- function(object) {
545   UseMethod("emacsInspect")
546 }
547
548 emacsInspect.default <- function(thing) {
549   c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
550 }
551
552 emacsInspect.list <- function(list) {
553   c(list("a list", list(quote(`:newline`))),
554     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
555            names(list), list))
556 }
557
558 emacsInspect.numeric <- function(numeric) {
559   c(list("a numeric", list(quote(`:newline`))),
560     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
561            (1:length(numeric)), numeric))
562 }
563
564 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
565   resetInspector(slimeConnection)
566   FALSE
567 }
568
569 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
570   slimeConnection$istate$parts[[index]]
571 }
572
573 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
574   object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
575   inspectObject(slimeConnection, object)
576 }
577
578 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
579   if(!is.null(slimeConnection$istate$previous)) {
580     slimeConnection$istate <- slimeConnection$istate$previous
581     istateToElisp(slimeConnection$istate)
582   } else {
583     FALSE
584   }
585 }
586
587 `swank:inspector-next` <- function(slimeConnection, sldbState) {
588   if(!is.null(slimeConnection$istate$`next`)) {
589     slimeConnection$istate <- slimeConnection$istate$`next`
590     istateToElisp(slimeConnection$istate)
591   } else {
592     FALSE
593   }
594 }
595
596 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
597   expr <- parse(text=string)[[1]]
598   object <- slimeConnection$istate$object
599   if(inherits(object, "list")|inherits(object, "environment")) {
600     substituted <- substituteDirect(expr, object)
601     eval(substituted, envir=globalenv())
602   } else {
603     eval(expr, envir=globalenv())
604   }
605 }
606
607 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
608   resetInspector(slimeConnection)
609   inspectObject(slimeConnection, sldbState$condition)
610 }
611
612 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
613   resetInspector(slimeConnection)
614   frame <- sldbState$frames[[1+frame]]
615   name <- ls(envir=frame)[[1+var]]
616   object <- get(name, envir=frame)
617   inspectObject(slimeConnection, object)
618 }