Debian Codegraph @

R/execution.r

raw symbols SCIP
1 #' @include options.r class_unions.r
2 NULL
3
4 # Create an empty named list
5 #' @importFrom stats setNames
6 namedlist <- function() setNames(list(), character(0))
7 # Converts something to a string no matter what
8 #' @importFrom utils str
9 resilient_to_str <- function(v) tryCatch(toString(v), error = function(e) capture.output(str(v)))
10
11 plot_builds_upon <- function(prev, current) {
12 if (is.null(prev)) {
13 return(TRUE)
14 }
15
16 lprev <- length(prev[[1]])
17 lcurrent <- length(current[[1]])
18
19 lcurrent >= lprev && identical(current[[1]][1:lprev], prev[[1]][1:lprev])
20 }
21
22 ask <- function(prompt = '') {
23 answer <- NA
24 while (is.na(answer)) {
25 answer <- switch(readline(prompt),
26 y = , Y = TRUE,
27 n = , N = FALSE,
28 c = NULL,
29 NA)
30 }
31 answer
32 }
33
34 format_stack <- function(calls) {
35 line_refs <- rep('', length(calls))
36
37 tb <- lapply(seq_along(calls), function(cl) {
38 call <- calls[[cl]]
39
40 # first_line, first_byte, last_line, last_byte, first_column, last_column, first_parsed, last_parsed
41 ref <- attr(call, 'srcref')
42
43 filename <- attr(ref, 'srcfile')$filename
44
45 if (!is.null(ref)) {
46 f <- ref[[1]]
47 l <- ref[[3]]
48 lines <- if (f == l) f else paste0(f, '-', l)
49 line_refs[[cl]] <<- paste0(' # at line ', lines, ' of file ', filename)
50 }
51
52 white <- paste(rep(' ', nchar(format(cl))), collapse = '')
53
54 f.call <- format(call)
55 line.prefix <- c(cl, rep(white, length(f.call) - 1))
56 paste(paste0(line.prefix, '. ', f.call), collapse = '\n')
57 })
58
59 paste0(tb, line_refs)
60 }
61
62
63 #' @importFrom utils capture.output
64 Executor <- setRefClass(
65 Class = 'Executor',
66 fields = list(
67 send_response = 'function',
68 handle_stdin = 'function',
69 abort_queued_messages = 'function',
70 execution_count = 'integer',
71 payload = 'list',
72 err = 'list',
73 interrupted = 'logical',
74 last_recorded_plot = 'recordedplotOrNULL',
75 current_request = 'listOrNULL',
76 nframe = 'integer'),
77 methods = list(
78
79 is_silent = function() {
80 current_request$content$silent
81 },
82
83 should_store_history = function() {
84 sh <- current_request$content$store_history
85 !is.null(sh) && sh
86 },
87
88 send_error_msg = function(msg) {
89 if (is_silent()) return()
90 send_response('stream', current_request, 'iopub',
91 list(name = 'stderr', text = msg))
92
93 },
94
95 display_data = function(data, metadata = NULL) {
96 if (is.null(metadata)) {
97 metadata <- namedlist()
98 }
99 send_response('display_data', current_request, 'iopub', list(
100 data = data,
101 metadata = metadata))
102
103 invisible(TRUE)
104 },
105
106 clear_output = function(wait = TRUE) {
107 send_response('clear_output', current_request, 'iopub', list(wait = wait))
108 },
109
110 page = function(mimebundle) {
111 payload <<- c(payload, list(c(source = 'page', mimebundle)))
112 },
113
114 # .Last doesn’t seem to work, so replicating behavior
115 quit = function(save = 'default', status = 0, runLast = TRUE) {
116 save <- switch(save,
117 default = , yes = TRUE,
118 no = FALSE,
119 ask = ask('Save workspace image? [y/n/c]: '),
120 stop('unknown `save` value'))
121 if (is.null(save)) return() # cancel
122 if (runLast) {
123 if (!is.null(.GlobalEnv$.Last)) .GlobalEnv$.Last()
124 if (!is.null(.GlobalEnv$.Last.sys)) .GlobalEnv$.Last.sys()
125 }
126 if (save) NULL # TODO: actually save history
127 payload <<- c(.self$payload, list(list(source = 'ask_exit', keepkernel = FALSE)))
128 },
129
130 # noninteractive
131 readline = function(prompt = '') {
132 log_debug('entering custom readline')
133 send_response('input_request', current_request, 'stdin',
134 list(prompt = prompt, password = FALSE))
135 # wait for 'input_reply' response message
136 input <- handle_stdin()
137 },
138
139 # noninteractive 5.0 protocol:
140 get_pass = function(prompt = '') {
141 log_debug('entering custom get_pass')
142 send_response('input_request', current_request, 'stdin',
143 list(prompt = prompt, password = TRUE))
144 # wait for 'input_reply' response message
145 log_debug('exiting custom get_pass')
146 input <- handle_stdin()
147 },
148
149 handle_error = function(e) {
150 estr <- resilient_to_str(e)
151 tryCatch({
152 log_debug('Error output: %s', estr)
153 calls <- head(sys.calls()[-seq_len(nframe + 1L)], -3)
154
155 calls <- skip_repeated(calls)
156
157 msg <- paste0(estr, 'Traceback:\n')
158 stack_info <- format_stack(calls)
159
160 err <<- list(ename = 'ERROR', evalue = estr, traceback = as.list(c(msg, stack_info)))
161 if (!is_silent()) {
162 send_response('error', current_request, 'iopub', err)
163 }
164 }, error = function(e2) {
165 log_error('Error in handle_error! %s', resilient_to_str(e2))
166 log_error('Caused when handling %s', estr)
167 })
168 },
169
170 send_plot = function(plotobj) {
171 log_debug('Sending plot...')
172 formats <- namedlist()
173 metadata <- namedlist()
174 for (mime in getOption('jupyter.plot_mimetypes')) {
175 w <- attr(plotobj, '.irkernel_width')
176 h <- attr(plotobj, '.irkernel_height')
177 ppi <- attr(plotobj, '.irkernel_ppi')
178 tryCatch({
179 formats[[mime]] <- mime2repr[[mime]](plotobj, w, h)
180 }, error = handle_error)
181 if (!identical(mime, 'text/plain')) {
182 metadata[[mime]] <- list(
183 width = w * ppi,
184 height = h * ppi
185 )
186 }
187 # Isolating SVGs (putting them in an iframe) avoids strange
188 # interactions with CSS on the page.
189 if (identical(mime, 'image/svg+xml')) {
190 metadata[[mime]]$isolated <- TRUE
191 }
192 }
193 publish_mimebundle(formats, metadata)
194 },
195
196 handle_display_error = function(e) {
197 # This is used with withCallingHandler and only has two additional
198 # calls at the end instead of the 3 for tryCatch... (-2 at the end)
199 # we also remove the tryCatch and mime2repr stuff at the head of the callstack (+7)
200 calls <- head(sys.calls()[-seq_len(nframe + 7L)], -2)
201 stack_info <- format_stack(calls)
202 msg <- sprintf('ERROR while rich displaying an object: %s\nTraceback:\n%s\n',
203 toString(e),
204 paste(stack_info, collapse = '\n'))
205 log_debug(msg)
206 send_error_msg(msg)
207 },
208
209 handle_value = function(obj, visible) {
210 log_debug('Value output...')
211 set_last_value(obj)
212 if (!visible) return()
213
214 mimebundle <- prepare_mimebundle_kernel(obj, .self$handle_display_error)
215 if (is.null(mimebundle$data)) return()
216
217 if (length(intersect(class(obj), getOption('jupyter.pager_classes'))) > 0) {
218 log_debug('Showing pager: %s', paste(capture.output(str(mimebundle$data)), collapse = '\n'))
219 page(mimebundle)
220 } else {
221 log_debug('Sending display_data: %s', paste(capture.output(str(mimebundle$data)), collapse = '\n'))
222 send_response('display_data', current_request, 'iopub', mimebundle)
223 }
224 },
225
226 stream = function(output, streamname) {
227 log_debug('Stream output: %s', output)
228 send_response('stream', current_request, 'iopub', list(
229 name = streamname,
230 text = paste(output, collapse = '\n')))
231 },
232
233 handle_graphics = function(plotobj) {
234 log_debug('Graphics output...')
235 if (!plot_builds_upon(last_recorded_plot, plotobj)) {
236 send_plot(last_recorded_plot)
237 }
238 # need to be set here to capture the size and have it available when the plot is sent
239 attr(plotobj, '.irkernel_width') <- getOption('repr.plot.width', repr_option_defaults$repr.plot.width)
240 attr(plotobj, '.irkernel_height') <- getOption('repr.plot.height', repr_option_defaults$repr.plot.height)
241 attr(plotobj, '.irkernel_ppi') <-
242 getOption('repr.plot.res', repr_option_defaults$repr.plot.res) /
243 getOption('jupyter.plot_scale', jupyter_option_defaults$jupyter.plot_scale)
244 last_recorded_plot <<- plotobj
245 },
246
247 handle_message = function(o) {
248 log_debug('Message output: %s', o)
249 stream(paste(c(conditionMessage(o), '\n'), collapse = ''), 'stderr')
250 },
251
252 handle_warning = function(o) {
253 call <- conditionCall(o)
254 call <- if (is.null(call)) '' else sprintf(' in %s', deparse(call)[[1]])
255 msg <- sprintf('Warning message%s:\n%s\n', call, dQuote(conditionMessage(o)))
256 log_debug('Warning output: %s', msg)
257 stream(msg, 'stderr')
258 },
259
260 execute = function(request) {
261 send_response('execute_input', request, 'iopub', list(
262 code = request$content$code,
263 execution_count = execution_count))
264
265 # Make the current request available to other functions
266 current_request <<- request
267 # reset ...
268 payload <<- list()
269 err <<- list()
270
271 # shade base::readline
272 replace_in_package('base', 'readline', .self$readline)
273
274 # shade getPass::getPass
275 add_to_user_searchpath('getPass', .self$get_pass, 'getPass')
276
277 # shade base::quit
278 replace_in_package('base', 'quit', .self$quit)
279 replace_in_package('base', 'q', .self$quit)
280
281 # find out stack depth in notebook cell
282 # TODO: maybe replace with a single call on first execute and rest reuse the value?
283 tryCatch(evaluate(
284 'stop()',
285 stop_on_error = 1L,
286 output_handler = new_output_handler(error = function(e) nframe <<- sys.nframe())))
287
288 oh <- if (is_silent()) {
289 new_output_handler(
290 text = identity,
291 graphics = identity,
292 message = identity,
293 warning = identity,
294 error = identity,
295 value = identity)
296 } else {
297 new_output_handler(
298 text = function(o) stream(o, 'stdout'),
299 graphics = .self$handle_graphics,
300 message = .self$handle_message,
301 warning = .self$handle_warning,
302 error = .self$handle_error,
303 value = .self$handle_value)
304 }
305
306 interrupted <<- FALSE
307 last_recorded_plot <<- NULL
308 log_debug('Executing code: %s', request$content$code)
309
310 warn_unicode_on_windows(request$content$code, .self$send_error_msg)
311
312 tryCatch(
313 evaluate(
314 request$content$code,
315 envir = .GlobalEnv,
316 output_handler = oh,
317 stop_on_error = 1L),
318 interrupt = function(cond) {
319 log_debug('Interrupt during execution')
320 interrupted <<- TRUE
321 },
322 error = .self$handle_error) # evaluate does not catch errors in parsing
323
324 if (!is_silent() && !is.null(last_recorded_plot)) {
325 send_plot(last_recorded_plot)
326 }
327
328 status <-
329 if (interrupted) 'abort'
330 else if (!is.null(err$ename)) 'error'
331 else 'ok'
332
333 log_debug('Code execution result: %s', status)
334
335 reply_content <- c(
336 list(
337 status = status,
338 execution_count = execution_count),
339 switch(status,
340 ok = list(payload = payload, user_expressions = namedlist()),
341 error = err))
342
343 send_response('execute_reply', request, 'shell', reply_content)
344
345 if (interrupted || !is.null(err$ename)) {
346 # errors or interrupts should interrupt all currently queued messages,
347 # not only the currently running one...
348 abort_queued_messages()
349 }
350
351 if (!is_silent() && should_store_history()) {
352 execution_count <<- execution_count + 1L
353 }
354 },
355
356 initialize = function(...) {
357 execution_count <<- 1L
358 err <<- list()
359 options(
360 pager = function(files, header, title, delete.file) {
361 text <- title
362 for (path in files) {
363 text <- c(text, header, readLines(path))
364 }
365 if (delete.file) file.remove(files)
366 data <- list('text/plain' = paste(text, collapse = '\n'))
367 page(list(data=data, metadata=namedlist()))
368 },
369 jupyter.base_display_func = .self$display_data,
370 jupyter.clear_output_func = .self$clear_output
371 )
372 # Create the shadow env here and detach it finalize
373 # so it's available for the whole lifetime of the kernel.
374 .BaseNamespaceEnv$attach(NULL, name = 'jupyter:irkernel')
375
376 # Add stuff to the user environment and configure a few options
377 # in the current session
378 init_shadowenv()
379 init_session()
380 init_null_device()
381
382 callSuper(...)
383 },
384 finalize = function() {
385 detach('jupyter:irkernel')
386 })
387 )