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.
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.
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>.
16 swank <- function(port=4005) {
17 acceptConnections(port, FALSE)
20 startSwank <- function(portFile) {
21 acceptConnections(FALSE, portFile)
24 acceptConnections <- function(port, portFile) {
25 s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
30 serve <- function(io) {
34 mainLoop <- function(io) {
35 slimeConnection <- new.env()
36 slimeConnection$io <- io
38 withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
39 swankTopLevel=function(c) NULL),
40 abort="return to SLIME's toplevel")
44 dispatch <- function(slimeConnection, event, sldbState=NULL) {
47 if(kind == quote(`:emacs-rex`)) {
48 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
52 sendToEmacs <- function(slimeConnection, obj) {
53 io <- slimeConnection$io
55 payload <- writeSexpToString(obj)
56 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
57 writeChar(payload, io, eos=NULL)
59 cat(sprintf("%06x", nchar(payload)), payload, sep="")
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.
71 if(form[[1]] == quote(quote)) {
74 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
81 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
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)))
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))
104 sldbLoop <- function(slimeConnection, sldbState, id) {
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))
110 dispatch(slimeConnection, readPacket(io), sldbState)
112 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
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)
123 readChunk <- function(io, len) {
124 buffer <- readChar(io, len)
125 if(nchar(buffer) != len) {
126 stop("short read in readChunk")
131 readSexpFromString <- function(string) {
135 char <- substr(string, pos, pos)
141 if(pos > nchar(string))
142 stop("EOF during read")
143 obj <- readNumberOrSymbol()
144 if(obj == quote(`.`)) {
145 stop("Consing dot not implemented")
150 skipWhitespace <- function() {
151 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
155 readList <- function() {
160 char <- substr(string, pos, pos)
166 if(length(obj) == 1 && obj == quote(`.`)) {
167 stop("Consing dot not implemented")
169 ret <- c(ret, list(obj))
174 readString <- function() {
176 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
179 char <- substr(string, pos, pos)
181 "\""={ pos <<- pos + 1; break },
182 "\\"={ pos <<- pos + 1
183 char2 <- substr(string, pos, pos)
187 stop("Unrecognized escape character")) },
192 readNumberOrSymbol <- function() {
194 if(nchar(token)==0) {
195 stop("End of file reading token")
196 } else if(grepl("^[0-9]+$", token)) {
198 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
204 readToken <- function() {
207 char <- substr(string, pos, pos)
210 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
213 token <- paste(token, char, sep="")
222 writeSexpToString <- function(obj) {
223 writeSexpToStringLoop <- function(obj) {
225 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
226 "list"={ string <- paste(string, "(", sep="")
230 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
232 string <- paste(string, " ", sep="")
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="")))
245 writeSexpToStringLoop(obj)
248 withOutputToString <- function(expr) {
249 call <- substitute(expr)
252 tryCatch({ tryCatch(eval.parent(call), finally=sink())
257 printToString <- function(val) {
258 withOutputToString(str(val, indent.str="", list.len=5, max.level=2))
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",
266 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
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)
279 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
283 sendReplResult <- function(slimeConnection, value) {
284 string <- printToString(value)
285 sendToEmacs(slimeConnection,
286 list(quote(`:write-string`),
287 paste(string, collapse="\n"),
288 quote(`:repl-result`)))
291 sendReplResultFunction <- sendReplResult
293 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
294 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
295 expr <- parse(text=string)[[1]]
296 lookedup <- do.call("bquote", list(expr))
297 value <- eval(lookedup, envir = globalenv())
298 sendReplResultFunction(slimeConnection, value)
302 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
303 "No Arglist Information"
306 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
310 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
311 condition <- simpleCondition("Throw to toplevel")
312 class(condition) <- c("swankTopLevel", class(condition))
313 signalCondition(condition)
316 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
317 calls <- sldbState$calls
318 if(is.null(to)) to <- length(calls)
320 calls <- lapply(calls[from:to],
321 { frameNumber <- from-1;
323 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
324 frameNumber <<- 1+frameNumber
330 computeRestartsForEmacs <- function (sldbState) {
331 lapply(sldbState$restarts,
333 ## this is all a little bit internalsy
334 restartName <- x[[1]][[1]]
335 description <- restartDescription(x)
336 list(restartName, if(is.null(description)) restartName else description)
340 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
341 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
342 computeRestartsForEmacs(sldbState),
343 `swank:backtrace`(slimeConnection, sldbState, from, to),
347 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
348 if(sldbState$level == level) {
349 invokeRestart(sldbState$restarts[[n+1]])
353 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
354 call <- sldbState$calls[[n+1]]
355 srcref <- attr(call, "srcref")
356 srcfile <- attr(srcref, "srcfile")
357 if(is.null(srcfile)) {
358 list(quote(`:error`), "no srcfile")
360 list(quote(`:location`),
361 list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
362 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
367 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
371 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
372 str(sldbState$frames)
373 frame <- sldbState$frames[[1+index]]
374 objs <- ls(envir=frame)
375 list(lapply(objs, function(name) { list(quote(`:name`), name,
377 quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
381 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
382 ## fails multiply if prefix contains regexp metacharacters
383 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
384 nmatches <- length(matches)
388 longest <- matches[order(nchar(matches))][1]
389 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
390 longest <- substr(longest, 1, nchar(longest)-1)
392 list(as.list(matches), longest)
396 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
397 # FIXME: I think in parse() here we can use srcref to associate
398 # buffer/filename/position to the objects. Or something.
399 withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
400 abort="abort compilation")
401 list(quote(`:compilation-result`), list(), TRUE, times[3])
404 withRetryRestart <- function(description, expr) {
405 call <- substitute(expr)
409 withRestarts(eval.parent(call),
410 retry=list(description=description,
411 handler=function() retry <<- TRUE))
415 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
416 withRetryRestart("retry SLIME interactive evaluation request",
417 value <- eval(parse(text=string), envir=globalenv()))
421 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
422 withRetryRestart("retry SLIME interactive evaluation request",
424 withOutputToString(value <- eval(parse(text=string),
425 envir=globalenv())) })
426 list(output, printToString(value))
429 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
430 if(exists(string, envir = globalenv())) {
431 thing <- get(string, envir = globalenv())
432 if(inherits(thing, "function")) {
434 srcref <- attr(body, "srcref")
435 srcfile <- attr(body, "srcfile")
436 if(is.null(srcfile)) {
439 filename <- get("filename", srcfile)
440 list(list(sprintf("function %s", string),
441 list(quote(`:location`),
442 list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
443 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
454 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
455 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
456 collapse="\n", sep="")
459 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
460 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
464 resetInspector <- function(slimeConnection) {
465 assign("istate", list(), envir=slimeConnection)
466 assign("inspectorHistory", NULL, envir=slimeConnection)
469 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
470 withRetryRestart("retry SLIME inspection request",
471 { resetInspector(slimeConnection)
472 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
477 inspectObject <- function(slimeConnection, object) {
478 previous <- slimeConnection$istate
479 slimeConnection$istate <- new.env()
480 slimeConnection$istate$object <- object
481 slimeConnection$istate$previous <- previous
482 slimeConnection$istate$content <- emacsInspect(object)
483 if(!(object %in% slimeConnection$inspectorHistory)) {
484 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
486 if(!is.null(slimeConnection$istate$previous)) {
487 slimeConnection$istate$previous$`next` <- slimeConnection$istate
489 istateToElisp(slimeConnection$istate)
492 valuePart <- function(istate, object, string) {
493 list(quote(`:value`),
494 if(is.null(string)) paste(printToString(object),collapse=" ") else string,
495 assignIndexInParts(object, istate))
498 preparePart <- function(istate, part) {
499 if(is.character(part)) {
502 switch(as.character(part[[1]]),
503 `:newline` = list("\n"),
504 `:value` = valuePart(istate, part[[2]], part[[3]]),
505 `:line` = list(printToString(part[[2]]), ": ",
506 valuePart(istate, part[[3]], NULL), "\n"))
510 prepareRange <- function(istate, start, end) {
511 range <- istate$content[start+1:min(end+1, length(istate$content))]
514 ps <- c(ps, preparePart(istate, part))
516 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
520 assignIndexInParts <- function(object, istate) {
521 ret <- 1+length(istate$parts)
522 istate$parts <- c(istate$parts, list(object))
526 istateToElisp <- function(istate) {
527 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
528 quote(`:id`), assignIndexInParts(istate$object, istate),
529 quote(`:content`), prepareRange(istate, 0, 500))
532 emacsInspect <- function(object) {
533 UseMethod("emacsInspect")
536 emacsInspect.list <- function(list) {
537 c(list("a list", list(quote(`:newline`))),
538 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
542 emacsInspect.numeric <- function(numeric) {
543 c(list("a numeric", list(quote(`:newline`))),
544 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
545 (1:length(numeric)), numeric))
548 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
549 resetInspector(slimeConnection)
553 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
554 slimeConnection$istate$parts[[index]]
557 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
558 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
559 inspectObject(slimeConnection, object)
562 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
563 if(!is.null(slimeConnection$istate$previous)) {
564 slimeConnection$istate <- slimeConnection$istate$previous
565 istateToElisp(slimeConnection$istate)
571 `swank:inspector-next` <- function(slimeConnection, sldbState) {
572 if(!is.null(slimeConnection$istate$`next`)) {
573 slimeConnection$istate <- slimeConnection$istate$`next`
574 istateToElisp(slimeConnection$istate)