| Title: | Tree-Sitter Parsing Tools |
| Version: | 0.1.0 |
| Description: | Common tree-sitter (https://tree-sitter.github.io/tree-sitter/) parsing tools for R. It is meant to be used by other packages that specialize in particular languages and file formats. |
| License: | MIT + file LICENSE |
| Depends: | R (≥ 3.5.0) |
| Imports: | cli, utils |
| Suggests: | magrittr, pillar, testthat (≥ 3.0.0), tsjsonc, tstoml, withr |
| Config/Needs/check: | gaborcsardi/tsjsonc, gaborcsardi/tstoml |
| Config/Needs/coverage: | gaborcsardi/tsjsonc, gaborcsardi/tstoml |
| Additional_repositories: | https://github.com/r-lib/tsitter/releases/download |
| Encoding: | UTF-8 |
| URL: | https://github.com/r-lib/tsitter, https://r-lib.github.io/tsitter/ |
| BugReports: | https://github.com/r-lib/tsitter/issues |
| Config/testthat/edition: | 3 |
| Config/Needs/website: | r-lib/asciicast, tidyverse/tidytemplate, gaborcsardi/tsjsonc, gaborcsardi/tstoml |
| Biarch: | true |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-05-18 16:10:11 UTC; gaborcsardi |
| Author: | Gábor Csárdi [aut, cre],
Posit Software, PBC |
| Maintainer: | Gábor Csárdi <csardi.gabor@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-05-22 09:20:02 UTC |
Convert ts_tree object to a data frame
Description
Create a data frame for the syntax tree of a JSON document, by indexing a ts_tree object with single brackets. This is occasionally useful for exploration and debugging.
Usage
## S3 method for class 'ts_tree'
x[i, j, drop = FALSE]
Arguments
x |
A |
i, j |
Incides, passed to the regular data.frame indexing method, see
|
drop |
Passed to the regular data.frame indexing method, see
|
Details
A tree-sitter tree object has at least four classes:
-
ts_tree_<parser_name>, e.g.ts_tree_tsjsonc, -
ts_tree, -
tbl, from the pillar package, for better printing when converted to a data frame, and -
data.frame, since it is a data frame internally.
The ts_tree class has custom format() and print() methods, that
show (part of) the underlying document, and also the selected elements,
if any.
It is sometimes useful to treat a tree ts_tree object as a data
frame, and drop the ts_tree classes. This can be done by indexing with
single brackets, e.g. tree[]. This returns a data frame with one
row per token, and various columns with information about the tokens.
See details in the 'Value' section or this page.
Value
A data frame with one row per token, and columns:
-
id: integer, the id of the token. The (root) document node has id 1. -
parent: integer, the id of the parent token. The root token has parentNA -
field_name: character, the field name of the token in its parent. -
type: character, the type of the token. -
code: character, the actual code of the token. -
start_byte,end_byte: integer, the byte positions of the token in the input. -
start_row,start_column,end_row,end_column: integer, the position of the token in the input. -
is_missing: logical, whether the token is a missing token added by the parser to recover from errors. -
has_error: logical, whether the token has a parse error. -
children: list of integer vectors, the ids of the children tokens. -
dom_type: character, the type of the node in the DOM tree. Seets_tree_dom(). Nodes that are not part of the DOM tree haveNA_character_here. -
dom_children: list of integer vectors, the ids of the children in the DOM tree. Seets_tree_dom(). -
dom_parent: integer, the parent of the node in the DOM tree. Seets_tree_dom(). Nodes that are not part of the DOM tree and the document node have haveNA_integer_here.
Other, undocumented columns may also be present, these are considered internal and may change without notice.
See Also
Other ts_tree exploration:
ts_tree_ast(),
ts_tree_dom(),
ts_tree_query(),
ts_tree_sexpr()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
tree
tree[]
Edit parts of a tree-sitter tree
Description
The [[<- operator works similarly to the combination of
ts_tree_select() and
ts_tree_update(), (and also to the
replacement function ts_tree_select<-()),
but it might be more readable.
Usage
## S3 replacement method for class 'ts_tree'
x[[i]] <- value
Arguments
x |
A |
i |
A list with selection expressions, see
|
value |
An R expression to serialize or
|
Details
The following two expressions are equivalent:
tree <- ts_tree_update(ts_tree_select(tree, <selectors>), value)
and
tree[[list(<selectors>)]] <- value
Value
The modified ts_tree object.
See Also
Other ts_tree generics:
[[.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')
tree
tree[[list("a")]] <- 42
tree[[list("b", -1)]] <- ts_tree_deleted()
tree
Unserialize parts of a tree-sitter tree
Description
The [[ operator works similarly to the combination of
ts_tree_select() and
ts_tree_unserialize(), but it
might be more readable.
Usage
## S3 method for class 'ts_tree'
x[[i, ...]]
Arguments
x |
A |
i |
Selection expressions in a list, see details in
|
... |
Additional arguments, passed to
|
Details
The following two expressions are equivalent:
ts_tree_unserialize(ts_tree_select(tree, <selectors>))
and
tree[[list(<selectors>)]]
The [[<- replacement operator
The [[<- operator works similarly to the combination of
ts_tree_select() and
ts_tree_update(), (and also to the
replacement function ts_tree_select<-()),
but it might be more readable.
Value
List of R objects, with one entry for each selected element.
See Also
Other ts_tree generics:
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Other serialization functions:
ts_tree_unserialize()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')
tree
tree[[list("a")]]
# Last two elements of "b"
tree[[list("b", -(1:2))]]
About tsitter
Description
tsitter is a common interface to tree-sitter parsers, implemented in other R packages. It has a common API to
query,
edit,
format, and
unserialize
tree-sitter parse trees.
Details
In this document I show examples with the tsjsonc package.
Create a tree-sitter tree
Create a ts_tree (ts_tree_jsonc) object from a string:
txt <- r"(
// this is a comment
{
"a": {
"a1": [1, 2, 3],
// comment
"a2": "string"
},
"b": [
{
"b11": true,
"b12": false
},
{
"b21": false,
"b22": false
}
]
}
)"
json <- tsjsonc::ts_parse_jsonc(txt)
#>
Pretty print a ts_tree object:
json
#> # jsonc (19 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a1": [1, 2, 3], #> 6 | // comment #> 7 | "a2": "string" #> 8 | }, #> 9 | "b": [ #> 10 | { #> ℹ 9 more lines #> ℹ Use `print(n = ...)` to see more lines
Select nodes of a tree
Selecting nodes is the basis of editing and querying tree-sitter trees.
Select element by objects key:
ts_tree_select(json, "a")
#> # jsonc (19 lines, 1 selected element) #> 1 | #> 2 | // this is a comment #> 3 | { #> > 4 | "a": { #> > 5 | "a1": [1, 2, 3], #> > 6 | // comment #> > 7 | "a2": "string" #> > 8 | }, #> 9 | "b": [ #> 10 | { #> 11 | "b11": true, #> ...
Select element inside element:
ts_tree_select(json, "a", "a1")
#> # jsonc (19 lines, 1 selected element) #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> > 5 | "a1": [1, 2, 3], #> 6 | // comment #> 7 | "a2": "string" #> 8 | }, #> ...
Select element(s) of an array:
ts_tree_select(json, "a", "a1", 1:2)
#> # jsonc (19 lines, 2 selected elements) #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> > 5 | "a1": [1, 2, 3], #> 6 | // comment #> 7 | "a2": "string" #> 8 | }, #> ...
Select multiple keys from an object:
ts_tree_select(json, "a", c("a1", "a2"))
#> # jsonc (19 lines, 2 selected elements) #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> > 5 | "a1": [1, 2, 3], #> 6 | // comment #> > 7 | "a2": "string" #> 8 | }, #> 9 | "b": [ #> 10 | { #> ...
Select nodes that match a tree-sitter query:
ts_tree_select(json, query = "((pair value: (false) @val))")
#> # jsonc (19 lines, 3 selected elements) #> ... #> 9 | "b": [ #> 10 | { #> 11 | "b11": true, #> > 12 | "b12": false #> 13 | }, #> 14 | { #> > 15 | "b21": false, #> > 16 | "b22": false #> 17 | } #> 18 | ] #> 19 | }
Delete elements
Delete selected elements:
ts_tree_delete(ts_tree_select(json, "a", "a1"))
#> # jsonc (18 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | // comment #> 6 | "a2": "string" #> 7 | }, #> 8 | "b": [ #> 9 | { #> 10 | "b11": true, #> ℹ 8 more lines #> ℹ Use `print(n = ...)` to see more lines
Insert elements
Insert element into an array:
ts_tree_insert(ts_tree_select(json, "a", "a1"), at = 2, "new")
#> # jsonc (24 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a1": [ #> 6 | 1, #> 7 | 2, #> 8 | "new", #> 9 | 3 #> 10 | ], #> ℹ 14 more lines #> ℹ Use `print(n = ...)` to see more lines
Inserting into an array reformats the array.
Insert element into an object, at the specified key:
ts_tree_insert(
ts_tree_select(json, "a"),
key = "a0",
at = 0,
list("new", "element")
)
#> # jsonc (27 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a0": [ #> 6 | "new", #> 7 | "element" #> 8 | ], #> 9 | "a1": [ #> 10 | 1, #> ℹ 17 more lines #> ℹ Use `print(n = ...)` to see more lines
Update elements
Update existing element:
ts_tree_update(ts_tree_select(json, "a", c("a1", "a2")), "new value")
#> # jsonc (19 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a1": "new value", #> 6 | // comment #> 7 | "a2": "new value" #> 8 | }, #> 9 | "b": [ #> 10 | { #> ℹ 9 more lines #> ℹ Use `print(n = ...)` to see more lines
Inserts the element if some parents are missing:
json <- ts_parse_jsonc(text = "{ \"a\": { \"b\": true } }")
json
#> Error in ts_parse_jsonc(text = "{ \"a\": { \"b\": true } }") :
#> could not find function "ts_parse_jsonc"
#> # jsonc (19 lines)
#> 1 |
#> 2 | // this is a comment
#> 3 | {
#> 4 | "a": {
#> 5 | "a1": [1, 2, 3],
#> 6 | // comment
#> 7 | "a2": "string"
#> 8 | },
#> 9 | "b": [
#> 10 | {
#> ℹ 9 more lines
#> ℹ Use `print(n = ...)` to see more lines
ts_tree_update(ts_tree_select(json, "a", "x", "y"), list(1, 2, 3))
#> # jsonc (30 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a1": [ #> 6 | 1, #> 7 | 2, #> 8 | 3 #> 9 | ], #> 10 | // comment #> ℹ 20 more lines #> ℹ Use `print(n = ...)` to see more lines
Write out a document
Use stdout() to write it to the screen instread of a file:
ts_tree_write(json, stdout())
#>
#> // this is a comment
#> {
#> "a": {
#> "a1": [1, 2, 3],
#> // comment
#> "a2": "string"
#> },
#> "b": [
#> {
#> "b11": true,
#> "b12": false
#> },
#> {
#> "b21": false,
#> "b22": false
#> }
#> ]
#> }
Formatting
Format the whole document:
ts_tree_format(json)
#> # jsonc (23 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": { #> 5 | "a1": [ #> 6 | 1, #> 7 | 2, #> 8 | 3 #> 9 | ], #> 10 | // comment #> ℹ 13 more lines #> ℹ Use `print(n = ...)` to see more lines
Format part of the document:
ts_tree_format( ts_tree_select(json, "a"), options = list(format = "compact") )
#> # jsonc (15 lines) #> 1 | #> 2 | // this is a comment #> 3 | { #> 4 | "a": {"a1":[1,2,3],"a2":"string"}, #> 5 | "b": [ #> 6 | { #> 7 | "b11": true, #> 8 | "b12": false #> 9 | }, #> 10 | { #> ℹ 5 more lines #> ℹ Use `print(n = ...)` to see more lines
Unserializing
Unserialize a whole document:
ts_tree_unserialize(json)
#> [[1]] #> [[1]]$a #> [[1]]$a$a1 #> [[1]]$a$a1[[1]] #> [1] 1 #> #> [[1]]$a$a1[[2]] #> [1] 2 #> #> [[1]]$a$a1[[3]] #> [1] 3 #> #> #> [[1]]$a$a2 #> [1] "string" #> #> #> [[1]]$b #> [[1]]$b[[1]] #> [[1]]$b[[1]]$b11 #> [1] TRUE #> #> [[1]]$b[[1]]$b12 #> [1] FALSE #> #> #> [[1]]$b[[2]] #> [[1]]$b[[2]]$b21 #> [1] FALSE #> #> [[1]]$b[[2]]$b22 #> [1] FALSE #> #> #> #>
Note that ts_tree_unserialize() always returns a list, the first element
of the list is the unserialized document.
Unserialize part(s) of the document:
ts_tree_unserialize(ts_tree_select(json, "b"))
#> [[1]] #> [[1]][[1]] #> [[1]][[1]]$b11 #> [1] TRUE #> #> [[1]][[1]]$b12 #> [1] FALSE #> #> #> [[1]][[2]] #> [[1]][[2]]$b21 #> [1] FALSE #> #> [[1]][[2]]$b22 #> [1] FALSE #> #> #>
Again, ts_tree_unserialize() returns a list, with one element for each
selected node.
Exploring a tree-sitter tree
It is often useful to explore the structure of a (JSONC) tree-sitter tree, to help writing the right selection or tree-sitter queries.
Print the annotated syntax tree:
ts_tree_ast(json)
#> document (1) 2|
#> ├─comment (2) |// this is a comment
#> └─object (3) 3|
#> ├─{ (4) |{
#> ├─pair (5) 4|
#> │ ├─string (6) |
#> │ │ ├─" (7) | "
#> │ │ ├─string_content (8) | a
#> │ │ └─" (9) | "
#> │ ├─: (10) | :
#> │ └─object (11) |
#> │ ├─{ (12) | {
#> │ ├─pair (13) 5|
#> │ │ ├─string (14) |
#> │ │ │ ├─" (15) | "
#> │ │ │ ├─string_content (16) | a1
#> │ │ │ └─" (17) | "
#> │ │ ├─: (18) | :
#> │ │ └─array (19) |
#> │ │ ├─[ (20) | [
#> │ │ ├─number (21) | 1
#> │ │ ├─, (22) | ,
#> │ │ ├─number (23) | 2
#> │ │ ├─, (24) | ,
#> │ │ ├─number (25) | 3
#> │ │ └─] (26) | ]
#> │ ├─, (27) | ,
#> │ ├─comment (28) 6| // comment
#> │ ├─pair (29) 7|
#> │ │ ├─string (30) |
#> │ │ │ ├─" (31) | "
#> │ │ │ ├─string_content (32) | a2
#> │ │ │ └─" (33) | "
#> │ │ ├─: (34) | :
#> │ │ └─string (35) |
#> │ │ ├─" (36) | "
#> │ │ ├─string_content (37) | string
#> │ │ └─" (38) | "
#> │ └─} (39) 8| }
#> ├─, (40) | ,
#> ├─pair (41) 9|
#> │ ├─string (42) |
#> │ │ ├─" (43) | "
#> │ │ ├─string_content (44) | b
#> │ │ └─" (45) | "
#> │ ├─: (46) | :
#> │ └─array (47) |
#> │ ├─[ (48) | [
#> │ ├─object (49) 10|
#> │ │ ├─{ (50) | {
#> │ │ ├─pair (51) 11|
#> │ │ │ ├─string (52) |
#> │ │ │ │ ├─" (53) | "
#> │ │ │ │ ├─string_content (54) | b11
#> │ │ │ │ └─" (55) | "
#> │ │ │ ├─: (56) | :
#> │ │ │ └─true (57) | true
#> │ │ ├─, (58) | ,
#> │ │ ├─pair (59) 12|
#> │ │ │ ├─string (60) |
#> │ │ │ │ ├─" (61) | "
#> │ │ │ │ ├─string_content (62) | b12
#> │ │ │ │ └─" (63) | "
#> │ │ │ ├─: (64) | :
#> │ │ │ └─false (65) | false
#> │ │ └─} (66) 13| }
#> │ ├─, (67) | ,
#> │ ├─object (68) 14|
#> │ │ ├─{ (69) | {
#> │ │ ├─pair (70) 15|
#> │ │ │ ├─string (71) |
#> │ │ │ │ ├─" (72) | "
#> │ │ │ │ ├─string_content (73) | b21
#> │ │ │ │ └─" (74) | "
#> │ │ │ ├─: (75) | :
#> │ │ │ └─false (76) | false
#> │ │ ├─, (77) | ,
#> │ │ ├─pair (78) 16|
#> │ │ │ ├─string (79) |
#> │ │ │ │ ├─" (80) | "
#> │ │ │ │ ├─string_content (81) | b22
#> │ │ │ │ └─" (82) | "
#> │ │ │ ├─: (83) | :
#> │ │ │ └─false (84) | false
#> │ │ └─} (85) 17| }
#> │ └─] (86) 18| ]
#> └─} (87) 19|}
Print the document object model:
ts_tree_dom(json)
#> document (1) #> └─object (3) #> ├─object (11) # a #> │ ├─array (19) # a1 #> │ │ ├─number (21) #> │ │ ├─number (23) #> │ │ └─number (25) #> │ └─string (35) # a2 #> └─array (47) # b #> ├─object (49) #> │ ├─true (57) # b11 #> │ └─false (65) # b12 #> └─object (68) #> ├─false (76) # b21 #> └─false (84) # b22
Print the structural summary of a tree:
ts_tree_sexpr(json)
#> [1] "(document (comment) (object (pair key: (string (string_content)) value: (ob #> ject (pair key: (string (string_content)) value: (array (number) (number) (numbe #> r))) (comment) (pair key: (string (string_content)) value: (string (string_conte #> nt))))) (pair key: (string (string_content)) value: (array (object (pair key: (s #> tring (string_content)) value: (true)) (pair key: (string (string_content)) valu #> e: (false))) (object (pair key: (string (string_content)) value: (false)) (pair #> key: (string (string_content)) value: (false)))))))"
Value
Not applicable.
Examples
# See above please.
The document of a tree-sitter tree as a character scalar
Description
The document of a tree-sitter tree as a character scalar
Usage
## S3 method for class 'ts_tree'
as.character(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
A character scalar containing the document of the tree.
See Also
as.raw.ts_tree() to get the document as a raw vector.
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
tree
as.character(tree)
Raw bytes of a document of a tree-sitter tree
Description
Raw bytes of a document of a tree-sitter tree
Usage
## S3 method for class 'ts_tree'
as.raw(x)
Arguments
x |
A |
Value
A raw vector containing the bytes of the document of the tree.
See Also
as.character.ts_tree() to get the document as a character scalar.
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
tree
as.raw(tree)
Format tree-sitter trees
Description
Format a ts_tree object for printing.
Usage
## S3 method for class 'ts_tree'
format(x, n = 10, ...)
Arguments
x |
|
n |
Number of lines, or number of selections to print. |
... |
Currently ignored. |
Details
This is the engine of print.ts_tree(),
possibly useful to obtain a printed representation without doing the
actual printing.
If there are selected nodes in the tree, those will be highlighted
in the output. See ts_tree_select() to
select nodes in a tree.
Value
Character vector of lines to print.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
json <- tsjsonc::ts_parse_jsonc(
'{ "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": 100 } }'
)
format(json)
Print a tree-sitter tree
Description
Print a ts_tree object to the screen.
Usage
## S3 method for class 'ts_tree'
print(x, n = 10, ...)
Arguments
x |
|
n |
Number of lines, or number of selections to print. |
... |
Not used currently. |
Details
Calls format.ts_tree() to format the
ts_tree object, writes the formatted object to the standard output, and
returns the original object invisibly.
Value
Invisibly returns the original ts_tree object.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
json <- tsjsonc::ts_parse_jsonc(
'{ "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": 100 } }'
)
print(json)
Edit parts of a tree-sitter tree
Description
The ts_tree_select<-() replacement
function works similarly to the combination of
ts_tree_select() and
ts_tree_update(), but
it might be more readable.
Usage
ts_tree_select(tree, ...) <- value
Arguments
tree |
A |
... |
Selection expressions, see |
value |
An R expression to serialize or
|
Details
The following two expressions are equivalent:
tree <- ts_tree_update(ts_tree_select(tree, <selectors>), value)
and
ts_tree_select(tree, <selectors>) <- value
ts_tree_deleted() is a special marker to delete elements from a
ts_tree object with ts_tree_select<- or the double bracket operator.
Value
A ts_tree object with the selected parts updated.
ts_tree_deleted() returns a marker object to be used at the right
hand side of the ts_tree_select<- or the double bracket replacement
functions, see examples below.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')
tree
ts_tree_select(tree, "a") <- 42
ts_tree_select(tree, "b", -1) <- ts_tree_deleted()
tree
Utility functions for ts language implementations (internal)
Description
These functions are for packages implementing new parsers based on the ts package. It is very unlikely that you will need to call these functions directly.
Usage
ts_collapse(
s,
sep = ", ",
sep2 = sub("^,", "", last),
last = ", and ",
trunc = Inf,
width = Inf,
ellipsis = "...",
style = c("both-ends", "head")
)
ts_cnd(..., class = NULL, call = ts_caller_env(), .envir = parent.frame())
ts_caller_arg(arg)
as_ts_caller_arg(x)
## S3 method for class 'ts_caller_arg'
as.character(x, ...)
ts_caller_env(n = 1)
ts_check_named_arg(arg, frame = -1)
ts_parse_error_cnd(tree, text, call = ts_caller_env())
Arguments
s |
For |
sep |
Separator string for most elements. |
sep2 |
Separator string for two elements. |
last |
Separator string before the last element. |
trunc |
Integer, maximum number of elements to show before truncation. |
width |
Integer, maximum display width of the collapsed string.
If the collapsed string exceeds this width, it will be truncated
with |
ellipsis |
String to indicate truncation. |
style |
Character, the collapsing style to use. Possible values are
|
... |
Arguments collapsed and interpolated into a condition message. |
class |
A character vector of classes for the condition. |
call |
Environment of the call to associate with the error condition, defaults to the caller's environment. |
.envir |
The environment in which to evaluate the |
arg |
Argument to check. |
x |
A ts_caller_arg object. |
n |
Number of frames to go up to find the caller environment. |
frame |
Frame number to inspect, defaults to the caller's frame. |
tree |
A |
text |
Raw vector, the original text used to parse the tree. |
Details
ts_collapse() collapses a character vector into a single string,
with options for truncation by number of elements or display width.
It is useful for creating informative error messages.
ts_cnd() creates a condition object. It interpolates its
arguments into a single message.
ts_caller_arg() captures the expression used as an argument
to a function, for use in error messages.
as_ts_caller_arg() converts an object into a caller argument
object. This is useful when referring to parts of the caller argument
in downstream error messages.
as.character.ts_caller_arg() formats a caller argument
object as a short string for use in error messages. Multi-line
expressions are truncated after the first line.
ts_caller_env() returns the environment of the caller function,
n levels up the call stack. This is useful for associating error
conditions with the correct call.
ts_check_named_arg() checks whether an argument was supplied
with a name. If not, it raises an error.
ts_parse_error_cnd() creates a parse error condition
associated with a ts_tree object and the original text.
The error message includes information about the location of
parse errors in the text. It also has format() and print()
methods to display the error together with the relevant lines
of the original text.
Value
ts_collapse() returns a character scalar, the collapsed string.
ts_cnd() returns an error condition object.
ts_caller_arg() returns the captured expression as a
ts_caller_arg object.
as_ts_caller_arg() returns a ts_caller_arg object.
as.character.ts_caller_arg() returns a short string
representation of the caller argument, a character scalar.
ts_caller_env() returns an environment, or NULL is called
from the global environment.
ts_check_named_arg() returns TRUE invisibly if the argument
was named, otherwise it raises an error.
ts_parse_error_cnd() returns a ts_parse_error condition
Examples
ts_collapse(letters[1:3])
ts_collapse(letters[1:10], trunc = 5)
List installed tree-sitter parsers
Description
The ts package contains a common interface to several tree-sitter
parsers, implemented in other R packages. ts_list_parsers() lists
the available parsers installed in the system.
Usage
ts_list_parsers(lib_path = .libPaths())
Arguments
lib_path |
Library paths to search for installed packages.
Default is |
Details
To see tree-sitter parser packages that are available on CRAN, but not installed on your system, see the packages that depend on ts and have a name with a 'ts' prefix.
Here is an example that includes all tree-sitter parsers at this time:
ts_list_parsers()
#> # A data frame: 2 × 5 #> package version title library loaded #> * <chr> <chr> <chr> <chr> <lgl> #> 1 tsjsonc 0.0.0.9000 Edit JSON Files /Users/gaborcsardi/Librar… FALSE #> 2 tstoml 0.0.0.9000 Edit TOML files /Users/gaborcsardi/Librar… FALSE
Value
A data frame with columns:
-
package: character, the name of the package. -
version: character, the version of the package. -
title: character, the title of the package. -
library: character, the library path where the package is installed. -
loaded: logical, whether the package is currently loaded.
Examples
ts_list_parsers()
Show the annotated syntax tree of a tree-sitter tree
Description
ts_tree_ast() prints the annotated syntax tree of a ts_tree object.
This syntax tree contains all tree-sitter nodes, and it shows the
source code associated with each node, along with line numbers.
Usage
ts_tree_ast(tree)
Arguments
tree |
A |
Details
The syntax tree and the DOM tree
This syntax tree contains all nodes of the tree-sitter parse tree, including both named and unnamed nodes and comments. E.g. for a JSON(C) document it includes the pairs, brackets, braces, commas, colons, double quotes and string escape sequences as separate nodes.
See tsitter::ts_tree_dom() for a tree that
shows the semantic structure of the parsed document, which may be
different from the syntax tree.
Value
Character vector, the formatted annotated syntax tree, line by line. It has class cli_tree, from the cli package. It may contain ANSI escape sequences for coloring and hyperlinks.
See Also
ts_tree_dom() to show the document object model (DOM) of a
ts_tree object.
Other ts_tree exploration:
[.ts_tree(),
ts_tree_dom(),
ts_tree_query(),
ts_tree_sexpr()
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
tree
ts_tree_ast(tree)
ts_tree_dom(tree)
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
)")
tree
ts_tree_ast(tree)
ts_tree_dom(tree)
Delete selected elements from a tree-sitter tree
Description
Use ts_tree_select() to select the
elements to be deleted, and then call ts_tree_delete() to remove them
from the tree.
Usage
ts_tree_delete(tree, ...)
Arguments
tree |
A |
... |
Extra arguments for methods. |
Details
The formatting of the rest of the document is left as is.
If the tree does not have a selection, the tree corresponding to the empty document is returned, i.e. the whole content is deleted.
If the tree has a selection, but it is the empty selection, then the tree is returned unchanged.
For parsers that support comments, deleting elements that include comments typically delete the comments as well. Other comments are kept as is. See details in the manual of the specific parser.
Value
The modified ts_tree object with the selected elements removed.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc(
"{ \"a\": //comment\ntrue, \"b\": [1, 2, 3] }"
)
tree
ts_tree_select(tree, "a")
ts_tree_delete(ts_tree_select(tree, "a"))
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
[servers]
alpha = { ip = "127.0.0.1", dc = "eqdc10" }
beta = { ip = "127.0.0.2", dc = "eqdc20" }
)")
tree
ts_tree_select(tree, "servers", TRUE, "dc")
ts_tree_delete(ts_tree_select(tree, "servers", TRUE, "dc"))
Print the document object model (DOM) of a tree-sitter tree
Description
ts_tree_dom() prints the document object model (DOM) tree of a ts_tree
object. This tree only includes semantic elements. E.g. for a JSON(C)
document it includes objects, arrays and various value types, but not
the syntax elements like brackets, commas or colons.
Usage
ts_tree_dom(tree)
Arguments
tree |
A |
Details
The syntax tree and the DOM tree
See ts_tree_ast() for the complete
tree-sitter syntax tree that includes all nodes, including syntax
elements like brackets and commas.
Value
Character vector, the formatted annotated syntax tree, line by line. It has class cli_tree, from the cli package. It may contain ANSI escape sequences for coloring and hyperlinks.
See Also
ts_tree_ast() to show the annotated syntax tree of a
ts_tree object.
Other ts_tree exploration:
[.ts_tree(),
ts_tree_ast(),
ts_tree_query(),
ts_tree_sexpr()
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
tree
ts_tree_ast(tree)
ts_tree_dom(tree)
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
)")
tree
ts_tree_ast(tree)
ts_tree_dom(tree)
Format the selected elements of a tree sitter tree for printing
Description
(Re)format the selected elements of the document represented by a tree-sitter tree, if the tree-sitter parser supports formatting.
Usage
ts_tree_format(tree, options, ...)
Arguments
tree |
A |
options |
A list of options for the formatting. See details in the manual of the specific parser. |
... |
Extra arguments for methods. |
Details
If tree does not have a selection, then the whole document is
formatted.
If tree has an empty selection, then it is returned unchanged.
Some parsers support options to customize the formatting. See details in the manual of the specific parser.
Value
A ts_tree object representing the reformatted document.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{ "a":true, "b": [1,2,3] }')
tree
# Format whole document
ts_tree_format(tree)
# Format each top element under the document node in one line
ts_tree_format(
ts_tree_select(ts_tree_format(tree), TRUE),
options = list(format = "oneline")
)
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
[servers]
alpha = { ip = "127.0.0.1", dc = "eqdc10" }
beta = { ip = "127.0.0.2", dc = "eqdc20" }
)")
tree
ts_tree_format(tree)
Insert a new element into a tree-sitter tree
Description
Insert a new element into each selected element.
Usage
ts_tree_insert(tree, new, key, at, options, ...)
Arguments
tree |
A |
new |
The new element to insert. The type of |
key |
The key of the new element, if inserting into a keyed element. For example a JSON(C) object or a TOML table are keyed elements. |
at |
The position to insert the new element at. The interpretation of this argument depends on the method that implements the insertion. Typically the followings are supported:
See the details in the manual of the specific parser. |
options |
A list of options for the insertion. See details in the manual of the specific parser. |
... |
Extra arguments for methods. |
Details
It is not always possible to insert a new element into a selected element. For example in a JSONC document you can only insert a new element into an array or an object, but not into scalar elements. If the insertion is not possible, an error is raised.
If tree does not have a selection, the new element is inserted into
at the top level.
If tree has an empty selection, then it is returned unchanged, i.e.
no new element is inserted.
Value
A ts_tree object representing the modified parse tree.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{ "a": true, "b": [1, 2, 3] }')
ts_tree_insert(ts_tree_select(tree, "b"), 4, at = Inf)
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
[servers]
alpha = { ip = "127.0.0.1", dc = "eqdc10" }
beta = { ip = "127.0.0.2", dc = "eqdc20" }
)")
ts_tree_insert(
ts_tree_select(tree, "servers", TRUE),
key = "active",
TRUE
)
Helper function to decide which AST nodes to highlight for a selection (internal)
Description
This function is for packages implementing new parsers based on the ts package. It is very unlikely that you will need to call this function directly.
Usage
ts_tree_mark_selection1(tree, node)
## S3 method for class 'ts_tree'
ts_tree_mark_selection1(tree, node)
Arguments
tree |
Tree-sitter tree. |
node |
Node id, integer scalar. |
Details
In parsers where AST nodes do not correspond one-to-one to DOM nodes it is useful to highlight multiple AST nodes for a single selected DOM node. This generic function can be overridden in such parsers to return multiple AST node ids for a single selected (DOM) node id.
The default implementation simply returns the input node id.
Value
Integer vector of node ids to highlight.
Examples
# This is an internal generic for parser implementations, see the
# tsjsonc and tstoml packages for examples of methods implementing
# custom behavior.
Create tree-sitter tree from file or string
Description
This is the main function to create a tree-sitter parse tree, using a ts parser implemented in another package.
The result is a ts_tree object. A ts_tree object may be queried,
edited, formatted, written to file, etc. using ts_tree methods.
Usage
ts_tree_new(
language,
file = NULL,
text = NULL,
ranges = NULL,
fail_on_parse_error = TRUE,
...
)
Arguments
language |
Language of the file or string, a |
file |
Path of a file to parse. Use either |
text |
String to parse. Use either |
ranges |
Can be used to parse part(s) of the input. It must be a data frame with
integer columns |
fail_on_parse_error |
Logical, whether to error if there are parse errors in the document.
Default is |
... |
Additional arguments for methods. |
Details
A package that implements a tree-sitter parser provides a function that
creates a ts_language object for that parser. E.g.
tsjsonc has tsjsonc::ts_language_jsonc().
You need to use the returned ts_language object as the language
argument of ts_tree_new().
Value
A ts_tree object representing the parse tree of the input. You can
use the single bracket [
operator to convert it to a data frame.
See Also
The tree-sitter parser packages typically include shortcuts to
create parse trees from strings and file, e.g.
tsjsonc::ts_parse_jsonc() and tsjsonc::ts_read_jsonc().
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# JSONC example, needs the tsjsonc package -----------------------------
json <- ts_tree_new(
tsjsonc::ts_language_jsonc(),
text = '{ "a": 1, "b": 2 }'
)
json
ts_tree_format(json)
# TOML example, needs the tstoml package -------------------------------
toml <- ts_tree_new(
tstoml::ts_language_toml(),
text = '[section]\nkey = "value"\nnumber = 42\n'
)
toml
ts_tree_format(toml)
Run tree-sitter queries on tree-sitter trees
Description
Use tree-sitter's query language to find nodes in a tree-sitter tree.
Usage
ts_tree_query(tree, query)
Arguments
tree |
A |
query |
Character string, the tree-sitter query to run. |
Details
You probably need to know some details about the specific tree-sitter parser you are using, to write effective queries. See the documentation of the parser package you are using for details about the node types and the query language support. See links below.
Value
A list with entries patterns and matched_captures.
patterns contains information about all patterns in the queries and
it is a data frame with columns: id, name, pattern, match_count.
matched_captures contains information about all matches, and it has
columns id, pattern, match, start_byte, end_byte, start_row,
start_column, end_row, end_column, name, code.
The pattern column of matched_captured refers to the id column of
patterns.
See Also
ts_tree_select() to select the nodes matching a query.
Other ts_tree exploration:
[.ts_tree(),
ts_tree_ast(),
ts_tree_dom(),
ts_tree_sexpr()
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Select all numbers in a JSONC document ------------------------------------
json <- tsjsonc::ts_parse_jsonc(
'{ "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": 100 } }'
)
ts_tree_query(json, "(number) @number")
Select elements of a tree-sitter tree
Description
This function is the heart of ts. To edit a tree-sitter tree, you first need to select the parts you want to delete or update.
Usage
ts_tree_select(tree, ..., refine = FALSE)
Arguments
tree |
A |
... |
Selection expressions, see details. |
refine |
Logical, whether to refine the current selection or start a new selection. |
Details
The selection process is iterative. Selection expressions (selectors) are applied one by one, and each selector selects nodes from the currently selected nodes. For each selector, it is applied individually to each currently selected node, and the results are concatenated.
The selection process starts from the root of the DOM tree, the document
node (see ts_tree_dom()), unless
refine = TRUE is set, in which case it starts from the current
selection.
See the various types of selection expressions below.
Selectors
All elements: TRUE
Selects all child nodes of the current nodes.
Specific keys: character vector
Selects child nodes with the given names from nodes with named children. If a node has no named children, it selects nothing from that node.
By position: integer vector
Selects child nodes by position. Positive indices count from the start, negative indices count from the end. Zero indices are not allowed.
Matching keys: regular expression
A character scalar named regex can be used to select child nodes
whose names match the given regular expression, from nodes with named
children. If a node has no named children, it selects nothing from that
node.
Tree sitter query matches
A character scalar named query can be used to select nodes matching
a tree-sitter query. See ts_tree_query()
for details on tree-sitter queries.
Instead of a character scalar this can also be a two-element list, where the first element is the query string and the second element is a character vector of capture names to select. In this case only nodes matching the given capture names will be selected.
Explicit node ids
You can use I(c(...)) to select nodes by their ids directly. This is
for advanced use cases only.
Refining selections
If the refine argument of
ts_tree_select() is TRUE, then
the selection starts from the already selected elements (all of them
simultanously), instead of starting from the document element.
The ts_tree_select<-() replacement function
The ts_tree_select<-() replacement
function works similarly to the combination of
ts_tree_select() and
ts_tree_update(), but it might be more
readable.
The [[ and [[<- operators
The [[ operator works similarly to the combination of
ts_tree_select() and
ts_tree_unserialize(), but it
might be more readable.
The [[<- operator works similarly to the combination of
ts_tree_select() and
ts_tree_update(), (and also to the
replacement function ts_tree_select<-()),
but it might be more readable.
Value
A ts_tree object with the selected parts.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# ----------------------------------------------------------------------
# Create a JSONC tree, needs the tsjsonc package
json <- ts_tree_new(
tsjsonc::ts_language_jsonc(),
text = '{ "a": 1, "b": 2, "c": { "d": 3, "e": 4 } }'
)
ts_tree_select(json, "c", "d")
# ----------------------------------------------------------------------
# Create a TOML tree, needs the tstoml package
toml <- ts_tree_new(
tstoml::ts_language_toml(),
text = tstoml::toml_example_text()
)
ts_tree_select(toml, "servers", TRUE, "ip")
Select nodes from a tree-sitter tree (internal)
Description
This function is for packages implementing new parsers based on the ts package. It is very unlikely that you will need to call this function directly.
Usage
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.ts_tree_selector_default'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.NULL'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.ts_tree_selector_ids'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.ts_tree_selector_tsquery'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.character'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.integer'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.numeric'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.ts_tree_selector_regex'
ts_tree_select1(tree, node, slt)
## S3 method for class 'ts_tree.logical'
ts_tree_select1(tree, node, slt)
Arguments
tree |
A |
node |
Integer scalar, the node id to select from. |
slt |
A selector object, see details in |
Details
A parser package may implement methods for this generic to change the
behavior of ts_tree_select() for a
certain selector type, or even add new selector types.
Each new method should be named as
ts_tree_select.<ts_tree_class>.<selector_class>
The ts package implement deault methods for the selector types described
in the ts_tree_select() manual page.
ts_tree_selector_default selector
Method: ts_tree_select1.ts_tree.ts_tree_selector_default
This method is used to select the default element(s), when there is no selected element. E.g. when starting a new selection from the root of the DOM tree.
The default implementation returns the ids of all children of the document root in the AST, except comments. If there are no such children, it returns the id of the document root of the AST itself (always id 1).
NULL selector
Method: ts_tree_select1.ts_tree.NULL
This method is used for the NULL selector, that is supposed to
clear the selection. You probably do not need to override this method.
The default implementation returns an empty integer vector.
ts_tree_selector_ids selector
Method: ts_tree_select1.ts_tree.ts_tree_selector_ids
This method is used to select nodes by their ids directly. You probably do not need to override this method. The default implementation returns the ids stored in the selector.
Note
This behaviour may change in the future to select only nodes in the subtree of the current node.
ts_tree_selector_tsquery selector
Method: ts_tree_select1.ts_tree.ts_tree_selector_tsquery
This method is used to select nodes matching a tree-sitter query. You probably do not need to override this method. The default implementation returns the ids stored in the selector.
Note
This behaviour may change in the future to select only nodes in the subtree of the current node.
character (character vector) selector
Method: ts_tree_select1.ts_tree.character
This method is used when the selector is a character vector.
The default implementation selects DOM children of node whose names
are in the character vector. If not all children o node are named,
it returns an empty integer vector. (E.g. in a JSONC document it returns
an empty integer vector when nodes is an array.)
integer (integer vector) selector
Method: ts_tree_select1.ts_tree.integer
This method is used when the selector is an integer vector.
The default implementation selects DOM children of node by position.
Positive indices count from the start, negative indices count from the
end. Zero indices are not allowed and an error is raised if any are
used.
numeric (numeric, double vector) selector
Method: ts_tree_select1.ts_tree.numeric
This method is used when the selector is a numeric (double) vector. It currrently coerces the numeric vector to integer and calls the integer method.
ts_tree_selector_regex (regular expression) selector
Method: ts_tree_select1.ts_tree.ts_tree_selector_regex
This method is used when the selector is a regular expression.
The default implementation selects DOM children of node whose names
match the regular expression. If not all children o node are named,
it returns an empty integer vector. (E.g. in a JSONC document it
returns an empty integer vector when nodes is an array.)
logical (logical vector) selector
Method: ts_tree_select1.ts_tree.logical
This method is used when the selector is a logical vector.
The default implementation only supports scalar TRUE, which selects
all DOM children of node. Other values raise an error.
Value
Must return an integer vector of selected node ids.
Examples
# This is an internal generic for parser implementations, see the
# tsjsonc and tstoml packages for examples of methods implementing
# selector types.
Helper functions for tree-sitter tree selections (internal)
Description
These functions are for packages implementing new parsers based on the ts package. It is very unlikely that you will need to call these functions directly.
Usage
ts_tree_selection(tree, default = TRUE)
ts_tree_selected_nodes(tree, default = TRUE)
Arguments
tree |
A |
default |
Logical, whether to return the default selection if there
is no explicit selection, or |
Details
ts_tree_selection() returns the current selection, as a list
of selectors.
ts_tree_selected_nodes() returns the ids of the currently
selected nodes.
Value
ts_tree_selection() returns a list of selection records.
ts_tree_selected_nodes() returns the ids of the currently
selected nodes.
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')
tree <- ts_tree_select(tree, "b", -1)
ts_tree_selection(tree)
Show the syntax tree of a tree-sitter tree
Description
Show the structure of a tree-sitter tree as an S-expression.
Usage
ts_tree_sexpr(tree)
Arguments
tree |
A |
Details
This function returns a nested list representation of the syntax tree, where each node is represented as a list with its type and children.
Value
A string representing the S-expression of the syntax tree.
See Also
Other ts_tree exploration:
[.ts_tree(),
ts_tree_ast(),
ts_tree_dom(),
ts_tree_query()
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_unserialize(),
ts_tree_update(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc(
"{ \"a\": //comment\ntrue, \"b\": [1, 2, 3] }"
)
ts_tree_sexpr(tree)
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
[servers]
alpha = { ip = "127.0.0.1", dc = "eqdc10" }
beta = { ip = "127.0.0.2", dc = "eqdc20" }
)")
ts_tree_sexpr(tree)
Unserialize selected elements of a tree-sitter tree
Description
Unserialize the selected elements of a ts_tree object, i.e. convert
them to R objects.
Usage
ts_tree_unserialize(tree)
Arguments
tree |
A |
Details
If no elements are selected in the tree, then the whole document is unserialized.
If the tree has an empty selection, then an empty list is returned.
The [[ operator
The [[ operator works similarly to the combination of
ts_tree_select() and
ts_tree_unserialize(), but it might be more readable.
For the details on how the selected elements are mapped to R objects, see the documentation of the methods in the parser packages. The methods in the installed parser packages are linked below.
Value
List of R objects, with one entry for each selected element.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_update(),
ts_tree_write()
Other serialization functions:
[[.ts_tree()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')
tree
ts_tree_unserialize(ts_tree_select(tree, c("b", "c")))
ts_tree_unserialize(ts_tree_select(tree, "b"))
Replace selected elements with a new element in a tree-sitter tree
Description
Replace all selected elements with a new element.
Usage
ts_tree_update(tree, new, options, ...)
Arguments
tree |
A |
new |
The new element to replace the selected elements with. The type of See details in the manual of the specific parser. |
options |
A list of options for the update. |
... |
Extra arguments for methods. |
Details
If the tree does not have a selection, the new element replaces the whole document.
If the tree has an empty selection, the new element is inserted at the position of where the selected elements would be.
Value
The modified ts_tree object with the selected elements replaced
by the new element.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_write()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc(r"(
{
"name": "example",
"version": "1.0.0",
"dependencies": {
"tsjsonc": "^0.1.0"
}
}
)")
ts_tree_update(ts_tree_select(tree, "version"), "2.0.0")
# Create a parse tree with tstoml --------------------------------------
tree <- tstoml::ts_parse_toml(r"(
[package]
name = "example"
version = "1.0.0"
depdendencies = { tstoml = "0.1.0" }
)")
ts_tree_update(ts_tree_select(tree, "package", "version"), "2.0.0")
Write a tree-sitter tree to a file
Description
Writes the document of a ts ts_tree object to a file or connection.
Usage
ts_tree_write(tree, file = NULL)
Arguments
tree |
A |
file |
Character string, connection, or |
Details
If tree was created from a file, then ts_tree_write() by default
writes it back to the same file. Otherwise, the file argument must be
specified.
To write to a connection, pass a connection object to the file
argument. If the connection is opened in binary mode, the raw bytes
are written using base::writeBin(). Otherwise, the raw bytes are
converted to characters using the system encoding before writing using
base::rawToChar().
Use file = stdout() to write to the standard output, i.e. to the
console in an interactive R session.
Value
Invisibly returns NULL.
See Also
Other ts_tree generics:
[[.ts_tree(),
[[<-.ts_tree(),
format.ts_tree(),
print.ts_tree(),
select-set,
ts_tree_ast(),
ts_tree_delete(),
ts_tree_dom(),
ts_tree_format(),
ts_tree_insert(),
ts_tree_new(),
ts_tree_query(),
ts_tree_select(),
ts_tree_sexpr(),
ts_tree_unserialize(),
ts_tree_update()
Examples
# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"foo": 42, "bar": [1, 2, 3]}')
# Format and write to file
ts_tree_write(ts_tree_format(tree), "example.json")