1 swank <- function(port=4005) {
2 acceptConnections(port, FALSE)
5 startSwank <- function(portFile) {
6 acceptConnections(FALSE, portFile)
9 acceptConnections <- function(port, portFile) {
10 s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
15 serve <- function(io) {
19 mainLoop <- function(io) {
21 withRestarts(tryCatch(dispatch(io, readPacket(io)),
22 swankTopLevel=function(c) NULL),
23 abort="return to SLIME's toplevel")
27 dispatch <- function(io, event, sldbState=NULL) {
30 if(kind == quote(`:emacs-rex`)) {
31 do.call("emacsRex", c(list(io), list(sldbState), event[-1]))
35 sendToEmacs <- function(io, obj) {
37 payload <- writeSexpToString(obj)
38 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
39 writeChar(payload, io, eos=NULL)
41 cat(sprintf("%06x", nchar(payload)), payload, sep="")
44 emacsRex <- function(io, sldbState, form, pkg, thread, id, level=0) {
49 value <- do.call(eval(form[[1]]), c(list(io), list(sldbState), form[-1]))
51 }, error=function(c) {
52 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
53 withRestarts(sldbLoop(io, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
54 finally=sendToEmacs(io, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
57 makeSldbState <- function(condition, level, id) {
58 calls <- rev(sys.calls())[-1]
59 frames <- rev(sys.frames())[-1]
60 restarts <- rev(computeRestarts(condition))[-1]
61 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
62 class(ret) <- c("sldbState", class(ret))
66 sldbLoop <- function(io, sldbState, id) {
68 sendToEmacs(io, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(io, sldbState)))
69 sendToEmacs(io, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
71 dispatch(io, readPacket(io), sldbState)
73 }, finally=sendToEmacs(io, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
76 readPacket <- function(io) {
77 header <- readChunk(io, 6)
78 len <- strtoi(header, base=16)
79 payload <- readChunk(io, len)
80 readSexpFromString(payload)
83 readChunk <- function(io, len) {
84 buffer <- readChar(io, len)
85 if(nchar(buffer) != len) {
86 stop("short read in readChunk")
91 readSexpFromString <- function(string) {
95 char <- substr(string, pos, pos)
101 if(pos > nchar(string))
102 stop("EOF during read")
103 obj <- readNumberOrSymbol()
104 if(obj == quote(`.`)) {
105 stop("Consing dot not implemented")
110 skipWhitespace <- function() {
111 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
115 readList <- function() {
120 char <- substr(string, pos, pos)
126 if(length(obj) == 1 && obj == quote(`.`)) {
127 stop("Consing dot not implemented")
129 ret <- c(ret, list(obj))
134 readString <- function() {
136 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
139 char <- substr(string, pos, pos)
141 "\""={ pos <<- pos + 1; break },
142 "\\"={ pos <<- pos + 1
143 char2 <- substr(string, pos, pos)
147 stop("Unrecognized escape character")) },
152 readNumberOrSymbol <- function() {
154 if(nchar(token)==0) {
155 stop("End of file reading token")
156 } else if(grepl("^[0-9]+$", token)) {
158 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
164 readToken <- function() {
167 char <- substr(string, pos, pos)
170 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
173 token <- paste(token, char, sep="")
182 writeSexpToString <- function(obj) {
183 writeSexpToStringLoop <- function(obj) {
185 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
186 "list"={ string <- paste(string, "(", sep="")
190 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
192 string <- paste(string, " ", sep="")
196 string <- paste(string, ")", sep="") },
197 "symbol"={ string <- paste(string, as.character(obj), sep="") },
198 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
199 "double"={ string <- paste(string, as.character(obj), sep="") },
200 "integer"={ string <- paste(string, as.character(obj), sep="") },
201 stop(paste("can't write object ", obj, sep="")))
205 writeSexpToStringLoop(obj)
208 printToString <- function(val) {
210 tryCatch({ sink(f); print(val); sink(); readLines(f) },
214 `swank:connection-info` <- function (io, sldbState) {
215 list(quote(`:pid`), Sys.getpid(),
216 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
217 quote(`:lisp-implementation`), list(quote(`:type`), "R",
219 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
222 `swank:swank-require` <- function (io, sldbState, contribs) {
226 `swank:create-repl` <- function(io, sldbState, env, ...) {
230 `swank:listener-eval` <- function(io, sldbState, string) {
231 val <- eval(parse(text=string), envir = globalenv())
232 string <- printToString(val)
233 list(quote(`:values`), paste(string, collapse="\n"))
236 `swank:autodoc` <- function(io, sldbState, rawForm, ...) {
237 "No Arglist Information"
240 `swank:operator-arglist` <- function(io, sldbState, op, package) {
244 `swank:throw-to-toplevel` <- function(io, sldbState) {
245 condition <- simpleCondition("Throw to toplevel")
246 class(condition) <- c("swankTopLevel", class(condition))
247 signalCondition(condition)
250 `swank:backtrace` <- function(io, sldbState, from=0, to=NULL) {
251 calls <- sldbState$calls
252 if(is.null(to)) to <- length(calls)
254 calls <- lapply(calls[from:to],
255 { frameNumber <- from-1;
257 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
258 frameNumber <<- 1+frameNumber
264 computeRestartsForEmacs <- function (sldbState) {
265 lapply(sldbState$restarts,
267 ## this is all a little bit internalsy
268 restartName <- x[[1]][[1]]
269 description <- restartDescription(x)
270 list(restartName, if(is.null(description)) restartName else description)
274 `swank:debugger-info-for-emacs` <- function(io, sldbState, from=0, to=NULL) {
275 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
276 computeRestartsForEmacs(sldbState),
277 `swank:backtrace`(io, sldbState, from, to),
281 `swank:invoke-nth-restart-for-emacs` <- function(io, sldbState, level, n) {
282 if(sldbState$level == level) {
283 invokeRestart(sldbState$restarts[[n+1]])
287 `swank:frame-source-location` <- function(io, sldbState, n) {
288 call <- sldbState$calls[[n+1]]
289 srcref <- attr(call, "srcref")
290 srcfile <- attr(srcref, "srcfile")
291 if(is.null(srcfile)) {
292 list(quote(`:error`), "no srcfile")
294 filename <- get("filename", srcfile)
295 list(quote(`:location`),
296 list(quote(`:file`), filename),
297 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
302 `swank:buffer-first-change` <- function(io, sldbState, filename) {
306 `swank:frame-locals-and-catch-tags` <- function(io, sldbState, index) {
307 str(sldbState$frames)
308 frame <- sldbState$frames[[1+index]]
309 objs <- ls(envir=frame)
310 list(lapply(objs, function(name) { list(quote(`:name`), name,
312 quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
316 `swank:simple-completions` <- function(io, sldbState, prefix, package) {
317 ## fails multiply if prefix contains regexp metacharacters
318 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
319 nmatches <- length(matches)
323 longest <- matches[order(nchar(matches))][1]
324 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
325 longest <- substr(longest, 1, nchar(longest)-1)
327 list(as.list(matches), longest)
331 `swank:compile-string-for-emacs` <- function(io, sldbState, string, buffer, position, filename, policy) {
332 # FIXME: I think in parse() here we can use srcref to associate
333 # buffer/filename/position to the objects. Or something.
334 withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
335 abort="abort compilation")
336 list(quote(`:compilation-result`), list(), TRUE, times[3])
339 `swank:interactive-eval` <- function(io, sldbState, string) {
344 withRestarts(value <- eval(parse(text=string), envir = globalenv()),
345 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))
350 `swank:eval-and-grab-output` <- function(io, sldbState, string) {
359 withRestarts(value <- eval(parse(text=string), envir = globalenv()),
360 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
361 finally={sink(); output <- readLines(f); close(f)})
362 list(output, printToString(value))