8
f <- function(x) enquo(x)

e <- f()
#<quosure: empty>
#~

None of these work:

> is_empty(e)
[1] FALSE
> is_missing(e)
[1] FALSE
> is_false(e)
[1] FALSE
> is_quosure(e)
[1] TRUE
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187

2 Answers2

11

You can use quo_is_missing(x), which is an alias for is_missing(quo_get_expr(x)).

Lionel Henry
  • 6,652
  • 27
  • 33
  • 3
    I wasted a fair bit of time on this until I noticed/realized that `quo_is_missing(x)` needed to be run *after* `enquo(x)`. After that, it worked well! – D. Woods Apr 15 '18 at 22:35
3

Examining the print method for class quosure suggests it gets the "empty" attribute like so:

rlang:::env_type(get_env(e))
# [1] "empty"

Unfortunately, env_type is not exported, and neither are the functions env_type calls (ultimately heading to the C function rlang_is_reference)

You can get it more directly (TRUE/FALSE) as:

rlang:::is_reference(get_env(e), empty_env())
# [1] TRUE

Print method for quosure:

rlang:::print.quosure
# function (x, ...) 
# {
#     cat(paste0("<quosure: ", env_type(get_env(x)), ">\n"))
#     print(set_attrs(x, NULL))
#     invisible(x)
# }

I'm not familiar enough with rlang to state with certainty, but this appears to be a way to get what you want using exported functions:

identical(get_env(e), empty_env())
# [1] TRUE

Though I must be missing something, since rlang:::is_reference is not using identical.

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
  • Or another option may be `any(grepl("empty", capture.output(e)))` – akrun May 25 '17 at 17:17
  • 1
    @akrun I guess that's the other way to do it with exported objects. But seems extremely hack-y. I'd rather see an exported method -- perhaps [file an issue](https://github.com/tidyverse/rlang/issues)? And probably safer would be to `capture.output` of `get_env(e)` and look for `R_EmptyEnv` – MichaelChirico May 25 '17 at 17:18
  • The print method only indicates that the quosure is scoped in the empty environment. – Lionel Henry May 25 '17 at 21:21
  • @lionel I understood OP's question to be: "how does R know `e` is empty when these approaches I took couldn't elicit that?" Thanks for the input! – MichaelChirico May 25 '17 at 21:54
  • @MichaelChirico R doesn't know `e` is empty. To R, `e` is just another user-generated data structure that happens to contain some language-related objects. R is not rlang, rlang is not R. – Hong Ooi May 26 '17 at 00:15