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) {
47 if(kind == quote(`:emacs-rex`)) {
48 do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
52 sendToEmacs <- function(slimeConnection, obj) {
53 io <- slimeConnection$io
55 payload <- writeSexpToString(obj)
56 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
57 writeChar(payload, io, eos=NULL)
59 cat(sprintf("%06x", nchar(payload)), payload, sep="")
62 callify <- function(form) {
63 ## we implement here the conversion from Lisp S-expression (or list)
64 ## expressions of code into our own, swankr, calling convention,
65 ## with slimeConnection and sldbState as first and second arguments.
66 ## as.call() gets us part of the way, but we need to walk the list
67 ## recursively to mimic CL:EVAL; we need to avoid converting R
68 ## special operators which we are punning (only `quote`, for now)
69 ## into this calling convention.
71 if(form[[1]] == quote(quote)) {
74 as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
81 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
89 }, error=function(c) {
90 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
91 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
92 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
95 makeSldbState <- function(condition, level, id) {
96 calls <- rev(sys.calls())[-1]
97 frames <- rev(sys.frames())[-1]
98 restarts <- rev(computeRestarts(condition))[-1]
99 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
100 class(ret) <- c("sldbState", class(ret))
104 sldbLoop <- function(slimeConnection, sldbState, id) {
106 io <- slimeConnection$io
107 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
108 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
110 dispatch(slimeConnection, readPacket(io), sldbState)
112 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
115 readPacket <- function(io) {
116 socketSelect(list(io))
117 header <- readChunk(io, 6)
118 len <- strtoi(header, base=16)
119 payload <- readChunk(io, len)
120 readSexpFromString(payload)
123 readChunk <- function(io, len) {
124 buffer <- readChar(io, len)
125 if(nchar(buffer) != len) {
126 stop("short read in readChunk")
131 readSexpFromString <- function(string) {
135 char <- substr(string, pos, pos)
141 if(pos > nchar(string))
142 stop("EOF during read")
143 obj <- readNumberOrSymbol()
144 if(obj == quote(`.`)) {
145 stop("Consing dot not implemented")
150 skipWhitespace <- function() {
151 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
155 readList <- function() {
160 char <- substr(string, pos, pos)
166 if(length(obj) == 1 && obj == quote(`.`)) {
167 stop("Consing dot not implemented")
169 ret <- c(ret, list(obj))
174 readString <- function() {
176 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
179 char <- substr(string, pos, pos)
181 "\""={ pos <<- pos + 1; break },
182 "\\"={ pos <<- pos + 1
183 char2 <- substr(string, pos, pos)
187 stop("Unrecognized escape character")) },
192 readNumberOrSymbol <- function() {
194 if(nchar(token)==0) {
195 stop("End of file reading token")
196 } else if(grepl("^[0-9]+$", token)) {
198 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
204 readToken <- function() {
207 char <- substr(string, pos, pos)
210 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
213 token <- paste(token, char, sep="")
222 writeSexpToString <- function(obj) {
223 writeSexpToStringLoop <- function(obj) {
225 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
226 "list"={ string <- paste(string, "(", sep="")
230 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
232 string <- paste(string, " ", sep="")
236 string <- paste(string, ")", sep="") },
237 "symbol"={ string <- paste(string, as.character(obj), sep="") },
238 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
239 "double"={ string <- paste(string, as.character(obj), sep="") },
240 "integer"={ string <- paste(string, as.character(obj), sep="") },
241 stop(paste("can't write object ", obj, sep="")))
245 writeSexpToStringLoop(obj)
248 prin1ToString <- function(val) {
249 paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
250 sep="", collapse="\n")
253 printToString <- function(val) {
254 paste(capture.output(print(val)), sep="", collapse="\n")
257 `swank:connection-info` <- function (slimeConnection, sldbState) {
258 list(quote(`:pid`), Sys.getpid(),
259 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
260 quote(`:lisp-implementation`), list(quote(`:type`), "R",
262 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
265 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
266 for(contrib in contribs) {
267 filename <- sprintf("%s.R", as.character(contrib))
268 if(file.exists(filename)) {
269 source(filename, verbose=TRUE)
275 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
279 makeReplResult <- function(value) {
280 string <- printToString(value)
281 list(quote(`:write-string`), string,
282 quote(`:repl-result`))
285 makeReplResultFunction <- makeReplResult
287 sendReplResult <- function(slimeConnection, value) {
288 result <- makeReplResultFunction(value)
289 sendToEmacs(slimeConnection, result)
292 sendReplResultFunction <- sendReplResult
294 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
295 string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
296 expr <- parse(text=string)[[1]]
297 lookedup <- do.call("bquote", list(expr))
298 value <- eval(lookedup, envir = globalenv())
299 sendReplResultFunction(slimeConnection, value)
303 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
304 "No Arglist Information"
307 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
311 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
312 condition <- simpleCondition("Throw to toplevel")
313 class(condition) <- c("swankTopLevel", class(condition))
314 signalCondition(condition)
317 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
318 calls <- sldbState$calls
319 if(is.null(to)) to <- length(calls)
321 calls <- lapply(calls[from:to],
322 { frameNumber <- from-1;
324 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
325 frameNumber <<- 1+frameNumber
331 computeRestartsForEmacs <- function (sldbState) {
332 lapply(sldbState$restarts,
334 ## this is all a little bit internalsy
335 restartName <- x[[1]][[1]]
336 description <- restartDescription(x)
337 list(restartName, if(is.null(description)) restartName else description)
341 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
342 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
343 computeRestartsForEmacs(sldbState),
344 `swank:backtrace`(slimeConnection, sldbState, from, to),
348 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
349 if(sldbState$level == level) {
350 invokeRestart(sldbState$restarts[[n+1]])
354 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
355 call <- sldbState$calls[[n+1]]
356 srcref <- attr(call, "srcref")
357 srcfile <- attr(srcref, "srcfile")
358 if(is.null(srcfile)) {
359 list(quote(`:error`), "no srcfile")
361 list(quote(`:location`),
362 list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
363 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
368 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
372 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
373 frame <- sldbState$frames[[1+index]]
374 withRetryRestart("retry SLIME interactive evaluation request",
375 value <- eval(parse(text=string), envir=frame))
379 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
380 str(sldbState$frames)
381 frame <- sldbState$frames[[1+index]]
382 objs <- ls(envir=frame)
383 list(lapply(objs, function(name) { list(quote(`:name`), name,
385 quote(`:value`), printToString(eval(parse(text=name), envir=frame))) }),
389 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
390 ## fails multiply if prefix contains regexp metacharacters
391 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
392 nmatches <- length(matches)
396 longest <- matches[order(nchar(matches))][1]
397 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
398 longest <- substr(longest, 1, nchar(longest)-1)
400 list(as.list(matches), longest)
404 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
405 # FIXME: I think in parse() here we can use srcref to associate
406 # buffer/filename/position to the objects. Or something.
407 withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
408 abort="abort compilation")
409 list(quote(`:compilation-result`), list(), TRUE, times[3])
412 withRetryRestart <- function(description, expr) {
413 call <- substitute(expr)
417 withRestarts(eval.parent(call),
418 retry=list(description=description,
419 handler=function() retry <<- TRUE))
423 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
424 withRetryRestart("retry SLIME interactive evaluation request",
425 value <- eval(parse(text=string), envir=globalenv()))
429 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
430 withRetryRestart("retry SLIME interactive evaluation request",
432 capture.output(value <- eval(parse(text=string),
433 envir=globalenv())) })
434 output <- paste(output, sep="", collapse="\n")
435 list(output, prin1ToString(value))
438 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
439 if(exists(string, envir = globalenv())) {
440 thing <- get(string, envir = globalenv())
441 if(inherits(thing, "function")) {
443 srcref <- attr(body, "srcref")
444 srcfile <- attr(body, "srcfile")
445 if(is.null(srcfile)) {
448 filename <- get("filename", srcfile)
449 list(list(sprintf("function %s", string),
450 list(quote(`:location`),
451 list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
452 list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
463 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
464 paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
465 collapse="\n", sep="")
468 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
469 eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
473 resetInspector <- function(slimeConnection) {
474 assign("istate", list(), envir=slimeConnection)
475 assign("inspectorHistory", NULL, envir=slimeConnection)
478 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
479 withRetryRestart("retry SLIME inspection request",
480 { resetInspector(slimeConnection)
481 value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
486 inspectObject <- function(slimeConnection, object) {
487 previous <- slimeConnection$istate
488 slimeConnection$istate <- new.env()
489 slimeConnection$istate$object <- object
490 slimeConnection$istate$previous <- previous
491 slimeConnection$istate$content <- emacsInspect(object)
492 if(!(object %in% slimeConnection$inspectorHistory)) {
493 slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
495 if(!is.null(slimeConnection$istate$previous)) {
496 slimeConnection$istate$previous$`next` <- slimeConnection$istate
498 istateToElisp(slimeConnection$istate)
501 valuePart <- function(istate, object, string) {
502 list(quote(`:value`),
503 if(is.null(string)) printToString(object) else string,
504 assignIndexInParts(object, istate))
507 preparePart <- function(istate, part) {
508 if(is.character(part)) {
511 switch(as.character(part[[1]]),
512 `:newline` = list("\n"),
513 `:value` = valuePart(istate, part[[2]], part[[3]]),
514 `:line` = list(printToString(part[[2]]), ": ",
515 valuePart(istate, part[[3]], NULL), "\n"))
519 prepareRange <- function(istate, start, end) {
520 range <- istate$content[start+1:min(end+1, length(istate$content))]
523 ps <- c(ps, preparePart(istate, part))
525 list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
529 assignIndexInParts <- function(object, istate) {
530 ret <- 1+length(istate$parts)
531 istate$parts <- c(istate$parts, list(object))
535 istateToElisp <- function(istate) {
536 list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
537 quote(`:id`), assignIndexInParts(istate$object, istate),
538 quote(`:content`), prepareRange(istate, 0, 500))
541 emacsInspect <- function(object) {
542 UseMethod("emacsInspect")
545 emacsInspect.default <- function(thing) {
546 c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
549 emacsInspect.list <- function(list) {
550 c(list("a list", list(quote(`:newline`))),
551 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
555 emacsInspect.numeric <- function(numeric) {
556 c(list("a numeric", list(quote(`:newline`))),
557 mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
558 (1:length(numeric)), numeric))
561 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
562 resetInspector(slimeConnection)
566 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
567 slimeConnection$istate$parts[[index]]
570 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
571 object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
572 inspectObject(slimeConnection, object)
575 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
576 if(!is.null(slimeConnection$istate$previous)) {
577 slimeConnection$istate <- slimeConnection$istate$previous
578 istateToElisp(slimeConnection$istate)
584 `swank:inspector-next` <- function(slimeConnection, sldbState) {
585 if(!is.null(slimeConnection$istate$`next`)) {
586 slimeConnection$istate <- slimeConnection$istate$`next`
587 istateToElisp(slimeConnection$istate)
593 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
594 expr <- parse(text=string)[[1]]
595 object <- slimeConnection$istate$object
596 if(inherits(object, "list")|inherits(object, "environment")) {
597 substituted <- substituteDirect(expr, object)
598 eval(substituted, envir=globalenv())
600 eval(expr, envir=globalenv())
604 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
605 resetInspector(slimeConnection)
606 inspectObject(slimeConnection, sldbState$condition)
609 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
610 resetInspector(slimeConnection)
611 frame <- sldbState$frames[[1+frame]]
612 name <- ls(envir=frame)[[1+var]]
613 object <- get(name, envir=frame)
614 inspectObject(slimeConnection, object)
617 `swank:default-directory` <- function(slimeConnection, sldbState) {
621 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
623 `swank:default-directory`(slimeConnection, sldbState)
626 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
627 source(filename, local=FALSE)
631 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
632 times <- system.time(parse(filename))
633 list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)