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(4005, portFile)
24 acceptConnections <- function(port, portFile) {
25 if(portFile != FALSE) {
26 f <- file(portFile, open="w+")
30 s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
35 serve <- function(io) {
39 mainLoop <- function(io) {
40 slimeConnection <- new.env()
41 slimeConnection$io <- io
43 withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
44 swankTopLevel=function(c) NULL),
45 abort="return to SLIME's toplevel")
49 dispatch <- function(slimeConnection, event, sldbState=NULL) {
51 if(kind == quote(`:emacs-rex`)) {
52 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
56 sendToEmacs <- function(slimeConnection, obj) {
57 io <- slimeConnection$io
58 payload <- writeSexpToString(obj)
59 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
60 writeChar(payload, io, eos=NULL)
64 callify <- function(form) {
65 ## we implement here the conversion from Lisp S-expression (or list)
66 ## expressions of code into our own, swankr, calling convention,
67 ## with slimeConnection and sldbState as first and second arguments.
68 ## as.call() gets us part of the way, but we need to walk the list
69 ## recursively to mimic CL:EVAL; we need to avoid converting R
70 ## special operators which we are punning (only `quote`, for now)
71 ## into this calling convention.
73 if(form[[1]] == quote(quote)) {
76 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
83 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
86 conn <- textConnection(NULL, open="w")
91 capture.output(value <- eval(call), file=conn)
92 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
93 if(nchar(string) > 0) {
94 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
95 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
99 }, error=function(c) {
101 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
102 if(nchar(string) > 0) {
103 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
104 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
107 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
108 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
109 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
112 makeSldbState <- function(condition, level, id) {
113 calls <- rev(sys.calls())[-1]
114 frames <- rev(sys.frames())[-1]
115 restarts <- rev(computeRestarts(condition))[-1]
116 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
117 class(ret) <- c("sldbState", class(ret))
121 sldbLoop <- function(slimeConnection, sldbState, id) {
123 io <- slimeConnection$io
124 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
125 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
127 dispatch(slimeConnection, readPacket(io), sldbState)
129 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
132 readPacket <- function(io) {
133 socketSelect(list(io))
134 header <- readChunk(io, 6)
135 len <- strtoi(header, base=16)
136 payload <- readChunk(io, len)
137 readSexpFromString(payload)
140 readChunk <- function(io, len) {
141 buffer <- readChar(io, len)
142 if(nchar(buffer) != len) {
143 stop("short read in readChunk")
148 readSexpFromString <- function(string) {
152 char <- substr(string, pos, pos)
158 if(pos > nchar(string))
159 stop("EOF during read")
160 obj <- readNumberOrSymbol()
161 if(obj == quote(`.`)) {
162 stop("Consing dot not implemented")
167 skipWhitespace <- function() {
168 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
172 readList <- function() {
177 char <- substr(string, pos, pos)
183 if(length(obj) == 1 && obj == quote(`.`)) {
184 stop("Consing dot not implemented")
186 ret <- c(ret, list(obj))
191 readString <- function() {
193 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
196 char <- substr(string, pos, pos)
198 "\""={ pos <<- pos + 1; break },
199 "\\"={ pos <<- pos + 1
200 char2 <- substr(string, pos, pos)
204 stop("Unrecognized escape character")) },
209 readNumberOrSymbol <- function() {
211 if(nchar(token)==0) {
212 stop("End of file reading token")
213 } else if(grepl("^[0-9]+$", token)) {
215 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
218 name <- as.name(token)
219 if(name == quote(t)) {
221 } else if(name == quote(nil)) {
228 readToken <- function() {
231 char <- substr(string, pos, pos)
234 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
237 token <- paste(token, char, sep="")
246 writeSexpToString <- function(obj) {
247 writeSexpToStringLoop <- function(obj) {
249 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
250 "list"={ string <- paste(string, "(", sep="")
254 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
256 string <- paste(string, " ", sep="")
260 string <- paste(string, ")", sep="") },
261 "symbol"={ string <- paste(string, as.character(obj), sep="") },
262 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
263 "double"={ string <- paste(string, as.character(obj), sep="") },
264 "integer"={ string <- paste(string, as.character(obj), sep="") },
265 stop(paste("can't write object ", obj, sep="")))
269 writeSexpToStringLoop(obj)
272 prin1ToString <- function(val) {
273 paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
274 sep="", collapse="\n")
277 printToString <- function(val) {
278 paste(capture.output(print(val)), sep="", collapse="\n")
281 `swank:connection-info` <- function (slimeConnection, sldbState) {
282 list(quote(`:pid`), Sys.getpid(),
283 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
284 quote(`:lisp-implementation`), list(quote(`:type`), "R",
286 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
289 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
290 for(contrib in contribs) {
291 filename <- sprintf("%s.R", as.character(contrib))
292 if(file.exists(filename)) {
299 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
303 makeReplResult <- function(value) {
304 string <- printToString(value)
305 list(quote(`:write-string`), string,
306 quote(`:repl-result`))
309 makeReplResultFunction <- makeReplResult
311 sendReplResult <- function(slimeConnection, value) {
312 result <- makeReplResultFunction(value)
313 sendToEmacs(slimeConnection, result)
316 sendReplResultFunction <- sendReplResult
318 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
320 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
321 expr <- parse(text=string)[[1]]
322 ## O maybe this is even uglier
323 lookedup <- do.call("bquote", list(expr))
324 value <- eval(lookedup, envir = globalenv())
325 sendReplResultFunction(slimeConnection, value)
329 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
330 "No Arglist Information"
333 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
337 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
338 condition <- simpleCondition("Throw to toplevel")
339 class(condition) <- c("swankTopLevel", class(condition))
340 signalCondition(condition)
343 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
344 calls <- sldbState$calls
345 if(is.null(to)) to <- length(calls)
347 calls <- lapply(calls[from:to],
348 { frameNumber <- from-1;
350 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
351 frameNumber <<- 1+frameNumber
357 computeRestartsForEmacs <- function (sldbState) {
358 lapply(sldbState$restarts,
360 ## this is all a little bit internalsy
361 restartName <- x[[1]][[1]]
362 description <- restartDescription(x)
363 list(restartName, if(is.null(description)) restartName else description)
367 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
368 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
369 computeRestartsForEmacs(sldbState),
370 `swank:backtrace`(slimeConnection, sldbState, from, to),
374 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
375 if(sldbState$level == level) {
376 invokeRestart(sldbState$restarts[[n+1]])
380 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
381 call <- sldbState$calls[[n+1]]
382 srcref <- attr(call, "srcref")
383 srcfile <- attr(srcref, "srcfile")
384 if(is.null(srcfile)) {
385 list(quote(`:error`), "no srcfile")
387 filename <- get("filename", srcfile)
388 ## KLUDGE: what this means is "is the srcfile filename
390 if(substr(filename, 1, 1) == "/") {
393 file <- sprintf("%s/%s", srcfile$wd, filename)
395 list(quote(`:location`),
396 list(quote(`:file`), file),
397 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
402 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
406 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
407 frame <- sldbState$frames[[1+index]]
408 withRetryRestart("retry SLIME interactive evaluation request",
409 value <- eval(parse(text=string), envir=frame))
413 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
414 frame <- sldbState$frames[[1+index]]
415 objs <- ls(envir=frame)
416 list(lapply(objs, function(name) { list(quote(`:name`), name,
418 quote(`:value`), printToString(eval(parse(text=name), envir=frame))) }),
422 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
423 ## fails multiply if prefix contains regexp metacharacters
424 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
425 nmatches <- length(matches)
429 longest <- matches[order(nchar(matches))][1]
430 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
431 longest <- substr(longest, 1, nchar(longest)-1)
433 list(as.list(matches), longest)
437 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
438 lineOffset <- charOffset <- colOffset <- NULL
439 for(pos in position) {
440 switch(as.character(pos[[1]]),
441 `:position` = {charOffset <- pos[[2]]},
442 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
443 warning("unknown content in pos", pos))
445 frob <- function(refs) {
448 srcref(attr(x,"srcfile"),
449 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
450 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
451 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
452 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
454 transformSrcrefs <- function(s) {
455 srcrefs <- attr(s, "srcref")
456 attribs <- attributes(s)
459 "call"=as.call(lapply(s, transformSrcrefs)),
460 "expression"=as.expression(lapply(s, transformSrcrefs)),
462 attributes(new) <- attribs
463 if(!is.null(attr(s, "srcref"))) {
464 attr(new, "srcref") <- frob(srcrefs)
469 times <- system.time({
470 exprs <- parse(text=string, srcfile=srcfile(filename))
471 eval(transformSrcrefs(exprs), envir = globalenv()) })},
472 abort="abort compilation")
473 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
476 withRetryRestart <- function(description, expr) {
477 call <- substitute(expr)
481 withRestarts(eval.parent(call),
482 retry=list(description=description,
483 handler=function() retry <<- TRUE))
487 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
488 withRetryRestart("retry SLIME interactive evaluation request",
489 value <- eval(parse(text=string), envir=globalenv()))
493 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
494 withRetryRestart("retry SLIME interactive evaluation request",
496 capture.output(value <- eval(parse(text=string),
497 envir=globalenv())) })
498 output <- paste(output, sep="", collapse="\n")
499 list(output, prin1ToString(value))
502 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
503 withRetryRestart("retry SLIME interactive evaluation request",
504 value <- eval(parse(text=string), envir=globalenv()))
508 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
509 if(exists(string, envir = globalenv())) {
510 thing <- get(string, envir = globalenv())
511 if(inherits(thing, "function")) {
513 srcref <- attr(body, "srcref")
514 srcfile <- attr(body, "srcfile")
515 if(is.null(srcfile)) {
518 filename <- get("filename", srcfile)
519 ## KLUDGE: what this means is "is the srcfile filename
521 if(substr(filename, 1, 1) == "/") {
524 file <- sprintf("%s/%s", srcfile$wd, filename)
526 list(list(sprintf("function %s", string),
527 list(quote(`:location`),
528 list(quote(`:file`), file),
529 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
540 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
541 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
542 collapse="\n", sep="")
545 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
546 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
550 resetInspector <- function(slimeConnection) {
551 assign("istate", list(), envir=slimeConnection)
552 assign("inspectorHistory", NULL, envir=slimeConnection)
555 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
556 withRetryRestart("retry SLIME inspection request",
557 { resetInspector(slimeConnection)
558 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
563 inspectObject <- function(slimeConnection, object) {
564 previous <- slimeConnection$istate
565 slimeConnection$istate <- new.env()
566 slimeConnection$istate$object <- object
567 slimeConnection$istate$previous <- previous
568 slimeConnection$istate$content <- emacsInspect(object)
569 if(!(object %in% slimeConnection$inspectorHistory)) {
570 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
572 if(!is.null(slimeConnection$istate$previous)) {
573 slimeConnection$istate$previous$`next` <- slimeConnection$istate
575 istateToElisp(slimeConnection$istate)
578 valuePart <- function(istate, object, string) {
579 list(quote(`:value`),
580 if(is.null(string)) printToString(object) else string,
581 assignIndexInParts(object, istate))
584 preparePart <- function(istate, part) {
585 if(is.character(part)) {
588 switch(as.character(part[[1]]),
589 `:newline` = list("\n"),
590 `:value` = valuePart(istate, part[[2]], part[[3]]),
591 `:line` = list(printToString(part[[2]]), ": ",
592 valuePart(istate, part[[3]], NULL), "\n"))
596 prepareRange <- function(istate, start, end) {
597 range <- istate$content[start+1:min(end+1, length(istate$content))]
600 ps <- c(ps, preparePart(istate, part))
602 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
606 assignIndexInParts <- function(object, istate) {
607 ret <- 1+length(istate$parts)
608 istate$parts <- c(istate$parts, list(object))
612 istateToElisp <- function(istate) {
613 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
614 quote(`:id`), assignIndexInParts(istate$object, istate),
615 quote(`:content`), prepareRange(istate, 0, 500))
618 emacsInspect <- function(object) {
619 UseMethod("emacsInspect")
622 emacsInspect.default <- function(thing) {
623 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
626 emacsInspect.list <- function(list) {
627 c(list("a list", list(quote(`:newline`))),
628 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
632 emacsInspect.numeric <- function(numeric) {
633 c(list("a numeric", list(quote(`:newline`))),
634 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
635 (1:length(numeric)), numeric))
638 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
639 resetInspector(slimeConnection)
643 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
644 slimeConnection$istate$parts[[index]]
647 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
648 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
649 inspectObject(slimeConnection, object)
652 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
653 if(!is.null(slimeConnection$istate$previous)) {
654 slimeConnection$istate <- slimeConnection$istate$previous
655 istateToElisp(slimeConnection$istate)
661 `swank:inspector-next` <- function(slimeConnection, sldbState) {
662 if(!is.null(slimeConnection$istate$`next`)) {
663 slimeConnection$istate <- slimeConnection$istate$`next`
664 istateToElisp(slimeConnection$istate)
670 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
671 expr <- parse(text=string)[[1]]
672 object <- slimeConnection$istate$object
673 if(inherits(object, "list")|inherits(object, "environment")) {
674 substituted <- substituteDirect(expr, object)
675 eval(substituted, envir=globalenv())
677 eval(expr, envir=globalenv())
681 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
682 resetInspector(slimeConnection)
683 inspectObject(slimeConnection, sldbState$condition)
686 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
687 resetInspector(slimeConnection)
688 frame <- sldbState$frames[[1+frame]]
689 name <- ls(envir=frame)[[1+var]]
690 object <- get(name, envir=frame)
691 inspectObject(slimeConnection, object)
694 `swank:default-directory` <- function(slimeConnection, sldbState) {
698 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
700 `swank:default-directory`(slimeConnection, sldbState)
703 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
704 source(filename, local=FALSE, keep.source=TRUE)
708 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
709 times <- system.time(parse(filename, srcfile=srcfile(filename)))
711 ## KLUDGE: inelegant, but works. It might be more in the spirit
712 ## of things to keep the result of the parse above around to
714 `swank:load-file`(slimeConnection, sldbState, filename)
716 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
719 `swank:quit-lisp` <- function(slimeConnection, sldbState) {