r-lib / downlit

Syntax Highlighting and Automatic Linking
https://downlit.r-lib.org
Other
90 stars 22 forks source link

Default environment in evaluate_and_highlight() breaks registration of S3 methods #101

Closed krlmlr closed 3 years ago

krlmlr commented 3 years ago

Should the default be to evaluate in the global environment and to restore its contents after evaluation?

Downstream: https://github.com/r-lib/pillar/issues/221

Rendered example: https://pillar.r-lib.org/reference/format_type_sum.html

library(pkgdown)
library(pillar)

accel <- structure(9.81, class = "accel")

# Broken output: method is not avaliable

out <- downlit::evaluate_and_highlight('
  type_sum.accel <- function(x) {
    I("kg m/s^2")
  }
  format(pillar(accel))[[1]]
')
tail(strsplit(out, "\n")[[1]], 1)
#> [1] "<span class='r-out co'><span class='r-pr'>#&gt;</span> [1] \"&lt;accel&gt;\"</span>"

# Output is fixed if method is made available via .GlobalEnv

type_sum.accel <- function(x) {
  I("kg m/s^2")
}

out <- downlit::evaluate_and_highlight("
  format(pillar(accel))[[1]]
")
tail(strsplit(out, "\n")[[1]], 1)
#> [1] "<span class='r-out co'><span class='r-pr'>#&gt;</span> [1] \"kg m/s^2\"</span>"

Created on 2021-05-24 by the reprex package (v2.0.0)

krlmlr commented 3 years ago

Can we register in the top-level environment and set the eval env to the top-level env, will it be picked up from there?

hadley commented 3 years ago

Need to check where UseMethod() looks — is it always global env or is it top level env?

hadley commented 3 years ago

I think it's probably ok for this to match the behaviour in vignettes; i.e. if you're defining an S3 class for an example, you need to manually register the method.