Christophe Weblog Wiki Code Publications Music
09ad173d3285d2e139fac4ec220e16f766c67af4
[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     tryCatch(dispatch(io, readPacket(io)),
22              swankTopLevel=function(c) NULL)
23   }
24 }
25
26 dispatch <- function(io, event, sldbState=NULL) {
27   str(event)
28   kind <- event[[1]]
29   if(kind == quote(`:emacs-rex`)) {
30     do.call("emacsRex", c(list(io), list(sldbState), event[-1]))
31   }
32 }
33
34 sendToEmacs <- function(io, obj) {
35   str(obj)
36   payload <- writeSexpToString(obj)
37   writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
38   writeChar(payload, io, eos=NULL)
39   flush(io)
40   cat(sprintf("%06x", nchar(payload)), payload, sep="")
41 }
42
43 emacsRex <- function(io, sldbState, form, pkg, thread, id, level=0) {
44   ok <- FALSE
45   value <- NULL
46   tryCatch({
47     withCallingHandlers({
48       value <- do.call(eval(form[[1]]), c(list(io), list(sldbState), form[-1]))
49       ok <- TRUE
50     }, error=function(c) {
51       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
52       sldbLoop(io, newSldbState, id) })},
53     finally=sendToEmacs(io, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
54 }
55
56 makeSldbState <- function(condition, level, id) {
57   ret <- list(condition=condition, level=level, id=id)
58   class(ret) <- c("sldbState", class(ret))
59   ret
60 }
61
62 sldbLoop <- function(io, sldbState, id) {
63   sendToEmacs(io, c(list(quote(`:debug`), id, sldbState$level), debuggerInfoForEmacs(sldbState)))
64   sendToEmacs(io, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
65   while(TRUE) {
66     dispatch(io, readPacket(io), sldbState)
67   }
68 }
69
70 debuggerInfoForEmacs <- function(sldbState, from=0, to=NULL) {
71   backtraceForEmacs <- function() {
72     calls <- rev(sys.calls())
73     if(is.null(to)) to <- length(calls)
74     from <- from+1
75     calls <- lapply(calls[from:to], { frameNumber <- from-1;
76                              function (x) { ret <- list(frameNumber, paste(format(x), sep="", collapse=" ")); frameNumber <<- 1+frameNumber; ret }})
77   }
78   computeRestartsForEmacs <- function () {
79     lapply(computeRestarts(sldbState$condition),
80            function(x) {
81              ## this is all a little bit internalsy
82              restartName <- x[[1]][[1]]
83              description <- restartDescription(x)
84              list(restartName, if(is.null(description)) restartName else description)
85            })
86   }
87   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
88        computeRestartsForEmacs(),
89        backtraceForEmacs(),
90        list(sldbState$id))
91 }
92
93 readPacket <- function(io) {
94   header <- readChunk(io, 6)
95   len <- strtoi(header, base=16)
96   payload <- readChunk(io, len)
97   readSexpFromString(payload)
98 }
99
100 readChunk <- function(io, len) {
101   buffer <- readChar(io, len)
102   if(nchar(buffer) != len) {
103     stop("short read in readChunk")
104   }
105   buffer
106 }
107
108 readSexpFromString <- function(string) {
109   pos <- 1
110   read <- function() {
111     skipWhitespace()
112     char <- substr(string, pos, pos)
113     switch(char,
114            "("=readList(),
115            "\""=readString(),
116            "'"=readQuote(),
117            {
118              if(pos > nchar(string))
119                stop("EOF during read")
120              obj <- readNumberOrSymbol()
121              if(obj == quote(`.`)) {
122                stop("Consing dot not implemented")
123              }
124              obj
125            })
126   }
127   skipWhitespace <- function() {
128     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
129       pos <<- pos + 1
130     }
131   }
132   readList <- function() {
133     ret <- list()
134     pos <<- pos + 1
135     while(TRUE) {
136       skipWhitespace()
137       char <- substr(string, pos, pos)
138       if(char == ")") {
139         pos <<- pos + 1
140         break
141       } else {
142         obj <- read()
143         if(length(obj) == 1 && obj == quote(`.`)) {
144           stop("Consing dot not implemented")
145         }
146         ret <- c(ret, list(obj))
147       }
148     }
149     ret
150   }
151   readString <- function() {
152     ret <- ""
153     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
154     while(TRUE) {
155       pos <<- pos + 1
156       char <- substr(string, pos, pos)
157       switch(char,
158              "\""={ pos <<- pos + 1; break },
159              "\\"={ pos <<- pos + 1
160                     char2 <- substr(string, pos, pos)
161                     switch(char2,
162                            "\""=addChar(char2),
163                            "\\"=addChar(char2),
164                            stop("Unrecognized escape character")) },
165              addChar(char))
166     }
167     ret
168   }
169   readNumberOrSymbol <- function() {
170     token <- readToken()
171     if(nchar(token)==0) {
172       stop("End of file reading token")
173     } else if(grepl("^[0-9]+$", token)) {
174       strtoi(token)
175     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
176       as.double(token)
177     } else {
178       as.name(token)
179     }
180   }
181   readToken <- function() {
182     token <- ""
183     while(TRUE) {
184       char <- substr(string, pos, pos)
185       if(char == "") {
186         break;
187       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
188         break;
189       } else {
190         token <- paste(token, char, sep="")
191         pos <<- pos + 1
192       }
193     }
194     token
195   }
196   read()
197 }
198
199 writeSexpToString <- function(obj) {
200   writeSexpToStringLoop <- function(obj) {
201     switch(typeof(obj),
202            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
203            "list"={ string <- paste(string, "(", sep="")
204                     max <- length(obj)
205                     if(max > 0) {
206                       for(i in 1:max) {
207                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
208                         if(i != max) {
209                           string <- paste(string, " ", sep="")
210                         }
211                       }
212                     }
213                     string <- paste(string, ")", sep="") },
214            "symbol"={ string <- paste(string, as.character(obj), sep="") },
215            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
216            "double"={ string <- paste(string, as.character(obj), sep="") },
217            "integer"={ string <- paste(string, as.character(obj), sep="") },
218            stop(paste("can't write object ", obj, sep="")))
219     string
220   }
221   string <- ""
222   writeSexpToStringLoop(obj)
223 }
224
225 `swank:connection-info` <- function (io, sldbState) {
226   list(quote(`:pid`), Sys.getpid(),
227        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
228        quote(`:lisp-implementation`), list(quote(`:type`), "R",
229                                            quote(`:name`), "R",
230                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
231 }
232
233 `swank:swank-require` <- function (io, sldbState, contribs) {
234   list()
235 }
236
237 `swank:create-repl` <- function(io, sldbState, env, ...) {
238   list("R", "R")
239 }
240
241 `swank:listener-eval` <- function(io, sldbState, string) {
242   val <- eval(parse(text=string), envir = globalenv())
243   f <- fifo("")
244   sink(f)
245   print(val)
246   sink()
247   lines <- readLines(f)
248   list(quote(`:values`), paste(lines, collapse="\n"))
249 }
250
251 `swank:autodoc` <- function(io, sldbState, rawForm, ...) {
252   "No Arglist Information"
253 }
254
255 `swank:throw-to-toplevel` <- function(io, sldbState) {
256   condition <- simpleCondition("Throw to toplevel")
257   class(condition) <- c("swankTopLevel", class(condition))
258   signalCondition(condition)
259 }
260
261 `swank:debugger-info-for-emacs` <- function(io, sldbState, from, to) {
262   debuggerInfoForEmacs(sldbState, from=from, to=to)
263 }
264
265 `swank:invoke-nth-restart-for-emacs` <- function(io, sldbState, level, n) {
266   if(sldbState$level == level) {
267     invokeRestart(computeRestarts()[[n+1]])
268   }
269 }
270
271 `swank:buffer-first-change` <- function(io, sldbState, filename) {
272   FALSE
273 }