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) {
36 withRestarts(tryCatch(dispatch(io, readPacket(io)),
37 swankTopLevel=function(c) NULL),
38 abort="return to SLIME's toplevel")
42 dispatch <- function(io, event, sldbState=NULL) {
45 if(kind == quote(`:emacs-rex`)) {
46 do.call("emacsRex", c(list(io), list(sldbState), event[-1]))
50 sendToEmacs <- function(io, obj) {
52 payload <- writeSexpToString(obj)
53 writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
54 writeChar(payload, io, eos=NULL)
56 cat(sprintf("%06x", nchar(payload)), payload, sep="")
59 emacsRex <- function(io, sldbState, form, pkg, thread, id, level=0) {
64 value <- do.call(eval(form[[1]]), c(list(io), list(sldbState), form[-1]))
66 }, error=function(c) {
67 newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
68 withRestarts(sldbLoop(io, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
69 finally=sendToEmacs(io, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
72 makeSldbState <- function(condition, level, id) {
73 calls <- rev(sys.calls())[-1]
74 frames <- rev(sys.frames())[-1]
75 restarts <- rev(computeRestarts(condition))[-1]
76 ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
77 class(ret) <- c("sldbState", class(ret))
81 sldbLoop <- function(io, sldbState, id) {
83 sendToEmacs(io, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(io, sldbState)))
84 sendToEmacs(io, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
86 dispatch(io, readPacket(io), sldbState)
88 }, finally=sendToEmacs(io, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
91 readPacket <- function(io) {
92 header <- readChunk(io, 6)
93 len <- strtoi(header, base=16)
94 payload <- readChunk(io, len)
95 readSexpFromString(payload)
98 readChunk <- function(io, len) {
99 buffer <- readChar(io, len)
100 if(nchar(buffer) != len) {
101 stop("short read in readChunk")
106 readSexpFromString <- function(string) {
110 char <- substr(string, pos, pos)
116 if(pos > nchar(string))
117 stop("EOF during read")
118 obj <- readNumberOrSymbol()
119 if(obj == quote(`.`)) {
120 stop("Consing dot not implemented")
125 skipWhitespace <- function() {
126 while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
130 readList <- function() {
135 char <- substr(string, pos, pos)
141 if(length(obj) == 1 && obj == quote(`.`)) {
142 stop("Consing dot not implemented")
144 ret <- c(ret, list(obj))
149 readString <- function() {
151 addChar <- function(c) { ret <<- paste(ret, c, sep="") }
154 char <- substr(string, pos, pos)
156 "\""={ pos <<- pos + 1; break },
157 "\\"={ pos <<- pos + 1
158 char2 <- substr(string, pos, pos)
162 stop("Unrecognized escape character")) },
167 readNumberOrSymbol <- function() {
169 if(nchar(token)==0) {
170 stop("End of file reading token")
171 } else if(grepl("^[0-9]+$", token)) {
173 } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
179 readToken <- function() {
182 char <- substr(string, pos, pos)
185 } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
188 token <- paste(token, char, sep="")
197 writeSexpToString <- function(obj) {
198 writeSexpToStringLoop <- function(obj) {
200 "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
201 "list"={ string <- paste(string, "(", sep="")
205 string <- paste(string, writeSexpToString(obj[[i]]), sep="")
207 string <- paste(string, " ", sep="")
211 string <- paste(string, ")", sep="") },
212 "symbol"={ string <- paste(string, as.character(obj), sep="") },
213 "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
214 "double"={ string <- paste(string, as.character(obj), sep="") },
215 "integer"={ string <- paste(string, as.character(obj), sep="") },
216 stop(paste("can't write object ", obj, sep="")))
220 writeSexpToStringLoop(obj)
223 printToString <- function(val) {
225 tryCatch({ sink(f); print(val); sink(); readLines(f) },
229 `swank:connection-info` <- function (io, sldbState) {
230 list(quote(`:pid`), Sys.getpid(),
231 quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
232 quote(`:lisp-implementation`), list(quote(`:type`), "R",
234 quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
237 `swank:swank-require` <- function (io, sldbState, contribs) {
241 `swank:create-repl` <- function(io, sldbState, env, ...) {
245 `swank:listener-eval` <- function(io, sldbState, string) {
246 val <- eval(parse(text=string), envir = globalenv())
247 string <- printToString(val)
248 list(quote(`:values`), paste(string, collapse="\n"))
251 `swank:autodoc` <- function(io, sldbState, rawForm, ...) {
252 "No Arglist Information"
255 `swank:operator-arglist` <- function(io, sldbState, op, package) {
259 `swank:throw-to-toplevel` <- function(io, sldbState) {
260 condition <- simpleCondition("Throw to toplevel")
261 class(condition) <- c("swankTopLevel", class(condition))
262 signalCondition(condition)
265 `swank:backtrace` <- function(io, sldbState, from=0, to=NULL) {
266 calls <- sldbState$calls
267 if(is.null(to)) to <- length(calls)
269 calls <- lapply(calls[from:to],
270 { frameNumber <- from-1;
272 ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
273 frameNumber <<- 1+frameNumber
279 computeRestartsForEmacs <- function (sldbState) {
280 lapply(sldbState$restarts,
282 ## this is all a little bit internalsy
283 restartName <- x[[1]][[1]]
284 description <- restartDescription(x)
285 list(restartName, if(is.null(description)) restartName else description)
289 `swank:debugger-info-for-emacs` <- function(io, sldbState, from=0, to=NULL) {
290 list(list(as.character(sldbState$condition), sprintf(" [%s]", class(sldbState$condition)[[1]]), FALSE),
291 computeRestartsForEmacs(sldbState),
292 `swank:backtrace`(io, sldbState, from, to),
296 `swank:invoke-nth-restart-for-emacs` <- function(io, sldbState, level, n) {
297 if(sldbState$level == level) {
298 invokeRestart(sldbState$restarts[[n+1]])
302 `swank:frame-source-location` <- function(io, sldbState, n) {
303 call <- sldbState$calls[[n+1]]
304 srcref <- attr(call, "srcref")
305 srcfile <- attr(srcref, "srcfile")
306 if(is.null(srcfile)) {
307 list(quote(`:error`), "no srcfile")
309 filename <- get("filename", srcfile)
310 list(quote(`:location`),
311 list(quote(`:file`), filename),
312 list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
317 `swank:buffer-first-change` <- function(io, sldbState, filename) {
321 `swank:frame-locals-and-catch-tags` <- function(io, sldbState, index) {
322 str(sldbState$frames)
323 frame <- sldbState$frames[[1+index]]
324 objs <- ls(envir=frame)
325 list(lapply(objs, function(name) { list(quote(`:name`), name,
327 quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
331 `swank:simple-completions` <- function(io, sldbState, prefix, package) {
332 ## fails multiply if prefix contains regexp metacharacters
333 matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
334 nmatches <- length(matches)
338 longest <- matches[order(nchar(matches))][1]
339 while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
340 longest <- substr(longest, 1, nchar(longest)-1)
342 list(as.list(matches), longest)
346 `swank:compile-string-for-emacs` <- function(io, sldbState, string, buffer, position, filename, policy) {
347 # FIXME: I think in parse() here we can use srcref to associate
348 # buffer/filename/position to the objects. Or something.
349 withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
350 abort="abort compilation")
351 list(quote(`:compilation-result`), list(), TRUE, times[3])
354 `swank:interactive-eval` <- 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))
365 `swank:eval-and-grab-output` <- function(io, sldbState, string) {
374 withRestarts(value <- eval(parse(text=string), envir = globalenv()),
375 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
376 finally={sink(); output <- readLines(f); close(f)})
377 list(output, printToString(value))