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 ## FIXME: maybe we should support dontClose here?
37 s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
39 tryCatch(serve(s), endOfFile=function(c) NULL)
42 serve <- function(io) {
46 mainLoop <- function(io) {
47 slimeConnection <- new.env()
48 slimeConnection$io <- io
50 withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
51 swankTopLevel=function(c) NULL),
52 abort="return to SLIME's toplevel")
56 dispatch <- function(slimeConnection, event, sldbState=NULL) {
58 if(kind == quote(`:emacs-rex`)) {
59 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
63 sendToEmacs <- function(slimeConnection, obj) {
64 io <- slimeConnection$io
65 payload <- writeSexpToString(obj)
66 writeChar(sprintf("%06x", nchar(payload, type="bytes")), io, eos=NULL)
67 writeChar(payload, io, eos=NULL)
71 callify <- function(form) {
72 ## we implement here the conversion from Lisp S-expression (or list)
73 ## expressions of code into our own, swankr, calling convention,
74 ## with slimeConnection and sldbState as first and second arguments.
75 ## as.call() gets us part of the way, but we need to walk the list
76 ## recursively to mimic CL:EVAL; we need to avoid converting R
77 ## special operators which we are punning (only `quote`, for now)
78 ## into this calling convention.
80 if(form[[1]] == quote(quote)) {
83 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
90 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
93 conn <- textConnection(NULL, open="w")
98 capture.output(value <- eval(call), file=conn)
99 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
100 if(nchar(string) > 0) {
101 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
102 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
106 }, error=function(c) {
108 string <- paste(textConnectionValue(conn), sep="", collapse="\n")
109 if(nchar(string) > 0) {
110 sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
111 sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
114 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
115 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
116 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
119 makeSldbState <- function(condition, level, id) {
120 calls <- rev(sys.calls())[-1]
121 frames <- rev(sys.frames())[-1]
122 restarts <- rev(computeRestarts(condition))[-1]
123 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
124 class(ret) <- c("sldbState", class(ret))
128 sldbLoop <- function(slimeConnection, sldbState, id) {
130 io <- slimeConnection$io
131 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
132 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
134 dispatch(slimeConnection, readPacket(io), sldbState)
136 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
139 readPacket <- function(io) {
140 socketSelect(list(io))
141 header <- readChunk(io, 6)
142 len <- strtoi(header, base=16)
143 payload <- readChunk(io, len)
144 readSexpFromString(payload)
147 readChunk <- function(io, len) {
148 buffer <- readChar(io, len)
149 if(length(buffer) == 0) {
150 condition <- simpleCondition("End of file on io")
151 class(condition) <- c("endOfFile", class(condition))
152 signalCondition(condition)
154 if(nchar(buffer) != len) {
155 stop("short read in readChunk")
160 readSexpFromString <- function(string) {
164 char <- substr(string, pos, pos)
170 if(pos > nchar(string))
171 stop("EOF during read")
172 obj <- readNumberOrSymbol()
173 if(obj == quote(`.`)) {
174 stop("Consing dot not implemented")
179 skipWhitespace <- function() {
180 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
184 readList <- function() {
189 char <- substr(string, pos, pos)
195 if(length(obj) == 1 && obj == quote(`.`)) {
196 stop("Consing dot not implemented")
198 ret <- c(ret, list(obj))
203 readString <- function() {
205 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
208 char <- substr(string, pos, pos)
210 "\""={ pos <<- pos + 1; break },
211 "\\"={ pos <<- pos + 1
212 char2 <- substr(string, pos, pos)
216 stop("Unrecognized escape character")) },
221 readNumberOrSymbol <- function() {
223 if(nchar(token)==0) {
224 stop("End of file reading token")
225 } else if(grepl("^[0-9]+$", token)) {
227 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
230 name <- as.name(token)
231 if(name == quote(t)) {
233 } else if(name == quote(nil)) {
240 readToken <- function() {
243 char <- substr(string, pos, pos)
246 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
249 token <- paste(token, char, sep="")
258 writeSexpToString <- function(obj) {
259 writeSexpToStringLoop <- function(obj) {
261 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
262 "list"={ string <- paste(string, "(", sep="")
266 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
268 string <- paste(string, " ", sep="")
272 string <- paste(string, ")", sep="") },
273 "symbol"={ string <- paste(string, as.character(obj), sep="") },
274 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
275 "double"={ string <- paste(string, as.character(obj), sep="") },
276 "integer"={ string <- paste(string, as.character(obj), sep="") },
277 stop(paste("can't write object ", obj, sep="")))
281 writeSexpToStringLoop(obj)
284 prin1ToString <- function(val) {
285 paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
286 sep="", collapse="\n")
289 printToString <- function(val) {
290 paste(capture.output(print(val)), sep="", collapse="\n")
293 `swank:connection-info` <- function (slimeConnection, sldbState) {
294 list(quote(`:pid`), Sys.getpid(),
295 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
296 quote(`:version`), "2012-04-23",
297 quote(`:encoding`), list(quote(`:coding-systems`), list("utf-8-unix")),
298 quote(`:lisp-implementation`), list(quote(`:type`), "R",
300 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
303 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
304 for(contrib in contribs) {
305 filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
306 if(file.exists(filename)) {
313 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
317 makeReplResult <- function(value) {
318 string <- printToString(value)
319 list(quote(`:write-string`), string,
320 quote(`:repl-result`))
323 makeReplResultFunction <- makeReplResult
325 sendReplResult <- function(slimeConnection, value) {
326 result <- makeReplResultFunction(value)
327 sendToEmacs(slimeConnection, result)
330 sendReplResultFunction <- sendReplResult
332 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
334 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
335 for(expr in parse(text=string)) {
337 ## O maybe this is even uglier
338 lookedup <- do.call("bquote", list(expr))
339 tmp <- withVisible(eval(lookedup, envir = globalenv()))
341 sendReplResultFunction(slimeConnection, tmp$value)
347 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
348 "No Arglist Information"
351 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
352 if(!exists(op, envir = globalenv())) {
355 funoid <- get(op, envir = globalenv())
356 if(is.function(funoid)) {
357 args <- formals(funoid)
358 paste(sprintf("%s=%s", names(args), args), collapse=", ")
364 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
365 condition <- simpleCondition("Throw to toplevel")
366 class(condition) <- c("swankTopLevel", class(condition))
367 signalCondition(condition)
370 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
371 calls <- sldbState$calls
372 if(is.null(to)) to <- length(calls)
374 calls <- lapply(calls[from:to],
375 { frameNumber <- from-1;
377 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
378 frameNumber <<- 1+frameNumber
384 computeRestartsForEmacs <- function (sldbState) {
385 lapply(sldbState$restarts,
387 ## this is all a little bit internalsy
388 restartName <- x[[1]][[1]]
389 description <- restartDescription(x)
390 list(restartName, if(is.null(description)) restartName else description)
394 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
395 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
396 computeRestartsForEmacs(sldbState),
397 `swank:backtrace`(slimeConnection, sldbState, from, to),
401 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
402 if(sldbState$level == level) {
403 invokeRestart(sldbState$restarts[[n+1]])
407 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
408 call <- sldbState$calls[[n+1]]
409 srcref <- attr(call, "srcref")
410 srcfile <- attr(srcref, "srcfile")
411 if(is.null(srcfile)) {
412 list(quote(`:error`), "no srcfile")
414 filename <- get("filename", srcfile)
415 ## KLUDGE: what this means is "is the srcfile filename
417 if(substr(filename, 1, 1) == "/") {
420 file <- sprintf("%s/%s", srcfile$wd, filename)
422 list(quote(`:location`),
423 list(quote(`:file`), file),
424 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
429 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
433 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
434 frame <- sldbState$frames[[1+index]]
435 withRetryRestart("retry SLIME interactive evaluation request",
436 value <- eval(parse(text=string), envir=frame))
440 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
441 frame <- sldbState$frames[[1+index]]
442 objs <- ls(envir=frame)
443 if(identical(frame, globalenv())) {
446 list(lapply(objs, function(name) { list(quote(`:name`), name,
450 printToString(eval(parse(text=name), envir=frame))
451 }, error=function(c) {
452 sprintf("error printing object")
457 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
458 symbolFieldsCompletion <- function(object, rest) {
459 ## FIXME: this is hacky, ignoring several syntax issues (use of
460 ## and/or necessity for backquoting identifiers: e.g. fields
461 ## containing hyphens)
462 if((dollar <- regexpr("$", rest, fixed=TRUE)) == -1) {
463 matches <- grep(sprintf("^%s", literal2rx(rest)), names(object), value=TRUE)
464 matches <- sprintf("%s$%s", gsub("\\$[^$]*$", "", prefix), matches)
465 returnMatches(matches)
467 if(exists(substr(rest, 1, dollar-1), object)) {
468 symbolFieldsCompletion(get(substr(rest, 1, dollar-1), object), substr(rest, dollar+1, nchar(rest)))
470 returnMatches(character(0))
474 returnMatches <- function(matches) {
475 nmatches <- length(matches)
479 longest <- matches[order(nchar(matches))][1]
480 while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
481 longest <- substr(longest, 1, nchar(longest)-1)
483 list(as.list(matches), longest)
486 literal2rx <- function(string) {
487 ## list of ERE metacharacters from ?regexp
488 gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
490 matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
491 nmatches <- length(matches)
492 if((nmatches == 0) && ((dollar <- regexpr("$", prefix, fixed=TRUE)) > -1)) {
493 symbolFieldsCompletion(globalenv(), prefix)
495 returnMatches(matches)
499 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
500 lineOffset <- charOffset <- colOffset <- NULL
501 for(pos in position) {
502 switch(as.character(pos[[1]]),
503 `:position` = {charOffset <- pos[[2]]},
504 `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
505 warning("unknown content in pos", pos))
507 frob <- function(refs) {
510 srcref(attr(x,"srcfile"),
511 c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
512 x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
513 ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
514 ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
516 transformSrcrefs <- function(s) {
517 srcrefs <- attr(s, "srcref")
518 attribs <- attributes(s)
521 "call"=as.call(lapply(s, transformSrcrefs)),
522 "expression"=as.expression(lapply(s, transformSrcrefs)),
524 attributes(new) <- attribs
525 if(!is.null(attr(s, "srcref"))) {
526 attr(new, "srcref") <- frob(srcrefs)
531 times <- system.time({
532 exprs <- parse(text=string, srcfile=srcfile(filename))
533 eval(transformSrcrefs(exprs), envir = globalenv()) })},
534 abort="abort compilation")
535 list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
538 withRetryRestart <- function(description, expr) {
539 call <- substitute(expr)
543 withRestarts(eval.parent(call),
544 retry=list(description=description,
545 handler=function() retry <<- TRUE))
549 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
550 withRetryRestart("retry SLIME interactive evaluation request",
551 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
553 prin1ToString(tmp$value)
559 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
560 withRetryRestart("retry SLIME interactive evaluation request",
562 capture.output(tmp <- withVisible(eval(parse(text=string),
563 envir=globalenv()))) })
564 output <- paste(output, sep="", collapse="\n")
566 list(output, prin1ToString(tmp$value))
568 list(output, "# invisible value")
572 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
573 withRetryRestart("retry SLIME interactive evaluation request",
574 tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
576 prin1ToString(tmp$value)
582 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
583 if(exists(string, envir = globalenv())) {
584 thing <- get(string, envir = globalenv())
585 if(inherits(thing, "function")) {
587 srcref <- attr(body, "srcref")
588 srcfile <- attr(body, "srcfile")
589 if(is.null(srcfile)) {
592 filename <- get("filename", srcfile)
593 ## KLUDGE: what this means is "is the srcfile filename
595 if(substr(filename, 1, 1) == "/") {
598 file <- sprintf("%s/%s", srcfile$wd, filename)
600 list(list(sprintf("function %s", string),
601 list(quote(`:location`),
602 list(quote(`:file`), file),
603 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
614 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
615 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
616 collapse="\n", sep="")
619 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
620 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
624 resetInspector <- function(slimeConnection) {
625 assign("istate", list(), envir=slimeConnection)
626 assign("inspectorHistory", NULL, envir=slimeConnection)
629 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
630 withRetryRestart("retry SLIME inspection request",
631 { resetInspector(slimeConnection)
632 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
637 inspectObject <- function(slimeConnection, object) {
638 vectorify <- function(x) {
645 previous <- slimeConnection$istate
646 slimeConnection$istate <- new.env()
647 slimeConnection$istate$object <- object
648 slimeConnection$istate$previous <- previous
649 slimeConnection$istate$content <- emacsInspect(object)
650 if(!(vectorify(object) %in% slimeConnection$inspectorHistory)) {
651 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
653 if(!is.null(slimeConnection$istate$previous)) {
654 slimeConnection$istate$previous$`next` <- slimeConnection$istate
656 istateToElisp(slimeConnection$istate)
659 valuePart <- function(istate, object, string) {
660 list(quote(`:value`),
661 if(is.null(string)) prin1ToString(object) else string,
662 assignIndexInParts(object, istate))
665 preparePart <- function(istate, part) {
666 if(is.character(part)) {
669 switch(as.character(part[[1]]),
670 `:newline` = list("\n"),
671 `:value` = valuePart(istate, part[[2]], part[[3]]),
672 `:line` = list(prin1ToString(part[[2]]), ": ",
673 valuePart(istate, part[[3]], NULL), "\n"))
677 prepareRange <- function(istate, start, end) {
678 range <- istate$content[start+1:min(end+1, length(istate$content))]
681 ps <- c(ps, preparePart(istate, part))
683 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
687 assignIndexInParts <- function(object, istate) {
688 ret <- 1+length(istate$parts)
689 istate$parts <- c(istate$parts, list(object))
693 istateToElisp <- function(istate) {
694 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
695 quote(`:id`), assignIndexInParts(istate$object, istate),
696 quote(`:content`), prepareRange(istate, 0, 500))
699 emacsInspect <- function(object) {
700 UseMethod("emacsInspect")
703 emacsInspect.default <- function(thing) {
704 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
707 emacsInspect.list <- function(list) {
708 c(list("a list", list(quote(`:newline`))),
709 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
713 emacsInspect.numeric <- function(numeric) {
714 c(list("a numeric", list(quote(`:newline`))),
715 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
716 (1:length(numeric)), numeric))
719 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
720 resetInspector(slimeConnection)
724 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
725 slimeConnection$istate$parts[[index]]
728 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
729 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
730 inspectObject(slimeConnection, object)
733 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
734 if(!is.null(slimeConnection$istate$previous)) {
735 slimeConnection$istate <- slimeConnection$istate$previous
736 istateToElisp(slimeConnection$istate)
742 `swank:inspector-next` <- function(slimeConnection, sldbState) {
743 if(!is.null(slimeConnection$istate$`next`)) {
744 slimeConnection$istate <- slimeConnection$istate$`next`
745 istateToElisp(slimeConnection$istate)
751 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
752 expr <- parse(text=string)[[1]]
753 object <- slimeConnection$istate$object
754 if(inherits(object, "list")|inherits(object, "environment")) {
755 substituted <- substituteDirect(expr, object)
756 eval(substituted, envir=globalenv())
758 eval(expr, envir=globalenv())
762 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
763 resetInspector(slimeConnection)
764 inspectObject(slimeConnection, sldbState$condition)
767 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
768 resetInspector(slimeConnection)
769 frame <- sldbState$frames[[1+frame]]
770 name <- ls(envir=frame)[[1+var]]
771 object <- get(name, envir=frame)
772 inspectObject(slimeConnection, object)
775 `swank:default-directory` <- function(slimeConnection, sldbState) {
779 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
781 `swank:default-directory`(slimeConnection, sldbState)
784 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
785 source(filename, local=FALSE, keep.source=TRUE)
789 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
790 times <- system.time(parse(filename, srcfile=srcfile(filename)))
792 ## KLUDGE: inelegant, but works. It might be more in the spirit
793 ## of things to keep the result of the parse above around to
795 `swank:load-file`(slimeConnection, sldbState, filename)
797 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
800 `swank:quit-lisp` <- function(slimeConnection, sldbState) {