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) {
46 if(kind == quote(`:emacs-rex`)) {
47 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
51 sendToEmacs <- function(slimeConnection, obj) {
52 io <- slimeConnection$io
53 payload <- writeSexpToString(obj)
54 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
55 writeChar(payload, io, eos=NULL)
59 callify <- function(form) {
60 ## we implement here the conversion from Lisp S-expression (or list)
61 ## expressions of code into our own, swankr, calling convention,
62 ## with slimeConnection and sldbState as first and second arguments.
63 ## as.call() gets us part of the way, but we need to walk the list
64 ## recursively to mimic CL:EVAL; we need to avoid converting R
65 ## special operators which we are punning (only `quote`, for now)
66 ## into this calling convention.
68 if(form[[1]] == quote(quote)) {
71 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
78 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
81 conn <- textConnection(NULL, open="w")
86 capture.output(value <- eval(call), file=conn)
87 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
88 if(nchar(string) > 0) {
89 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
90 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
94 }, error=function(c) {
96 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
97 if(nchar(string) > 0) {
98 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
99 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
102 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
103 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
104 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
107 makeSldbState <- function(condition, level, id) {
108 calls <- rev(sys.calls())[-1]
109 frames <- rev(sys.frames())[-1]
110 restarts <- rev(computeRestarts(condition))[-1]
111 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
112 class(ret) <- c("sldbState", class(ret))
116 sldbLoop <- function(slimeConnection, sldbState, id) {
118 io <- slimeConnection$io
119 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
120 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
122 dispatch(slimeConnection, readPacket(io), sldbState)
124 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
127 readPacket <- function(io) {
128 socketSelect(list(io))
129 header <- readChunk(io, 6)
130 len <- strtoi(header, base=16)
131 payload <- readChunk(io, len)
132 readSexpFromString(payload)
135 readChunk <- function(io, len) {
136 buffer <- readChar(io, len)
137 if(nchar(buffer) != len) {
138 stop("short read in readChunk")
143 readSexpFromString <- function(string) {
147 char <- substr(string, pos, pos)
153 if(pos > nchar(string))
154 stop("EOF during read")
155 obj <- readNumberOrSymbol()
156 if(obj == quote(`.`)) {
157 stop("Consing dot not implemented")
162 skipWhitespace <- function() {
163 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
167 readList <- function() {
172 char <- substr(string, pos, pos)
178 if(length(obj) == 1 && obj == quote(`.`)) {
179 stop("Consing dot not implemented")
181 ret <- c(ret, list(obj))
186 readString <- function() {
188 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
191 char <- substr(string, pos, pos)
193 "\""={ pos <<- pos + 1; break },
194 "\\"={ pos <<- pos + 1
195 char2 <- substr(string, pos, pos)
199 stop("Unrecognized escape character")) },
204 readNumberOrSymbol <- function() {
206 if(nchar(token)==0) {
207 stop("End of file reading token")
208 } else if(grepl("^[0-9]+$", token)) {
210 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
216 readToken <- function() {
219 char <- substr(string, pos, pos)
222 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
225 token <- paste(token, char, sep="")
234 writeSexpToString <- function(obj) {
235 writeSexpToStringLoop <- function(obj) {
237 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
238 "list"={ string <- paste(string, "(", sep="")
242 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
244 string <- paste(string, " ", sep="")
248 string <- paste(string, ")", sep="") },
249 "symbol"={ string <- paste(string, as.character(obj), sep="") },
250 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
251 "double"={ string <- paste(string, as.character(obj), sep="") },
252 "integer"={ string <- paste(string, as.character(obj), sep="") },
253 stop(paste("can't write object ", obj, sep="")))
257 writeSexpToStringLoop(obj)
260 prin1ToString <- function(val) {
261 paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
262 sep="", collapse="\n")
265 printToString <- function(val) {
266 paste(capture.output(print(val)), sep="", collapse="\n")
269 `swank:connection-info` <- function (slimeConnection, sldbState) {
270 list(quote(`:pid`), Sys.getpid(),
271 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
272 quote(`:lisp-implementation`), list(quote(`:type`), "R",
274 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
277 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
278 for(contrib in contribs) {
279 filename <- sprintf("%s.R", as.character(contrib))
280 if(file.exists(filename)) {
287 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
291 makeReplResult <- function(value) {
292 string <- printToString(value)
293 list(quote(`:write-string`), string,
294 quote(`:repl-result`))
297 makeReplResultFunction <- makeReplResult
299 sendReplResult <- function(slimeConnection, value) {
300 result <- makeReplResultFunction(value)
301 sendToEmacs(slimeConnection, result)
304 sendReplResultFunction <- sendReplResult
306 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
308 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
309 expr <- parse(text=string)[[1]]
310 ## O maybe this is even uglier
311 lookedup <- do.call("bquote", list(expr))
312 value <- eval(lookedup, envir = globalenv())
313 sendReplResultFunction(slimeConnection, value)
317 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
318 "No Arglist Information"
321 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
325 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
326 condition <- simpleCondition("Throw to toplevel")
327 class(condition) <- c("swankTopLevel", class(condition))
328 signalCondition(condition)
331 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
332 calls <- sldbState$calls
333 if(is.null(to)) to <- length(calls)
335 calls <- lapply(calls[from:to],
336 { frameNumber <- from-1;
338 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
339 frameNumber <<- 1+frameNumber
345 computeRestartsForEmacs <- function (sldbState) {
346 lapply(sldbState$restarts,
348 ## this is all a little bit internalsy
349 restartName <- x[[1]][[1]]
350 description <- restartDescription(x)
351 list(restartName, if(is.null(description)) restartName else description)
355 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
356 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
357 computeRestartsForEmacs(sldbState),
358 `swank:backtrace`(slimeConnection, sldbState, from, to),
362 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
363 if(sldbState$level == level) {
364 invokeRestart(sldbState$restarts[[n+1]])
368 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
369 call <- sldbState$calls[[n+1]]
370 srcref <- attr(call, "srcref")
371 srcfile <- attr(srcref, "srcfile")
372 if(is.null(srcfile)) {
373 list(quote(`:error`), "no srcfile")
375 filename <- get("filename", srcfile)
376 ## KLUDGE: what this means is "is the srcfile filename
378 if(substr(filename, 1, 1) == "/") {
381 file <- sprintf("%s/%s", srcfile$wd, filename)
383 list(quote(`:location`),
384 list(quote(`:file`), file),
385 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
390 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
394 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
395 frame <- sldbState$frames[[1+index]]
396 withRetryRestart("retry SLIME interactive evaluation request",
397 value <- eval(parse(text=string), envir=frame))
401 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
402 frame <- sldbState$frames[[1+index]]
403 objs <- ls(envir=frame)
404 list(lapply(objs, function(name) { list(quote(`:name`), name,
406 quote(`:value`), printToString(eval(parse(text=name), envir=frame))) }),
410 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
411 ## fails multiply if prefix contains regexp metacharacters
412 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
413 nmatches <- length(matches)
417 longest <- matches[order(nchar(matches))][1]
418 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
419 longest <- substr(longest, 1, nchar(longest)-1)
421 list(as.list(matches), longest)
425 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
426 lineOffset <- charOffset <- colOffset <- NULL
427 for(pos in position) {
428 switch(as.character(pos[[1]]),
429 `:position` = {charOffset <- pos[[2]]},
430 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
431 warning("unknown content in pos", pos))
433 frob <- function(refs) {
436 srcref(attr(x,"srcfile"),
437 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
438 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
439 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
440 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
442 transformSrcrefs <- function(s) {
443 srcrefs <- attr(s, "srcref")
444 attribs <- attributes(s)
447 "call"=as.call(lapply(s, transformSrcrefs)),
448 "expression"=as.expression(lapply(s, transformSrcrefs)),
450 attributes(new) <- attribs
451 if(!is.null(attr(s, "srcref"))) {
452 attr(new, "srcref") <- frob(srcrefs)
457 times <- system.time({
458 exprs <- parse(text=string, srcfile=srcfile(filename))
459 eval(transformSrcrefs(exprs), envir = globalenv()) })},
460 abort="abort compilation")
461 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
464 withRetryRestart <- function(description, expr) {
465 call <- substitute(expr)
469 withRestarts(eval.parent(call),
470 retry=list(description=description,
471 handler=function() retry <<- TRUE))
475 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
476 withRetryRestart("retry SLIME interactive evaluation request",
477 value <- eval(parse(text=string), envir=globalenv()))
481 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
482 withRetryRestart("retry SLIME interactive evaluation request",
484 capture.output(value <- eval(parse(text=string),
485 envir=globalenv())) })
486 output <- paste(output, sep="", collapse="\n")
487 list(output, prin1ToString(value))
490 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
491 if(exists(string, envir = globalenv())) {
492 thing <- get(string, envir = globalenv())
493 if(inherits(thing, "function")) {
495 srcref <- attr(body, "srcref")
496 srcfile <- attr(body, "srcfile")
497 if(is.null(srcfile)) {
500 filename <- get("filename", srcfile)
501 ## KLUDGE: what this means is "is the srcfile filename
503 if(substr(filename, 1, 1) == "/") {
506 file <- sprintf("%s/%s", srcfile$wd, filename)
508 list(list(sprintf("function %s", string),
509 list(quote(`:location`),
510 list(quote(`:file`), file),
511 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
522 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
523 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
524 collapse="\n", sep="")
527 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
528 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
532 resetInspector <- function(slimeConnection) {
533 assign("istate", list(), envir=slimeConnection)
534 assign("inspectorHistory", NULL, envir=slimeConnection)
537 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
538 withRetryRestart("retry SLIME inspection request",
539 { resetInspector(slimeConnection)
540 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
545 inspectObject <- function(slimeConnection, object) {
546 previous <- slimeConnection$istate
547 slimeConnection$istate <- new.env()
548 slimeConnection$istate$object <- object
549 slimeConnection$istate$previous <- previous
550 slimeConnection$istate$content <- emacsInspect(object)
551 if(!(object %in% slimeConnection$inspectorHistory)) {
552 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
554 if(!is.null(slimeConnection$istate$previous)) {
555 slimeConnection$istate$previous$`next` <- slimeConnection$istate
557 istateToElisp(slimeConnection$istate)
560 valuePart <- function(istate, object, string) {
561 list(quote(`:value`),
562 if(is.null(string)) printToString(object) else string,
563 assignIndexInParts(object, istate))
566 preparePart <- function(istate, part) {
567 if(is.character(part)) {
570 switch(as.character(part[[1]]),
571 `:newline` = list("\n"),
572 `:value` = valuePart(istate, part[[2]], part[[3]]),
573 `:line` = list(printToString(part[[2]]), ": ",
574 valuePart(istate, part[[3]], NULL), "\n"))
578 prepareRange <- function(istate, start, end) {
579 range <- istate$content[start+1:min(end+1, length(istate$content))]
582 ps <- c(ps, preparePart(istate, part))
584 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
588 assignIndexInParts <- function(object, istate) {
589 ret <- 1+length(istate$parts)
590 istate$parts <- c(istate$parts, list(object))
594 istateToElisp <- function(istate) {
595 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
596 quote(`:id`), assignIndexInParts(istate$object, istate),
597 quote(`:content`), prepareRange(istate, 0, 500))
600 emacsInspect <- function(object) {
601 UseMethod("emacsInspect")
604 emacsInspect.default <- function(thing) {
605 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
608 emacsInspect.list <- function(list) {
609 c(list("a list", list(quote(`:newline`))),
610 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
614 emacsInspect.numeric <- function(numeric) {
615 c(list("a numeric", list(quote(`:newline`))),
616 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
617 (1:length(numeric)), numeric))
620 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
621 resetInspector(slimeConnection)
625 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
626 slimeConnection$istate$parts[[index]]
629 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
630 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
631 inspectObject(slimeConnection, object)
634 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
635 if(!is.null(slimeConnection$istate$previous)) {
636 slimeConnection$istate <- slimeConnection$istate$previous
637 istateToElisp(slimeConnection$istate)
643 `swank:inspector-next` <- function(slimeConnection, sldbState) {
644 if(!is.null(slimeConnection$istate$`next`)) {
645 slimeConnection$istate <- slimeConnection$istate$`next`
646 istateToElisp(slimeConnection$istate)
652 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
653 expr <- parse(text=string)[[1]]
654 object <- slimeConnection$istate$object
655 if(inherits(object, "list")|inherits(object, "environment")) {
656 substituted <- substituteDirect(expr, object)
657 eval(substituted, envir=globalenv())
659 eval(expr, envir=globalenv())
663 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
664 resetInspector(slimeConnection)
665 inspectObject(slimeConnection, sldbState$condition)
668 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
669 resetInspector(slimeConnection)
670 frame <- sldbState$frames[[1+frame]]
671 name <- ls(envir=frame)[[1+var]]
672 object <- get(name, envir=frame)
673 inspectObject(slimeConnection, object)
676 `swank:default-directory` <- function(slimeConnection, sldbState) {
680 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
682 `swank:default-directory`(slimeConnection, sldbState)
685 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
686 source(filename, local=FALSE)
690 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
691 times <- system.time(parse(filename))
692 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)