Repository navigation
Conversation
$-completion of method-chaining syntax and more
|
4b3044d commit adds |
|
I principally agree with your concern. I will think in practice, it is likely not as problematic. I suggest to add a user option something like "evaluation_level" to control how eager or cautious completion should be. What do you think of that? In any case, parsing is a fast first step before evaluation and could likely replace regex at any desired "evaluation_level". evaluation_level = "super_secure"If opting for this level. The auto-completion must only extract variables and not run user-defined or package defined generic functions. A malicious developer could sneak in bad side effects disguised as variables via e.g. activeBindings or the generic methods # sneaky evaluation #1
makeActiveBinding("xyz", f = \() {print("hello there");42L}, env = .GlobalEnv)
xyz
#> [1] "hello there"
#> [1] 42
# sneaky evaluation #2
l = list()
class(l) = "TomatoCan"
"$.TomatoCan" = \(self, name) {print("hi again");self[[name]]}
l$foo = "bar"
l$foo
#> [1] "hi again"
#> [1] "bar"Created on 2024-01-07 with reprex v2.0.2 evaluation_level = "only_generic_getters"allow (chained) evaluation generic functions like example of what could work:
example of what would not work (unless evaluation_level = "only_single_line_scope"There could be a choice which will only parse the same code line to make a meaningful evaluation. evaluation_level = "full_evaluation"Parsing like rstudio, but unlimited evaluation. I will argue if using most package APIs, then there are very few mutable methods out there. The polars and arrow packages is built around immutable structures. Most R objects SEXPs have imuttable behavior, where environment is the central exception. Most R package have APIs where the central objects are imuttable. On top of that polars has lazy evaluation (just as dplyrDB) where evaluation does not trigger computation before explicitly calling There are exceptions e.g. I think some users would happily opt-in for "full_evaluation". |
|
Thanks for the detailed explanation. I think the evaluation_level should be good enough to handle such problem. |
|
Update. I have been away for a while. I failed to make good safe list of functions which could be evaluated by IDE auto completion to avoid side effects. In the end, I think this feature is something a user has to willingly opt in to. |
|
This is outdated, so closing. |
…hem (#1949) ## Summary Hover and completion requests send the text in front of the cursor to R, which runs `eval(parse(text = expr))` in the global environment. The text is extracted in TypeScript with `[a-zA-Z0-9._$@ ]`, and R trusts that extraction. Because spaces are included, valid R code other than a name can still reach `eval()`: hovering `counter` in `repeat counter <- counter + 1` sends `repeat counter`, which parses and loops forever, so the R session hangs. Completion after `repeat x$` does the same. This PR adds a shared parser and resolver in sess that answers the same requests without evaluating the request text, so R no longer depends on what the client extracted. The existing socket handlers are not switched over yet, so behavior does not change in this PR; switching them is a follow-up. ## Why requests must not be evaluated - **Hover and completion run without an explicit action.** Evaluating the request runs code just because the cursor moved or `$` was typed, as the `repeat` example shows. This concern was raised for vscode-R before in #1469, whose author concluded that a safe allowlist of functions could not be built. R's own completion (utils rcompgen) does not evaluate a prefix that contains an explicit function call, ark forbids function calls in completion evaluation, and IPython limits completion to side-effect-free evaluation by default. - **The handler should not trust its caller.** Validating the request in R keeps the guarantee independent of how a client extracts the text. This also prepares these handlers to be exposed to other clients later (for example as arf IPC handlers, which run outside arf's evaluation policy and approval), where an evaluating handler would let any client of the same user run arbitrary code. - The current extraction never contains parentheses, so rejecting function calls removes no editor feature. ## What is accepted The request text is parsed in R and accepted only when it is a single expression that is one of: - a name, looked up from the global environment along the search path (as before, so `mtcars` and `pi` still work); - a constant: every length-one constant the parser produces (numbers, integers, complex, logical, `NULL`, typed `NA`, `Inf`, `NaN`, strings). Evaluating a constant runs no code, and the editor already requests hover for them. `T` and `F` are names; - a chain of `$` and `@` accesses on a name, with a name or non-empty string after each operator. Spaces such as `a $ b` and trailing comments are fine. Anything else, including function calls, `[[`, `::`, assignments, unary operators and multiple expressions, is rejected with an error of class `sess_inspection_invalid`. Previously only the first of several expressions was evaluated. Parsing in R, rather than splitting the text in TypeScript, keeps R's syntax (for example `0x10`, `1L`, `1i`) and its validation in one place. ## How accessors are applied The parsed request is not evaluated. The resolver looks up the name and applies each accessor as a fixed call: `base::$` or `base::@` is embedded as a function object, the member is inserted as a symbol (the operators do not evaluate their member argument), and the call is evaluated in a private environment that binds the current object. As a result: - `$` or `@` defined in the global environment do not change the operators; - the environment's parent is the global environment, so S3 `$` methods defined there still dispatch as they do at the console; - `base::@` is used instead of `methods::slot()` so that its own dispatch (S4 slots, S7 properties) is kept; - the current object is never re-evaluated, even if it is a language object. ## Side effects that remain Not evaluating the request does not make inspection free of side effects. Promises, active bindings (including R6 active fields), S3 `$` methods and methods for `str()` or `.DollarNames()` still run code that is already defined in the session, as they do now. They are kept so that hover and completion keep working for lazy data, R6 objects and classes with custom accessors. Each binding on the path is read once. ## Results and errors - Hover returns `list(str = ...)` from the existing `capture_str()`. Completion returns the same items as before; the item builder is extracted from `handle_complete()` into `completion_items()` without changing it. Completion without a `$` or `@` trigger returns `NULL` before reading any binding. - Properties of S7 objects can be hovered through `@`, but are not offered as completion items yet, because `completion_items()` lists `@` members only for S4 objects. This is unchanged and noted with a TODO. - A missing name, `$` on a plain atomic vector, and `@` on a missing S4 slot or on an object without a class return `NULL`. - For S4 objects, `@` accepts what `methods::.hasSlot()` reports plus the pseudo-slots that base `@` reads: `.S3Class`, `.Data` and, on list-based objects, `names`. Like base `@`, `.Data` gives `NULL` for an object without a data part rather than an error. - Invalid requests, other errors and interrupts are signalled rather than turned into `NULL`, so that a caller with an execution deadline can tell them apart. ## Other changes - sess is bumped to 3.4.9000.9000. - R6 and S7 are added to Suggests so that their inspection tests run in CI. The managed sess installation installs only Imports, so users do not get them. - `arity.toml` ignores `description-malformed-version`, which flags tidyverse-style development versions such as 3.4.9000.9000.




What problem did you solve?
with
setting.jsonvscode-R webserver has a simple regex based isolation of code to eval when using the
$/@to trigger in-session completion. This regex will fail for many but the simplest cases.Instead I suggest to rely on the R parser and the AST to decide what the left-hand-side of e.g.
$operator is.This will allow multi-line completion, chained method completion, and potentially anything the R parser accepts.
I'm interested in improving vscode-R similar as this patch for Rstudio completions to support completion for method chaining r-polars (... and also R6 and arrow),
How can I check this pull request?
example 1
example 2
example 3
support r-polars completion ;) (disclaimer I have co-authored the polars bindings for R)
example 4 completion for the arrow package (R6)