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) {
307 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
308 expr <- parse(text=string)[[1]]
309 lookedup <- do.call("bquote", list(expr))
310 value <- eval(lookedup, envir = globalenv())
311 sendReplResultFunction(slimeConnection, value)
315 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
316 "No Arglist Information"
319 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
323 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
324 condition <- simpleCondition("Throw to toplevel")
325 class(condition) <- c("swankTopLevel", class(condition))
326 signalCondition(condition)
329 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
330 calls <- sldbState$calls
331 if(is.null(to)) to <- length(calls)
333 calls <- lapply(calls[from:to],
334 { frameNumber <- from-1;
336 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
337 frameNumber <<- 1+frameNumber
343 computeRestartsForEmacs <- function (sldbState) {
344 lapply(sldbState$restarts,
346 ## this is all a little bit internalsy
347 restartName <- x[[1]][[1]]
348 description <- restartDescription(x)
349 list(restartName, if(is.null(description)) restartName else description)
353 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
354 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
355 computeRestartsForEmacs(sldbState),
356 `swank:backtrace`(slimeConnection, sldbState, from, to),
360 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
361 if(sldbState$level == level) {
362 invokeRestart(sldbState$restarts[[n+1]])
366 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
367 call <- sldbState$calls[[n+1]]
368 srcref <- attr(call, "srcref")
369 srcfile <- attr(srcref, "srcfile")
370 if(is.null(srcfile)) {
371 list(quote(`:error`), "no srcfile")
373 list(quote(`:location`),
374 list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
375 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
380 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
384 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
385 frame <- sldbState$frames[[1+index]]
386 withRetryRestart("retry SLIME interactive evaluation request",
387 value <- eval(parse(text=string), envir=frame))
391 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
392 frame <- sldbState$frames[[1+index]]
393 objs <- ls(envir=frame)
394 list(lapply(objs, function(name) { list(quote(`:name`), name,
396 quote(`:value`), printToString(eval(parse(text=name), envir=frame))) }),
400 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
401 ## fails multiply if prefix contains regexp metacharacters
402 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
403 nmatches <- length(matches)
407 longest <- matches[order(nchar(matches))][1]
408 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
409 longest <- substr(longest, 1, nchar(longest)-1)
411 list(as.list(matches), longest)
415 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
416 lineOffset <- charOffset <- colOffset <- NULL
417 for(pos in position) {
418 switch(as.character(pos[[1]]),
419 `:position` = {charOffset <- pos[[2]]},
420 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
421 warning("unknown content in pos", pos))
423 frob <- function(refs) {
426 srcref(attr(x,"srcfile"),
427 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
428 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
429 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
430 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
432 transformSrcrefs <- function(s) {
433 srcrefs <- attr(s, "srcref")
434 attribs <- attributes(s)
437 "call"=as.call(lapply(s, transformSrcrefs)),
438 "expression"=as.expression(lapply(s, transformSrcrefs)),
440 attributes(new) <- attribs
441 if(!is.null(attr(s, "srcref"))) {
442 attr(new, "srcref") <- frob(srcrefs)
447 times <- system.time({
448 exprs <- parse(text=string, srcfile=srcfile(filename))
449 eval(transformSrcrefs(exprs), envir = globalenv()) })},
450 abort="abort compilation")
451 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
454 withRetryRestart <- function(description, expr) {
455 call <- substitute(expr)
459 withRestarts(eval.parent(call),
460 retry=list(description=description,
461 handler=function() retry <<- TRUE))
465 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
466 withRetryRestart("retry SLIME interactive evaluation request",
467 value <- eval(parse(text=string), envir=globalenv()))
471 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
472 withRetryRestart("retry SLIME interactive evaluation request",
474 capture.output(value <- eval(parse(text=string),
475 envir=globalenv())) })
476 output <- paste(output, sep="", collapse="\n")
477 list(output, prin1ToString(value))
480 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
481 if(exists(string, envir = globalenv())) {
482 thing <- get(string, envir = globalenv())
483 if(inherits(thing, "function")) {
485 srcref <- attr(body, "srcref")
486 srcfile <- attr(body, "srcfile")
487 if(is.null(srcfile)) {
490 filename <- get("filename", srcfile)
491 ## KLUDGE: what this means is "is the srcfile filename
493 if(substr(filename, 1, 1) == "/") {
496 file <- sprintf("%s/%s", srcfile$wd, filename)
498 list(list(sprintf("function %s", string),
499 list(quote(`:location`),
500 list(quote(`:file`), file),
501 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
512 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
513 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
514 collapse="\n", sep="")
517 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
518 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
522 resetInspector <- function(slimeConnection) {
523 assign("istate", list(), envir=slimeConnection)
524 assign("inspectorHistory", NULL, envir=slimeConnection)
527 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
528 withRetryRestart("retry SLIME inspection request",
529 { resetInspector(slimeConnection)
530 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
535 inspectObject <- function(slimeConnection, object) {
536 previous <- slimeConnection$istate
537 slimeConnection$istate <- new.env()
538 slimeConnection$istate$object <- object
539 slimeConnection$istate$previous <- previous
540 slimeConnection$istate$content <- emacsInspect(object)
541 if(!(object %in% slimeConnection$inspectorHistory)) {
542 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
544 if(!is.null(slimeConnection$istate$previous)) {
545 slimeConnection$istate$previous$`next` <- slimeConnection$istate
547 istateToElisp(slimeConnection$istate)
550 valuePart <- function(istate, object, string) {
551 list(quote(`:value`),
552 if(is.null(string)) printToString(object) else string,
553 assignIndexInParts(object, istate))
556 preparePart <- function(istate, part) {
557 if(is.character(part)) {
560 switch(as.character(part[[1]]),
561 `:newline` = list("\n"),
562 `:value` = valuePart(istate, part[[2]], part[[3]]),
563 `:line` = list(printToString(part[[2]]), ": ",
564 valuePart(istate, part[[3]], NULL), "\n"))
568 prepareRange <- function(istate, start, end) {
569 range <- istate$content[start+1:min(end+1, length(istate$content))]
572 ps <- c(ps, preparePart(istate, part))
574 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
578 assignIndexInParts <- function(object, istate) {
579 ret <- 1+length(istate$parts)
580 istate$parts <- c(istate$parts, list(object))
584 istateToElisp <- function(istate) {
585 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
586 quote(`:id`), assignIndexInParts(istate$object, istate),
587 quote(`:content`), prepareRange(istate, 0, 500))
590 emacsInspect <- function(object) {
591 UseMethod("emacsInspect")
594 emacsInspect.default <- function(thing) {
595 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
598 emacsInspect.list <- function(list) {
599 c(list("a list", list(quote(`:newline`))),
600 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
604 emacsInspect.numeric <- function(numeric) {
605 c(list("a numeric", list(quote(`:newline`))),
606 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
607 (1:length(numeric)), numeric))
610 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
611 resetInspector(slimeConnection)
615 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
616 slimeConnection$istate$parts[[index]]
619 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
620 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
621 inspectObject(slimeConnection, object)
624 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
625 if(!is.null(slimeConnection$istate$previous)) {
626 slimeConnection$istate <- slimeConnection$istate$previous
627 istateToElisp(slimeConnection$istate)
633 `swank:inspector-next` <- function(slimeConnection, sldbState) {
634 if(!is.null(slimeConnection$istate$`next`)) {
635 slimeConnection$istate <- slimeConnection$istate$`next`
636 istateToElisp(slimeConnection$istate)
642 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
643 expr <- parse(text=string)[[1]]
644 object <- slimeConnection$istate$object
645 if(inherits(object, "list")|inherits(object, "environment")) {
646 substituted <- substituteDirect(expr, object)
647 eval(substituted, envir=globalenv())
649 eval(expr, envir=globalenv())
653 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
654 resetInspector(slimeConnection)
655 inspectObject(slimeConnection, sldbState$condition)
658 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
659 resetInspector(slimeConnection)
660 frame <- sldbState$frames[[1+frame]]
661 name <- ls(envir=frame)[[1+var]]
662 object <- get(name, envir=frame)
663 inspectObject(slimeConnection, object)
666 `swank:default-directory` <- function(slimeConnection, sldbState) {
670 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
672 `swank:default-directory`(slimeConnection, sldbState)
675 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
676 source(filename, local=FALSE)
680 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
681 times <- system.time(parse(filename))
682 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)