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 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
67 value <- do.call(eval(form[[1]]), c(list(slimeConnection), list(sldbState), form[-1]))
69 }, error=function(c) {
70 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
71 withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
72 finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
75 makeSldbState <- function(condition, level, id) {
76 calls <- rev(sys.calls())[-1]
77 frames <- rev(sys.frames())[-1]
78 restarts <- rev(computeRestarts(condition))[-1]
79 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
80 class(ret) <- c("sldbState", class(ret))
84 sldbLoop <- function(slimeConnection, sldbState, id) {
86 io <- slimeConnection$io
87 sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
88 sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
90 dispatch(slimeConnection, readPacket(io), sldbState)
92 }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
95 readPacket <- function(io) {
96 header <- readChunk(io, 6)
97 len <- strtoi(header, base=16)
98 payload <- readChunk(io, len)
99 readSexpFromString(payload)
102 readChunk <- function(io, len) {
103 buffer <- readChar(io, len)
104 if(nchar(buffer) != len) {
105 stop("short read in readChunk")
110 readSexpFromString <- function(string) {
114 char <- substr(string, pos, pos)
120 if(pos > nchar(string))
121 stop("EOF during read")
122 obj <- readNumberOrSymbol()
123 if(obj == quote(`.`)) {
124 stop("Consing dot not implemented")
129 skipWhitespace <- function() {
130 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
134 readList <- function() {
139 char <- substr(string, pos, pos)
145 if(length(obj) == 1 && obj == quote(`.`)) {
146 stop("Consing dot not implemented")
148 ret <- c(ret, list(obj))
153 readString <- function() {
155 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
158 char <- substr(string, pos, pos)
160 "\""={ pos <<- pos + 1; break },
161 "\\"={ pos <<- pos + 1
162 char2 <- substr(string, pos, pos)
166 stop("Unrecognized escape character")) },
171 readNumberOrSymbol <- function() {
173 if(nchar(token)==0) {
174 stop("End of file reading token")
175 } else if(grepl("^[0-9]+$", token)) {
177 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
183 readToken <- function() {
186 char <- substr(string, pos, pos)
189 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
192 token <- paste(token, char, sep="")
201 writeSexpToString <- function(obj) {
202 writeSexpToStringLoop <- function(obj) {
204 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
205 "list"={ string <- paste(string, "(", sep="")
209 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
211 string <- paste(string, " ", sep="")
215 string <- paste(string, ")", sep="") },
216 "symbol"={ string <- paste(string, as.character(obj), sep="") },
217 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
218 "double"={ string <- paste(string, as.character(obj), sep="") },
219 "integer"={ string <- paste(string, as.character(obj), sep="") },
220 stop(paste("can't write object ", obj, sep="")))
224 writeSexpToStringLoop(obj)
227 printToString <- function(val) {
229 tryCatch({ sink(f); print(val); sink(); readLines(f) },
233 `swank:connection-info` <- function (slimeConnection, sldbState) {
234 list(quote(`:pid`), Sys.getpid(),
235 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
236 quote(`:lisp-implementation`), list(quote(`:type`), "R",
238 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
241 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
245 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
249 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
250 val <- eval(parse(text=string), envir = globalenv())
251 string <- printToString(val)
252 sendToEmacs(slimeConnection, list(quote(`:write-string`), paste(string, collapse="\n"), quote(`:repl-result`)))
256 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
257 "No Arglist Information"
260 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
264 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
265 condition <- simpleCondition("Throw to toplevel")
266 class(condition) <- c("swankTopLevel", class(condition))
267 signalCondition(condition)
270 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
271 calls <- sldbState$calls
272 if(is.null(to)) to <- length(calls)
274 calls <- lapply(calls[from:to],
275 { frameNumber <- from-1;
277 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
278 frameNumber <<- 1+frameNumber
284 computeRestartsForEmacs <- function (sldbState) {
285 lapply(sldbState$restarts,
287 ## this is all a little bit internalsy
288 restartName <- x[[1]][[1]]
289 description <- restartDescription(x)
290 list(restartName, if(is.null(description)) restartName else description)
294 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
295 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
296 computeRestartsForEmacs(sldbState),
297 `swank:backtrace`(slimeConnection, sldbState, from, to),
301 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
302 if(sldbState$level == level) {
303 invokeRestart(sldbState$restarts[[n+1]])
307 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
308 call <- sldbState$calls[[n+1]]
309 srcref <- attr(call, "srcref")
310 srcfile <- attr(srcref, "srcfile")
311 if(is.null(srcfile)) {
312 list(quote(`:error`), "no srcfile")
314 filename <- get("filename", srcfile)
315 list(quote(`:location`),
316 list(quote(`:file`), filename),
317 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
322 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
326 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
327 str(sldbState$frames)
328 frame <- sldbState$frames[[1+index]]
329 objs <- ls(envir=frame)
330 list(lapply(objs, function(name) { list(quote(`:name`), name,
332 quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
336 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
337 ## fails multiply if prefix contains regexp metacharacters
338 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
339 nmatches <- length(matches)
343 longest <- matches[order(nchar(matches))][1]
344 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
345 longest <- substr(longest, 1, nchar(longest)-1)
347 list(as.list(matches), longest)
351 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
352 # FIXME: I think in parse() here we can use srcref to associate
353 # buffer/filename/position to the objects. Or something.
354 withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
355 abort="abort compilation")
356 list(quote(`:compilation-result`), list(), TRUE, times[3])
359 `swank:interactive-eval` <- function(slimeConnection, sldbState, string) {
364 withRestarts(value <- eval(parse(text=string), envir = globalenv()),
365 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))
370 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
379 withRestarts(value <- eval(parse(text=string), envir = globalenv()),
380 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
381 finally={sink(); output <- readLines(f); close(f)})
382 list(output, printToString(value))