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(`:lisp-implementation`), list(quote(`:type`), "R",
292 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
295 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
296 for(contrib in contribs) {
297 filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
298 if(file.exists(filename)) {
305 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
309 makeReplResult <- function(value) {
310 string <- printToString(value)
311 list(quote(`:write-string`), string,
312 quote(`:repl-result`))
315 makeReplResultFunction <- makeReplResult
317 sendReplResult <- function(slimeConnection, value) {
318 result <- makeReplResultFunction(value)
319 sendToEmacs(slimeConnection, result)
322 sendReplResultFunction <- sendReplResult
324 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
326 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
327 for(expr in parse(text=string)) {
329 ## O maybe this is even uglier
330 lookedup <- do.call("bquote", list(expr))
331 tmp <- withVisible(eval(lookedup, envir = globalenv()))
333 sendReplResultFunction(slimeConnection, tmp$value)
339 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
340 "No Arglist Information"
343 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
347 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
348 condition <- simpleCondition("Throw to toplevel")
349 class(condition) <- c("swankTopLevel", class(condition))
350 signalCondition(condition)
353 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
354 calls <- sldbState$calls
355 if(is.null(to)) to <- length(calls)
357 calls <- lapply(calls[from:to],
358 { frameNumber <- from-1;
360 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
361 frameNumber <<- 1+frameNumber
367 computeRestartsForEmacs <- function (sldbState) {
368 lapply(sldbState$restarts,
370 ## this is all a little bit internalsy
371 restartName <- x[[1]][[1]]
372 description <- restartDescription(x)
373 list(restartName, if(is.null(description)) restartName else description)
377 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
378 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
379 computeRestartsForEmacs(sldbState),
380 `swank:backtrace`(slimeConnection, sldbState, from, to),
384 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
385 if(sldbState$level == level) {
386 invokeRestart(sldbState$restarts[[n+1]])
390 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
391 call <- sldbState$calls[[n+1]]
392 srcref <- attr(call, "srcref")
393 srcfile <- attr(srcref, "srcfile")
394 if(is.null(srcfile)) {
395 list(quote(`:error`), "no srcfile")
397 filename <- get("filename", srcfile)
398 ## KLUDGE: what this means is "is the srcfile filename
400 if(substr(filename, 1, 1) == "/") {
403 file <- sprintf("%s/%s", srcfile$wd, filename)
405 list(quote(`:location`),
406 list(quote(`:file`), file),
407 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
412 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
416 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
417 frame <- sldbState$frames[[1+index]]
418 withRetryRestart("retry SLIME interactive evaluation request",
419 value <- eval(parse(text=string), envir=frame))
423 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
424 frame <- sldbState$frames[[1+index]]
425 objs <- ls(envir=frame)
426 list(lapply(objs, function(name) { list(quote(`:name`), name,
430 printToString(eval(parse(text=name), envir=frame))
431 }, error=function(c) {
432 sprintf("error printing object")
437 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
438 literal2rx <- function(string) {
439 ## list of ERE metacharacters from ?regexp
440 gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
442 matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
443 nmatches <- length(matches)
447 longest <- matches[order(nchar(matches))][1]
448 while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
449 longest <- substr(longest, 1, nchar(longest)-1)
451 list(as.list(matches), longest)
455 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
456 lineOffset <- charOffset <- colOffset <- NULL
457 for(pos in position) {
458 switch(as.character(pos[[1]]),
459 `:position` = {charOffset <- pos[[2]]},
460 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
461 warning("unknown content in pos", pos))
463 frob <- function(refs) {
466 srcref(attr(x,"srcfile"),
467 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
468 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
469 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
470 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
472 transformSrcrefs <- function(s) {
473 srcrefs <- attr(s, "srcref")
474 attribs <- attributes(s)
477 "call"=as.call(lapply(s, transformSrcrefs)),
478 "expression"=as.expression(lapply(s, transformSrcrefs)),
480 attributes(new) <- attribs
481 if(!is.null(attr(s, "srcref"))) {
482 attr(new, "srcref") <- frob(srcrefs)
487 times <- system.time({
488 exprs <- parse(text=string, srcfile=srcfile(filename))
489 eval(transformSrcrefs(exprs), envir = globalenv()) })},
490 abort="abort compilation")
491 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
494 withRetryRestart <- function(description, expr) {
495 call <- substitute(expr)
499 withRestarts(eval.parent(call),
500 retry=list(description=description,
501 handler=function() retry <<- TRUE))
505 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
506 withRetryRestart("retry SLIME interactive evaluation request",
507 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
509 prin1ToString(tmp$value)
515 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
516 withRetryRestart("retry SLIME interactive evaluation request",
518 capture.output(tmp <- withVisible(eval(parse(text=string),
519 envir=globalenv()))) })
520 output <- paste(output, sep="", collapse="\n")
522 list(output, prin1ToString(value))
524 list(output, "# invisible value")
528 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
529 withRetryRestart("retry SLIME interactive evaluation request",
530 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
538 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
539 if(exists(string, envir = globalenv())) {
540 thing <- get(string, envir = globalenv())
541 if(inherits(thing, "function")) {
543 srcref <- attr(body, "srcref")
544 srcfile <- attr(body, "srcfile")
545 if(is.null(srcfile)) {
548 filename <- get("filename", srcfile)
549 ## KLUDGE: what this means is "is the srcfile filename
551 if(substr(filename, 1, 1) == "/") {
554 file <- sprintf("%s/%s", srcfile$wd, filename)
556 list(list(sprintf("function %s", string),
557 list(quote(`:location`),
558 list(quote(`:file`), file),
559 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
570 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
571 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
572 collapse="\n", sep="")
575 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
576 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
580 resetInspector <- function(slimeConnection) {
581 assign("istate", list(), envir=slimeConnection)
582 assign("inspectorHistory", NULL, envir=slimeConnection)
585 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
586 withRetryRestart("retry SLIME inspection request",
587 { resetInspector(slimeConnection)
588 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
593 inspectObject <- function(slimeConnection, object) {
594 previous <- slimeConnection$istate
595 slimeConnection$istate <- new.env()
596 slimeConnection$istate$object <- object
597 slimeConnection$istate$previous <- previous
598 slimeConnection$istate$content <- emacsInspect(object)
599 if(!(object %in% slimeConnection$inspectorHistory)) {
600 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
602 if(!is.null(slimeConnection$istate$previous)) {
603 slimeConnection$istate$previous$`next` <- slimeConnection$istate
605 istateToElisp(slimeConnection$istate)
608 valuePart <- function(istate, object, string) {
609 list(quote(`:value`),
610 if(is.null(string)) printToString(object) else string,
611 assignIndexInParts(object, istate))
614 preparePart <- function(istate, part) {
615 if(is.character(part)) {
618 switch(as.character(part[[1]]),
619 `:newline` = list("\n"),
620 `:value` = valuePart(istate, part[[2]], part[[3]]),
621 `:line` = list(printToString(part[[2]]), ": ",
622 valuePart(istate, part[[3]], NULL), "\n"))
626 prepareRange <- function(istate, start, end) {
627 range <- istate$content[start+1:min(end+1, length(istate$content))]
630 ps <- c(ps, preparePart(istate, part))
632 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
636 assignIndexInParts <- function(object, istate) {
637 ret <- 1+length(istate$parts)
638 istate$parts <- c(istate$parts, list(object))
642 istateToElisp <- function(istate) {
643 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
644 quote(`:id`), assignIndexInParts(istate$object, istate),
645 quote(`:content`), prepareRange(istate, 0, 500))
648 emacsInspect <- function(object) {
649 UseMethod("emacsInspect")
652 emacsInspect.default <- function(thing) {
653 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
656 emacsInspect.list <- function(list) {
657 c(list("a list", list(quote(`:newline`))),
658 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
662 emacsInspect.numeric <- function(numeric) {
663 c(list("a numeric", list(quote(`:newline`))),
664 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
665 (1:length(numeric)), numeric))
668 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
669 resetInspector(slimeConnection)
673 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
674 slimeConnection$istate$parts[[index]]
677 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
678 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
679 inspectObject(slimeConnection, object)
682 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
683 if(!is.null(slimeConnection$istate$previous)) {
684 slimeConnection$istate <- slimeConnection$istate$previous
685 istateToElisp(slimeConnection$istate)
691 `swank:inspector-next` <- function(slimeConnection, sldbState) {
692 if(!is.null(slimeConnection$istate$`next`)) {
693 slimeConnection$istate <- slimeConnection$istate$`next`
694 istateToElisp(slimeConnection$istate)
700 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
701 expr <- parse(text=string)[[1]]
702 object <- slimeConnection$istate$object
703 if(inherits(object, "list")|inherits(object, "environment")) {
704 substituted <- substituteDirect(expr, object)
705 eval(substituted, envir=globalenv())
707 eval(expr, envir=globalenv())
711 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
712 resetInspector(slimeConnection)
713 inspectObject(slimeConnection, sldbState$condition)
716 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
717 resetInspector(slimeConnection)
718 frame <- sldbState$frames[[1+frame]]
719 name <- ls(envir=frame)[[1+var]]
720 object <- get(name, envir=frame)
721 inspectObject(slimeConnection, object)
724 `swank:default-directory` <- function(slimeConnection, sldbState) {
728 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
730 `swank:default-directory`(slimeConnection, sldbState)
733 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
734 source(filename, local=FALSE, keep.source=TRUE)
738 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
739 times <- system.time(parse(filename, srcfile=srcfile(filename)))
741 ## KLUDGE: inelegant, but works. It might be more in the spirit
742 ## of things to keep the result of the parse above around to
744 `swank:load-file`(slimeConnection, sldbState, filename)
746 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
749 `swank:quit-lisp` <- function(slimeConnection, sldbState) {