ast_rule | R Documentation |
Rules are the core of astgrepr
. Those are used to search for nodes and are
used in node_match*()
and node_find*()
functions. ast_rule()
is a very
flexible function that allows one to build simple rules but also much more
complex and specific ones.
ast_rule(
pattern = NULL,
kind = NULL,
regex = NULL,
inside = NULL,
has = NULL,
precedes = NULL,
follows = NULL,
all = NULL,
any = NULL,
not = NULL,
matches = NULL,
id = NULL
)
pattern |
The pattern to look for. This can be a string or an object of
class |
kind |
The kind of nodes to look for. |
regex |
A regex used to look for nodes. This must follow the syntax of
the Rust |
inside |
In which node should the node we look for be positioned? This
can be another rule made with |
has |
Same input type as |
precedes |
Same input type as |
follows |
Same input type as |
all |
This takes one or a list of rules made with |
any |
This takes one or a list of rules made with |
not |
This takes one or a list of rules made with |
matches |
This takes the |
id |
The name of this rule. This can be reused in another rule with
|
A list (possibly nested) with the class "astgrep_rule"
.
Meta-variables allow us to capture some of the content in a pattern. Usually,
using $
followed by an id in uppercase letters is enough:
src <- "any(duplicated(x))" root <- src |> tree_new() |> tree_root() root |> node_find(ast_rule(pattern = "any(duplicated($A))")) #> <List of 1 rule> #> |--rule_1: 1 node
However, in some cases using $
is a problem. For instance, if we want to
capture a column name coming after $
, then we can't use $
both as code
and as identifier.
src <- "df$a" root <- src |> tree_new() |> tree_root() root |> node_find(ast_rule(pattern = "df$$A")) #> <List of 1 rule> #> |--rule_1: 0 node
In this situation, we can use µ
instead:
root |> node_find(ast_rule(pattern = "df$µA")) #> <List of 1 rule> #> |--rule_1: 1 node
ast_rule(pattern = "print($A)")
ast_rule(
pattern = "print($A)",
inside = ast_rule(
any = ast_rule(
kind = c("for_statement", "while_statement")
)
)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.