Skip to content

Improve $-completion of method-chaining syntax and more - #1469

Closed
sorhawell wants to merge 3 commits into
REditorSupport:mainfrom
sorhawell:improve_complete
Closed

sorhawell wants to merge 3 commits into
REditorSupport:mainfrom
sorhawell:improve_complete

Conversation

@sorhawell

@sorhawell sorhawell commented Jan 2, 2024 •

Copy link
Copy Markdown

What problem did you solve?

with setting.json

    "r.lsp.debug": true,
    "r.session.useWebServer": true,

vscode-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?

check out branch with vscode and emulate the extension
"r.session.useWebServer": true

example 1

#$-complete after arbitrary parenthesis
(
    iris |> # |> is supported if the R interpreter supports it
    (\(iris) {
        iris$is_alien = FALSE
        head(iris, 3)
    })()
)$
image

example 2

#$ complete chained R6 methods 
FruitBasket <- R6::R6Class(
  "FruitBasket",
  private = list(content = character()),
  public = list(
    initialize = \() {},
    mutate_content = \(fruit) {
        private$content = c(private$content, fruit)
        self
    },
    add_banana = \() self$clone()$mutate_content("banana"),
    add_apple = \() self$clone()$mutate_content("apple"),
    to_count_list = \() as.list(table(private$content))
  )
)

#$-complete any multiline chain. If it is valid R syntax is works
{
  print("this print statement is not evaluated, because not a child of `$` call in AST");
  FruitBasket$new()$
    add_apple()$
    add_banana(
    
    )$
    add_apple()$
    to_count_list()$
}
image

example 3

support r-polars completion ;) (disclaimer I have co-authored the polars bindings for R)

# load polars and disable completion () and <- in suggestions
library(polars) #polars as of https://github.com/pola-rs/r-polars/pull/597
cs = polars:::completion_symbols
cs$method = ""
cs$setter = ""


pl$
  DataFrame(
    a = 1:5,
    b = letters[1:5]
  )$
  lazy()$
  select(
    pl$all()$head(5)
  )
image image

example 4 completion for the arrow package (R6)

library(arrow)


arrow_table(iris[,1:2])$
  Slice(2,10)$
  print()$
  Take(5)$
  
image

@sorhawell sorhawell changed the title Improve complete Improve $-completion of method-chaining syntax and more Jan 2, 2024
@sorhawell

Copy link
Copy Markdown
Author

4b3044d commit adds finish_expression which is related to the rstudio approach of filling in missing parenthesis. I forgot to add that to PR sry.

@renkun-ken

renkun-ken commented Jan 6, 2024 •

Copy link
Copy Markdown
Member

Thanks for working on this! It is definitely a super useful improvement of the current completion.

I notice that the code in scope has to be evaluated (silently) to provide the completion, which makes the completion result accurate. I wonder if it is safe to do so in many use cases?

For example:

df <- data.frame(id = 1:10)
obj <- local({
  file.remove("/path/to/something/important")
  df$x <- 1
  df
}$)
image

If a user writes some critical code that changes some important state, it seems only desirable that the code should only be evaluated when manually sent to the terminal by user. However, maybe a typo $ could trigger a completion that evaluates the code in the scope, i.e. the code is silently evaluated in the background.

A less damaging example is that the user code to be evaluated might be too time-consuming before the user realizes it. If the code contains C/C++ impl without caring user interruption, then the session might be blocked.

Evaluting any user code other than simple name1$name2$name3 cases seems to suffer such problem. What do you think?

@sorhawell

sorhawell commented Jan 7, 2024 •

Copy link
Copy Markdown
Author

@renkun-ken

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 .$, .[, .[[ or .dollarNames. That would also be an issue in the current vscode-R. I think it should be possible to block most of that.

# 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 .[ .[[ and .$, but no function calls ( in the AST which are not on the positive-list. This is pretty much what rstudio is running with today I think. BTW .[ in many ways behaves just as function call ( and can be used to circumvent rstudio completion limits. But by convention .[ is expected to only index so that is ok.

example of what could work:

image image

example of what would not work (unless c and list is added to the positive list)
image

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 collect(). A good R package running low level code, should check for R user interrupts every 100-1000ms and abort if requested.

There are exceptions e.g. data.table set-functions, (file)-connections ...

I think some users would happily opt-in for "full_evaluation".

@renkun-ken

Copy link
Copy Markdown
Member

Thanks for the detailed explanation. I think the evaluation_level should be good enough to handle such problem.

@sorhawell

Copy link
Copy Markdown
Author

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.

@randy3k
randy3k changed the base branch from master to main September 26, 2026 16:57
@eitsupi

eitsupi commented Sep 28, 2026

Copy link
Copy Markdown
Member

This is outdated, so closing.

@eitsupi eitsupi closed this Sep 28, 2026
eitsupi added a commit that referenced this pull request Nov 15, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants