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 ### KLUDGE: this assumes that we're being sourced with chdir=TRUE.
17 ### (If not, `swank:swank-require` will work under the circumstances
18 ### that it used to work anyway -- i.e. the working directory is the
22 swank <- function(port=4005) {
23 acceptConnections(port, FALSE)
26 startSwank <- function(portFile) {
27 acceptConnections(4005, portFile)
30 acceptConnections <- function(port, portFile) {
31 if(portFile != FALSE) {
32 f <- file(portFile, open="w+")
36 s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
41 serve <- function(io) {
45 mainLoop <- function(io) {
46 slimeConnection <- new.env()
47 slimeConnection$io <- io
49 withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
50 swankTopLevel=function(c) NULL),
51 abort="return to SLIME's toplevel")
55 dispatch <- function(slimeConnection, event, sldbState=NULL) {
57 if(kind == quote(`:emacs-rex`)) {
58 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
62 sendToEmacs <- function(slimeConnection, obj) {
63 io <- slimeConnection$io
64 payload <- writeSexpToString(obj)
65 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
66 writeChar(payload, io, eos=NULL)
70 callify <- function(form) {
71 ## we implement here the conversion from Lisp S-expression (or list)
72 ## expressions of code into our own, swankr, calling convention,
73 ## with slimeConnection and sldbState as first and second arguments.
74 ## as.call() gets us part of the way, but we need to walk the list
75 ## recursively to mimic CL:EVAL; we need to avoid converting R
76 ## special operators which we are punning (only `quote`, for now)
77 ## into this calling convention.
79 if(form[[1]] == quote(quote)) {
82 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
89 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
92 conn <- textConnection(NULL, open="w")
97 capture.output(value <- eval(call), file=conn)
98 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
99 if(nchar(string) > 0) {
100 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
101 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
105 }, error=function(c) {
107 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
108 if(nchar(string) > 0) {
109 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
110 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
113 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
114 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
115 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
118 makeSldbState <- function(condition, level, id) {
119 calls <- rev(sys.calls())[-1]
120 frames <- rev(sys.frames())[-1]
121 restarts <- rev(computeRestarts(condition))[-1]
122 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
123 class(ret) <- c("sldbState", class(ret))
127 sldbLoop <- function(slimeConnection, sldbState, id) {
129 io <- slimeConnection$io
130 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
131 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
133 dispatch(slimeConnection, readPacket(io), sldbState)
135 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
138 readPacket <- function(io) {
139 socketSelect(list(io))
140 header <- readChunk(io, 6)
141 len <- strtoi(header, base=16)
142 payload <- readChunk(io, len)
143 readSexpFromString(payload)
146 readChunk <- function(io, len) {
147 buffer <- readChar(io, len)
148 if(nchar(buffer) != len) {
149 stop("short read in readChunk")
154 readSexpFromString <- function(string) {
158 char <- substr(string, pos, pos)
164 if(pos > nchar(string))
165 stop("EOF during read")
166 obj <- readNumberOrSymbol()
167 if(obj == quote(`.`)) {
168 stop("Consing dot not implemented")
173 skipWhitespace <- function() {
174 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
178 readList <- function() {
183 char <- substr(string, pos, pos)
189 if(length(obj) == 1 && obj == quote(`.`)) {
190 stop("Consing dot not implemented")
192 ret <- c(ret, list(obj))
197 readString <- function() {
199 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
202 char <- substr(string, pos, pos)
204 "\""={ pos <<- pos + 1; break },
205 "\\"={ pos <<- pos + 1
206 char2 <- substr(string, pos, pos)
210 stop("Unrecognized escape character")) },
215 readNumberOrSymbol <- function() {
217 if(nchar(token)==0) {
218 stop("End of file reading token")
219 } else if(grepl("^[0-9]+$", token)) {
221 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
224 name <- as.name(token)
225 if(name == quote(t)) {
227 } else if(name == quote(nil)) {
234 readToken <- function() {
237 char <- substr(string, pos, pos)
240 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
243 token <- paste(token, char, sep="")
252 writeSexpToString <- function(obj) {
253 writeSexpToStringLoop <- function(obj) {
255 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
256 "list"={ string <- paste(string, "(", sep="")
260 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
262 string <- paste(string, " ", sep="")
266 string <- paste(string, ")", sep="") },
267 "symbol"={ string <- paste(string, as.character(obj), sep="") },
268 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
269 "double"={ string <- paste(string, as.character(obj), sep="") },
270 "integer"={ string <- paste(string, as.character(obj), sep="") },
271 stop(paste("can't write object ", obj, sep="")))
275 writeSexpToStringLoop(obj)
278 prin1ToString <- function(val) {
279 paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
280 sep="", collapse="\n")
283 printToString <- function(val) {
284 paste(capture.output(print(val)), sep="", collapse="\n")
287 `swank:connection-info` <- function (slimeConnection, sldbState) {
288 list(quote(`:pid`), Sys.getpid(),
289 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
290 quote(`:encoding`), list(quote(`:coding-systems`), list("utf-8-unix")),
291 quote(`:lisp-implementation`), list(quote(`:type`), "R",
293 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
296 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
297 for(contrib in contribs) {
298 filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
299 if(file.exists(filename)) {
306 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
310 makeReplResult <- function(value) {
311 string <- printToString(value)
312 list(quote(`:write-string`), string,
313 quote(`:repl-result`))
316 makeReplResultFunction <- makeReplResult
318 sendReplResult <- function(slimeConnection, value) {
319 result <- makeReplResultFunction(value)
320 sendToEmacs(slimeConnection, result)
323 sendReplResultFunction <- sendReplResult
325 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
327 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
328 for(expr in parse(text=string)) {
330 ## O maybe this is even uglier
331 lookedup <- do.call("bquote", list(expr))
332 tmp <- withVisible(eval(lookedup, envir = globalenv()))
334 sendReplResultFunction(slimeConnection, tmp$value)
340 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
341 "No Arglist Information"
344 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
348 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
349 condition <- simpleCondition("Throw to toplevel")
350 class(condition) <- c("swankTopLevel", class(condition))
351 signalCondition(condition)
354 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
355 calls <- sldbState$calls
356 if(is.null(to)) to <- length(calls)
358 calls <- lapply(calls[from:to],
359 { frameNumber <- from-1;
361 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
362 frameNumber <<- 1+frameNumber
368 computeRestartsForEmacs <- function (sldbState) {
369 lapply(sldbState$restarts,
371 ## this is all a little bit internalsy
372 restartName <- x[[1]][[1]]
373 description <- restartDescription(x)
374 list(restartName, if(is.null(description)) restartName else description)
378 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
379 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
380 computeRestartsForEmacs(sldbState),
381 `swank:backtrace`(slimeConnection, sldbState, from, to),
385 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
386 if(sldbState$level == level) {
387 invokeRestart(sldbState$restarts[[n+1]])
391 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
392 call <- sldbState$calls[[n+1]]
393 srcref <- attr(call, "srcref")
394 srcfile <- attr(srcref, "srcfile")
395 if(is.null(srcfile)) {
396 list(quote(`:error`), "no srcfile")
398 filename <- get("filename", srcfile)
399 ## KLUDGE: what this means is "is the srcfile filename
401 if(substr(filename, 1, 1) == "/") {
404 file <- sprintf("%s/%s", srcfile$wd, filename)
406 list(quote(`:location`),
407 list(quote(`:file`), file),
408 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
413 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
417 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
418 frame <- sldbState$frames[[1+index]]
419 withRetryRestart("retry SLIME interactive evaluation request",
420 value <- eval(parse(text=string), envir=frame))
424 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
425 frame <- sldbState$frames[[1+index]]
426 objs <- ls(envir=frame)
427 if(identical(frame, globalenv())) {
430 list(lapply(objs, function(name) { list(quote(`:name`), name,
434 printToString(eval(parse(text=name), envir=frame))
435 }, error=function(c) {
436 sprintf("error printing object")
441 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
442 literal2rx <- function(string) {
443 ## list of ERE metacharacters from ?regexp
444 gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
446 matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
447 nmatches <- length(matches)
451 longest <- matches[order(nchar(matches))][1]
452 while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
453 longest <- substr(longest, 1, nchar(longest)-1)
455 list(as.list(matches), longest)
459 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
460 lineOffset <- charOffset <- colOffset <- NULL
461 for(pos in position) {
462 switch(as.character(pos[[1]]),
463 `:position` = {charOffset <- pos[[2]]},
464 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
465 warning("unknown content in pos", pos))
467 frob <- function(refs) {
470 srcref(attr(x,"srcfile"),
471 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
472 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
473 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
474 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
476 transformSrcrefs <- function(s) {
477 srcrefs <- attr(s, "srcref")
478 attribs <- attributes(s)
481 "call"=as.call(lapply(s, transformSrcrefs)),
482 "expression"=as.expression(lapply(s, transformSrcrefs)),
484 attributes(new) <- attribs
485 if(!is.null(attr(s, "srcref"))) {
486 attr(new, "srcref") <- frob(srcrefs)
491 times <- system.time({
492 exprs <- parse(text=string, srcfile=srcfile(filename))
493 eval(transformSrcrefs(exprs), envir = globalenv()) })},
494 abort="abort compilation")
495 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
498 withRetryRestart <- function(description, expr) {
499 call <- substitute(expr)
503 withRestarts(eval.parent(call),
504 retry=list(description=description,
505 handler=function() retry <<- TRUE))
509 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
510 withRetryRestart("retry SLIME interactive evaluation request",
511 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
513 prin1ToString(tmp$value)
519 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
520 withRetryRestart("retry SLIME interactive evaluation request",
522 capture.output(tmp <- withVisible(eval(parse(text=string),
523 envir=globalenv()))) })
524 output <- paste(output, sep="", collapse="\n")
526 list(output, prin1ToString(tmp$value))
528 list(output, "# invisible value")
532 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
533 withRetryRestart("retry SLIME interactive evaluation request",
534 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
536 prin1ToString(tmp$value)
542 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
543 if(exists(string, envir = globalenv())) {
544 thing <- get(string, envir = globalenv())
545 if(inherits(thing, "function")) {
547 srcref <- attr(body, "srcref")
548 srcfile <- attr(body, "srcfile")
549 if(is.null(srcfile)) {
552 filename <- get("filename", srcfile)
553 ## KLUDGE: what this means is "is the srcfile filename
555 if(substr(filename, 1, 1) == "/") {
558 file <- sprintf("%s/%s", srcfile$wd, filename)
560 list(list(sprintf("function %s", string),
561 list(quote(`:location`),
562 list(quote(`:file`), file),
563 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
574 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
575 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
576 collapse="\n", sep="")
579 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
580 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
584 resetInspector <- function(slimeConnection) {
585 assign("istate", list(), envir=slimeConnection)
586 assign("inspectorHistory", NULL, envir=slimeConnection)
589 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
590 withRetryRestart("retry SLIME inspection request",
591 { resetInspector(slimeConnection)
592 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
597 inspectObject <- function(slimeConnection, object) {
598 previous <- slimeConnection$istate
599 slimeConnection$istate <- new.env()
600 slimeConnection$istate$object <- object
601 slimeConnection$istate$previous <- previous
602 slimeConnection$istate$content <- emacsInspect(object)
603 if(!(object %in% slimeConnection$inspectorHistory)) {
604 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
606 if(!is.null(slimeConnection$istate$previous)) {
607 slimeConnection$istate$previous$`next` <- slimeConnection$istate
609 istateToElisp(slimeConnection$istate)
612 valuePart <- function(istate, object, string) {
613 list(quote(`:value`),
614 if(is.null(string)) printToString(object) else string,
615 assignIndexInParts(object, istate))
618 preparePart <- function(istate, part) {
619 if(is.character(part)) {
622 switch(as.character(part[[1]]),
623 `:newline` = list("\n"),
624 `:value` = valuePart(istate, part[[2]], part[[3]]),
625 `:line` = list(printToString(part[[2]]), ": ",
626 valuePart(istate, part[[3]], NULL), "\n"))
630 prepareRange <- function(istate, start, end) {
631 range <- istate$content[start+1:min(end+1, length(istate$content))]
634 ps <- c(ps, preparePart(istate, part))
636 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
640 assignIndexInParts <- function(object, istate) {
641 ret <- 1+length(istate$parts)
642 istate$parts <- c(istate$parts, list(object))
646 istateToElisp <- function(istate) {
647 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
648 quote(`:id`), assignIndexInParts(istate$object, istate),
649 quote(`:content`), prepareRange(istate, 0, 500))
652 emacsInspect <- function(object) {
653 UseMethod("emacsInspect")
656 emacsInspect.default <- function(thing) {
657 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
660 emacsInspect.list <- function(list) {
661 c(list("a list", list(quote(`:newline`))),
662 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
666 emacsInspect.numeric <- function(numeric) {
667 c(list("a numeric", list(quote(`:newline`))),
668 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
669 (1:length(numeric)), numeric))
672 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
673 resetInspector(slimeConnection)
677 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
678 slimeConnection$istate$parts[[index]]
681 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
682 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
683 inspectObject(slimeConnection, object)
686 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
687 if(!is.null(slimeConnection$istate$previous)) {
688 slimeConnection$istate <- slimeConnection$istate$previous
689 istateToElisp(slimeConnection$istate)
695 `swank:inspector-next` <- function(slimeConnection, sldbState) {
696 if(!is.null(slimeConnection$istate$`next`)) {
697 slimeConnection$istate <- slimeConnection$istate$`next`
698 istateToElisp(slimeConnection$istate)
704 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
705 expr <- parse(text=string)[[1]]
706 object <- slimeConnection$istate$object
707 if(inherits(object, "list")|inherits(object, "environment")) {
708 substituted <- substituteDirect(expr, object)
709 eval(substituted, envir=globalenv())
711 eval(expr, envir=globalenv())
715 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
716 resetInspector(slimeConnection)
717 inspectObject(slimeConnection, sldbState$condition)
720 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
721 resetInspector(slimeConnection)
722 frame <- sldbState$frames[[1+frame]]
723 name <- ls(envir=frame)[[1+var]]
724 object <- get(name, envir=frame)
725 inspectObject(slimeConnection, object)
728 `swank:default-directory` <- function(slimeConnection, sldbState) {
732 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
734 `swank:default-directory`(slimeConnection, sldbState)
737 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
738 source(filename, local=FALSE, keep.source=TRUE)
742 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
743 times <- system.time(parse(filename, srcfile=srcfile(filename)))
745 ## KLUDGE: inelegant, but works. It might be more in the spirit
746 ## of things to keep the result of the parse above around to
748 `swank:load-file`(slimeConnection, sldbState, filename)
750 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
753 `swank:quit-lisp` <- function(slimeConnection, sldbState) {