Christophe Weblog Wiki Code Publications Music
05b1c784f6aca534b4361349ba05adb9cc732529
[swankr.git] / swank.R
1 swank <- function(port=4005) {
2   acceptConnections(port, FALSE)
3 }
4
5 startSwank <- function(portFile) {
6   acceptConnections(FALSE, portFile)
7 }
8
9 acceptConnections <- function(port, portFile) {
10   s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
11   on.exit(close(s))
12   serve(s)
13 }
14
15 serve <- function(io) {
16   mainLoop(io)
17 }
18
19 mainLoop <- function(io) {
20   while(TRUE) {
21     withRestarts(tryCatch(dispatch(io, readPacket(io)),
22                           swankTopLevel=function(c) NULL),
23                  abort="return to SLIME's toplevel")
24   }
25 }
26
27 dispatch <- function(io, event, sldbState=NULL) {
28   str(event)
29   kind <- event[[1]]
30   if(kind == quote(`:emacs-rex`)) {
31     do.call("emacsRex", c(list(io), list(sldbState), event[-1]))
32   }
33 }
34
35 sendToEmacs <- function(io, obj) {
36   str(obj)
37   payload <- writeSexpToString(obj)
38   writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
39   writeChar(payload, io, eos=NULL)
40   flush(io)
41   cat(sprintf("%06x", nchar(payload)), payload, sep="")
42 }
43
44 emacsRex <- function(io, sldbState, form, pkg, thread, id, level=0) {
45   ok <- FALSE
46   value <- NULL
47   tryCatch({
48     withCallingHandlers({
49       value <- do.call(eval(form[[1]]), c(list(io), list(sldbState), form[-1]))
50       ok <- TRUE
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)))
55 }
56
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))
63   ret
64 }
65
66 sldbLoop <- function(io, sldbState, id) {
67   tryCatch({
68     sendToEmacs(io, c(list(quote(`:debug`), id, sldbState$level), debuggerInfoForEmacs(sldbState)))
69     sendToEmacs(io, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
70     while(TRUE) {
71       dispatch(io, readPacket(io), sldbState)
72     }
73   }, finally=sendToEmacs(io, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
74 }
75
76 debuggerInfoForEmacs <- function(sldbState, from=0, to=NULL) {
77   backtraceForEmacs <- function() {
78     calls <- sldbState$calls
79     if(is.null(to)) to <- length(calls)
80     from <- from+1
81     calls <- lapply(calls[from:to], { frameNumber <- from-1;
82                              function (x) { ret <- list(frameNumber, paste(format(x), sep="", collapse=" ")); frameNumber <<- 1+frameNumber; ret }})
83   }
84   computeRestartsForEmacs <- function () {
85     lapply(sldbState$restarts,
86            function(x) {
87              ## this is all a little bit internalsy
88              restartName <- x[[1]][[1]]
89              description <- restartDescription(x)
90              list(restartName, if(is.null(description)) restartName else description)
91            })
92   }
93   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
94        computeRestartsForEmacs(),
95        backtraceForEmacs(),
96        list(sldbState$id))
97 }
98
99 readPacket <- function(io) {
100   header <- readChunk(io, 6)
101   len <- strtoi(header, base=16)
102   payload <- readChunk(io, len)
103   readSexpFromString(payload)
104 }
105
106 readChunk <- function(io, len) {
107   buffer <- readChar(io, len)
108   if(nchar(buffer) != len) {
109     stop("short read in readChunk")
110   }
111   buffer
112 }
113
114 readSexpFromString <- function(string) {
115   pos <- 1
116   read <- function() {
117     skipWhitespace()
118     char <- substr(string, pos, pos)
119     switch(char,
120            "("=readList(),
121            "\""=readString(),
122            "'"=readQuote(),
123            {
124              if(pos > nchar(string))
125                stop("EOF during read")
126              obj <- readNumberOrSymbol()
127              if(obj == quote(`.`)) {
128                stop("Consing dot not implemented")
129              }
130              obj
131            })
132   }
133   skipWhitespace <- function() {
134     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
135       pos <<- pos + 1
136     }
137   }
138   readList <- function() {
139     ret <- list()
140     pos <<- pos + 1
141     while(TRUE) {
142       skipWhitespace()
143       char <- substr(string, pos, pos)
144       if(char == ")") {
145         pos <<- pos + 1
146         break
147       } else {
148         obj <- read()
149         if(length(obj) == 1 && obj == quote(`.`)) {
150           stop("Consing dot not implemented")
151         }
152         ret <- c(ret, list(obj))
153       }
154     }
155     ret
156   }
157   readString <- function() {
158     ret <- ""
159     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
160     while(TRUE) {
161       pos <<- pos + 1
162       char <- substr(string, pos, pos)
163       switch(char,
164              "\""={ pos <<- pos + 1; break },
165              "\\"={ pos <<- pos + 1
166                     char2 <- substr(string, pos, pos)
167                     switch(char2,
168                            "\""=addChar(char2),
169                            "\\"=addChar(char2),
170                            stop("Unrecognized escape character")) },
171              addChar(char))
172     }
173     ret
174   }
175   readNumberOrSymbol <- function() {
176     token <- readToken()
177     if(nchar(token)==0) {
178       stop("End of file reading token")
179     } else if(grepl("^[0-9]+$", token)) {
180       strtoi(token)
181     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
182       as.double(token)
183     } else {
184       as.name(token)
185     }
186   }
187   readToken <- function() {
188     token <- ""
189     while(TRUE) {
190       char <- substr(string, pos, pos)
191       if(char == "") {
192         break;
193       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
194         break;
195       } else {
196         token <- paste(token, char, sep="")
197         pos <<- pos + 1
198       }
199     }
200     token
201   }
202   read()
203 }
204
205 writeSexpToString <- function(obj) {
206   writeSexpToStringLoop <- function(obj) {
207     switch(typeof(obj),
208            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
209            "list"={ string <- paste(string, "(", sep="")
210                     max <- length(obj)
211                     if(max > 0) {
212                       for(i in 1:max) {
213                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
214                         if(i != max) {
215                           string <- paste(string, " ", sep="")
216                         }
217                       }
218                     }
219                     string <- paste(string, ")", sep="") },
220            "symbol"={ string <- paste(string, as.character(obj), sep="") },
221            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
222            "double"={ string <- paste(string, as.character(obj), sep="") },
223            "integer"={ string <- paste(string, as.character(obj), sep="") },
224            stop(paste("can't write object ", obj, sep="")))
225     string
226   }
227   string <- ""
228   writeSexpToStringLoop(obj)
229 }
230
231 printToString <- function(val) {
232   f <- fifo("")
233   tryCatch({ sink(f); print(val); sink(); readLines(f) },
234            finally=close(f))
235 }
236
237 `swank:connection-info` <- function (io, sldbState) {
238   list(quote(`:pid`), Sys.getpid(),
239        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
240        quote(`:lisp-implementation`), list(quote(`:type`), "R",
241                                            quote(`:name`), "R",
242                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
243 }
244
245 `swank:swank-require` <- function (io, sldbState, contribs) {
246   list()
247 }
248
249 `swank:create-repl` <- function(io, sldbState, env, ...) {
250   list("R", "R")
251 }
252
253 `swank:listener-eval` <- function(io, sldbState, string) {
254   val <- eval(parse(text=string), envir = globalenv())
255   string <- printToString(val)
256   list(quote(`:values`), paste(string, collapse="\n"))
257 }
258
259 `swank:autodoc` <- function(io, sldbState, rawForm, ...) {
260   "No Arglist Information"
261 }
262
263 `swank:operator-arglist` <- function(io, sldbState, op, package) {
264   list()
265 }
266
267 `swank:throw-to-toplevel` <- function(io, sldbState) {
268   condition <- simpleCondition("Throw to toplevel")
269   class(condition) <- c("swankTopLevel", class(condition))
270   signalCondition(condition)
271 }
272
273 `swank:debugger-info-for-emacs` <- function(io, sldbState, from, to) {
274   debuggerInfoForEmacs(sldbState, from=from, to=to)
275 }
276
277 `swank:invoke-nth-restart-for-emacs` <- function(io, sldbState, level, n) {
278   if(sldbState$level == level) {
279     invokeRestart(sldbState$restarts[[n+1]])
280   }
281 }
282
283 `swank:buffer-first-change` <- function(io, sldbState, filename) {
284   FALSE
285 }
286
287 `swank:frame-locals-and-catch-tags` <- function(io, sldbState, index) {
288   str(sldbState$frames)
289   frame <- sldbState$frames[[1+index]]
290   objs <- ls(envir=frame)
291   list(lapply(objs, function(name) { list(quote(`:name`), name,
292                                           quote(`:id`), 0,
293                                           quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
294        list())
295 }
296
297 `swank:simple-completions` <- function(io, sldbState, prefix, package) {
298   ## fails multiply if prefix contains regexp metacharacters
299   matches <- apropos(sprintf("^%s", prefix), ignore.case=FALSE)
300   nmatches <- length(matches)
301   if(nmatches == 0) {
302     list(list(), "")
303   } else {
304     longest <- matches[order(nchar(matches))][1]
305     while(length(grep(sprintf("^%s", longest), matches)) < nmatches) {
306       longest <- substr(longest, 1, nchar(longest)-1)
307     }
308     list(as.list(matches), longest)
309   }
310 }
311
312 `swank:compile-string-for-emacs` <- function(io, sldbState, string, buffer, position, filename, policy) {
313   # FIXME: I think in parse() here we can use srcref to associate
314   # buffer/filename/position to the objects.  Or something.
315   withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
316                abort="abort compilation")
317   list(quote(`:compilation-result`), list(), TRUE, times[3])
318 }