Skip to contents

Convert STR_CONST text() values into R strings. This is useful to account for arbitrary character literals valid since R 4.0, e.g. R"------[hello]------", which is parsed in R as "hello". It is quite cumbersome to write XPaths allowing for strings like this, so whenever your linter logic requires testing a STR_CONST node's value, use this function. NB: this is also properly vectorized on s, and accepts a variety of inputs. Empty inputs will become NA outputs, which helps ensure that length(get_r_string(s)) == length(s).

Usage

get_r_string(s, xpath = NULL)

Arguments

s

An input string or strings. If s is an xml_node or xml_nodeset and xpath is NULL, extract its string value with xml2::xml_text(). If s is an xml_node or xml_nodeset and xpath is specified, it is extracted with xml2::xml_find_chr().

xpath

An XPath, passed on to xml2::xml_find_chr() after wrapping with string().

Examples

tmp <- withr::local_tempfile(lines = "c('a', 'b')")
expr_as_xml <- get_source_expressions(tmp)$expressions[[1L]]$xml_parsed_content
#> Warning: cannot open file '/tmp/RtmpaobaTl/file18d25c41d6cf': No such file or directory
#> Error in file(con, "r"): cannot open the connection
writeLines(as.character(expr_as_xml))
#> Error in eval(expr, envir, enclos): object 'expr_as_xml' not found
get_r_string(expr_as_xml, "expr[2]") # "a"
#> Error in eval(expr, envir, enclos): object 'expr_as_xml' not found
get_r_string(expr_as_xml, "expr[3]") # "b"
#> Error in eval(expr, envir, enclos): object 'expr_as_xml' not found

# more importantly, extract strings under R>=4 raw strings
tmp4.0 <- withr::local_tempfile(lines = "c(R'(a\\b)', R'--[a\\\"\'\"\\b]--')")
expr_as_xml4.0 <- get_source_expressions(tmp4.0)$expressions[[1L]]$xml_parsed_content
#> Warning: cannot open file '/tmp/RtmpaobaTl/file18d2703e565e': No such file or directory
#> Error in file(con, "r"): cannot open the connection
writeLines(as.character(expr_as_xml4.0))
#> Error in eval(expr, envir, enclos): object 'expr_as_xml4.0' not found
get_r_string(expr_as_xml4.0, "expr[2]") # "a\b"
#> Error in eval(expr, envir, enclos): object 'expr_as_xml4.0' not found
get_r_string(expr_as_xml4.0, "expr[3]") # "a\\"'\"\b"
#> Error in eval(expr, envir, enclos): object 'expr_as_xml4.0' not found