File: rd-example.R

package info (click to toggle)
r-cran-pkgdown 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,740 kB
  • sloc: javascript: 460; makefile: 14; sh: 13
file content (221 lines) | stat: -rw-r--r-- 5,694 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
rd2ex <- function(x, ...) {
  x <- rd_text(paste0("\\examples{", x, "}"), fragment = FALSE)[[1]]
  x <- process_conditional_examples(x)
  x <- flatten_ex(x, ...)

  if (grepl("\n", x)) {
    strsplit(x, "\n")[[1]]
  } else {
    x
  }
}

run_examples <- function(
  x,
  topic = "unknown",
  env = globalenv(),
  run_dont_run = FALSE
) {
  if (!inherits(x, "tag")) {
    x <- rd_text(x)
  }

  # Trim newline that usually occurs after \examples{
  if (is_newline(x[[1]], trim = TRUE)) {
    x <- x[-1]
  }

  x <- process_conditional_examples(x)
  code <- flatten_ex(x, run_dont_run = run_dont_run)

  if (!can_parse(code)) {
    cli::cli_warn("Failed to parse example for topic {.val {topic}}")
    return("")
  }

  if (!is.null(env)) {
    highlight_examples(code, topic, env = env)
  } else {
    highlight_text(code)
  }
}

process_conditional_examples <- function(rd) {
  if (is.list(rd)) {
    which_exif <- which(purrr::map_lgl(rd, function(x) {
      "tag_dontshow" %in%
        class(x) &&
        is.character(x[[1]]) &&
        grepl("# examplesIf$", x[[1]])
    }))
    if (length(which_exif) == 0) {
      return(rd)
    }
    if (length(which_exif) %% 2 != 0) {
      cli::cli_abort("@examplesIf error, not closed?", call = caller_env())
    }
    remove <- integer()
    modes <- c("begin", "end")
    for (idx in which_exif) {
      if (rd[[idx]] != "}) # examplesIf") {
        # Start of @examplesIf
        if (modes[1] == "end") {
          cli::cli_abort("@examplesIf error, not closed?", call = caller_env())
        }
        cond_expr <- parse(text = paste0(rd[[idx]], "\n})"))[[1]][[2]]
        cond <- eval(cond_expr)
        if (isTRUE(cond)) {
          remove <- c(remove, idx, idx + 1L)
        } else {
          cond_expr_str <- deparse1(cond_expr)
          is_false <- cond_expr_str == "FALSE"
          if (!is_false) {
            new_cond <- paste0("if (FALSE) { # ", cond_expr_str)
            cli::cli_warn(
              "@examplesIf condition {.val {cond_expr_str}} is {.val FALSE}"
            )
          } else {
            new_cond <- "if (FALSE) {"
          }
          rd[[idx]] <- structure(list(new_cond), class = c("RCODE", "tag"))
        }
      } else {
        # End of @examplesIf
        if (modes[1] == "begin") {
          cli::cli_abort(
            "@examplesIf error, closed twice?",
            call = caller_env()
          )
        }
        if (isTRUE(cond)) {
          remove <- c(remove, idx, idx + 1L)
        } else {
          rd[[idx]] <- structure(list("}"), class = c("RCODE", "tag"))
        }
      }
      modes <- rev(modes)
    }
    if (length(remove)) {
      rd <- rd[-remove]
    }
    rd
  } else {
    rd
  }
}


# as_example --------------------------------------------------------------

as_example <- function(x, run_dont_run = FALSE) {
  UseMethod("as_example")
}

#' @export
as_example.RCODE <- function(x, run_dont_run = FALSE) as.character(x)
#' @export
as_example.VERB <- as_example.RCODE
#' @export
as_example.TEXT <- as_example.RCODE
#' @export
as_example.COMMENT <- function(x, run_dont_run = FALSE) {
  if (grepl("^%[^ ]*%", x)) {
    meant <- gsub("%", "\\\\%", x)
    xun <- unclass(x)
    cli::cli_warn(c(
      "In the examples, {.val {xun}} is an Rd comment",
      "x" = "did you mean {.val {meant}}?"
    ))
  }
  ""
}
#' @export
as_example.tag_dontrun <- function(x, run_dont_run = FALSE) {
  if (run_dont_run) {
    block_tag_to_comment("\\dontrun", x, run_dont_run = run_dont_run)
  } else {
    ex <- flatten_ex(x, run_dont_run = run_dont_run)
    if (is_newline(x[[1]], trim = TRUE)) {
      paste0("if (FALSE) { # \\dontrun{", ex, "} # }")
    } else {
      paste0("if (FALSE) ", ex, " # \\dontrun{}")
    }
  }
}

#' @export
as_example.tag_donttest <- function(x, run_dont_run = FALSE) {
  block_tag_to_comment("\\donttest", x, run_dont_run = run_dont_run)
}
#' @export
as_example.tag_dontshow <- function(x, run_dont_run = FALSE) {
  ex <- flatten_ex(x, run_dont_run = run_dont_run)
  paste0("DONTSHOW({", ex, "})")
}
#' @export
as_example.tag_testonly <- function(x, run_dont_run = FALSE) {
  ex <- flatten_ex(x, run_dont_run = run_dont_run)
  paste0("TESTONLY({", ex, "})")
}

block_tag_to_comment <- function(tag, x, run_dont_run = FALSE) {
  ex <- flatten_ex(x, run_dont_run = run_dont_run)

  # Not easy to strip leading whitespace because it's attached to the previous
  # tag. So instead we add a comment to occupy that space
  if (is_newline(x[[1]], trim = TRUE)) {
    ex <- paste0("# ", tag, "{", ex, "# }")
  }
  ex
}

#' @export
as_example.tag <- function(x, run_dont_run = FALSE) {
  untag <- paste(class(x), collapse = "/")
  cli::cli_warn("Unknown tag: {.val {untag}}")
}

#' @export
as_example.tag_dots <- function(x, run_dont_run = FALSE) {
  "..."
}
#' @export
as_example.tag_ldots <- as_example.tag_dots

#' @export
as_example.tag_if <- function(x, run_dont_run = FALSE) {
  if (x[[1]] == "html") {
    flatten_ex(x[[2]], run_dont_run = run_dont_run)
  } else {
    ""
  }
}
#' @export
as_example.tag_ifelse <- function(x, run_dont_run = FALSE) {
  if (x[[1]] == "html") {
    flatten_ex(x[[2]], run_dont_run = run_dont_run)
  } else {
    flatten_ex(x[[3]], run_dont_run = run_dont_run)
  }
}
#' @export
as_example.tag_out <- function(x, run_dont_run = FALSE) {
  flatten_ex(x, run_dont_run = run_dont_run)
}

# Helpers -----------------------------------------------------------------

flatten_ex <- function(x, run_dont_run = FALSE) {
  out <- purrr::map_chr(x, as_example, run_dont_run = run_dont_run)
  paste(out, collapse = "")
}

can_parse <- function(x) {
  tryCatch(
    {
      parse(text = x)
      TRUE
    },
    error = function(e) FALSE
  )
}