Skip to main content

syntree/
lib.rs

1//! [<img alt="github" src="https://img.shields.io/badge/github-udoprog/syntree-8da0cb?style=for-the-badge&logo=github" height="20">](https://github.com/udoprog/syntree)
2//! [<img alt="crates.io" src="https://img.shields.io/crates/v/syntree.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/syntree)
3//! [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-syntree-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/syntree)
4//!
5//! A memory efficient syntax tree.
6//!
7//! This crate provides a tree structure which always is contiguously stored and
8//! manipulated in memory. It provides similar APIs as [`rowan`] and is intended
9//! to be an efficient replacement for it (read more below).
10//!
11//! Anything can be stored in the tree as long as it implements `Copy`.
12//!
13//! <br>
14//!
15//! ## Usage
16//!
17//! Add `syntree` to your crate:
18//!
19//! ```toml
20//! syntree = "0.20.3"
21//! ```
22//!
23//! If you want a complete sample for how `syntree` can be used for parsing, see
24//! the [calculator example][calculator].
25//!
26//! <br>
27//!
28//! ## Syntax trees
29//!
30//! This crate provides a way to efficiently model [abstract syntax trees]. The
31//! nodes of the tree are typically represented by variants in an enum, but
32//! [could be whatever you want][any-syntax].
33//!
34//! Each tree consists of *nodes* and *tokens*. Nodes are intermediary elements
35//! in the tree which encapsulate zero or more other nodes or tokens, while
36//! tokens are leaf elements representing exact source locations.
37//!
38//! An example tree for the simple expression `256 / 2 + 64 * 2` could be
39//! represented like this:
40//!
41//! ```text
42//! Operation@0..16
43//!   Number@0..3
44//!     Number@0..3 "256"
45//!   Whitespace@3..4 " "
46//!   Operator@4..5
47//!     Div@4..5 "/"
48//!   Whitespace@5..6 " "
49//!   Number@6..7
50//!     Number@6..7 "2"
51//!   Whitespace@7..8 " "
52//!   Operator@8..9
53//!     Plus@8..9 "+"
54//!   Whitespace@9..10 " "
55//!   Operation@10..16
56//!     Number@10..12
57//!       Number@10..12 "64"
58//!     Whitespace@12..13 " "
59//!     Operator@13..14
60//!       Mul@13..14 "*"
61//!     Whitespace@14..15 " "
62//!     Number@15..16
63//!       Number@15..16 "2"
64//! ```
65//!
66//! > Try it for yourself with:
67//! >
68//! > ```sh
69//! > cargo run --example calculator -- "256 / 2 + 64 * 2"
70//! > ```
71//!
72//! The primary difference between `syntree` and [`rowan`] is that *we don't
73//! store the original source* in the syntax tree. Instead, the user of the
74//! library is responsible for providing it as necessary. Like when calling
75//! [`print_with_source`].
76//!
77//! The API for constructing a syntax tree is provided through [`Builder`] which
78//! implements streaming builder methods. Internally the builder is represented
79//! as a contiguous slab of memory. Once a tree is built the structure of the
80//! tree can be queried through the [`Tree`] type.
81//!
82//! Note that [`syntree::tree!`] is only a helper which simplifies building
83//! trees for examples. It corresponds exactly to performing [`open`],
84//! [`close`], and [`token`][`Builder::token`] calls on [`Builder`] as specified.
85//!
86//! ```
87//! use syntree::{Builder, Span};
88//!
89//! #[derive(Debug, Clone, Copy, PartialEq, Eq)]
90//! enum Syntax {
91//!     Number,
92//!     Lit,
93//!     Nested,
94//! }
95//!
96//! use Syntax::*;
97//!
98//! let mut tree = Builder::new();
99//!
100//! tree.open(Number)?;
101//! tree.token(Lit, 1)?;
102//! tree.token(Lit, 3)?;
103//!
104//! tree.open(Nested)?;
105//! tree.token(Lit, 1)?;
106//! tree.close()?;
107//!
108//! tree.close()?;
109//!
110//! let tree = tree.build()?;
111//!
112//! let expected = syntree::tree! {
113//!     Number => {
114//!         (Lit, 1),
115//!         (Lit, 3),
116//!         Nested => {
117//!             (Lit, 1)
118//!         }
119//!     }
120//! };
121//!
122//! assert_eq!(tree, expected);
123//!
124//! let number = tree.first().ok_or("missing number")?;
125//! assert_eq!(number.span(), Span::new(0, 5));
126//! # Ok::<_, Box<dyn core::error::Error>>(())
127//! ```
128//!
129//! Note how the resulting [`Span`] for `Number` corresponds to the full span of
130//! its `Lit` children. Including the ones within `Nested`.
131//!
132//! Trees are usually constructed by parsing an input. This library encourages
133//! the use of a [handwritten pratt parser][pratt]. See the [calculator
134//! example][calculator] for a complete use case.
135//!
136//! <br>
137//!
138//! ### Nodes, tokens and elements
139//!
140//! A tree hands out three kinds of handles. A [`Node`] is an interior node, one
141//! which was [`open`]ed, and a [`Token`] is a leaf added with [`token`][`Builder::token`]. Anything
142//! which can be either, such as a child or a step of a walk, is an [`Element`],
143//! which has the navigation methods of a node and acts as an empty leaf when it
144//! is a token. Use `into_node` or `into_token` to get at what only one of them
145//! has, such as their ids.
146//!
147//! Nodes and tokens are stored in separate arrays, so node ids and token ids
148//! are separate index spaces. Ids are not dense either: an explicit span which
149//! leaves a gap after the previous token takes an internal token id for the
150//! gap.
151//!
152//! ```
153//! let tree = syntree::tree! {
154//!     "root" => {
155//!         ("lit", 3),
156//!         "child" => {
157//!             ("ws", 1)
158//!         }
159//!     }
160//! };
161//!
162//! let root = tree.first().ok_or("missing root")?;
163//!
164//! let kinds = root
165//!     .children()
166//!     .map(|e| (e.value(), e.is_node()))
167//!     .collect::<Vec<_>>();
168//!
169//! assert_eq!(kinds, [("lit", false), ("child", true)]);
170//!
171//! let child = root.last().and_then(|e| e.into_node()).ok_or("missing child")?;
172//! assert_eq!(tree.get(child.id()), Some(child));
173//! # Ok::<_, Box<dyn core::error::Error>>(())
174//! ```
175//!
176//! <br>
177//!
178//! ### Trivia
179//!
180//! Whitespace and comments can be added with [`trivia`] instead of [`token`][`Builder::token`].
181//! Trivia is stored in the token array like any other token, so node spans
182//! cover it and every source byte stays reachable, but `children()`, `walk()`
183//! and the other iterators skip it unless asked to include it with
184//! `with_trivia()`. Point accessors such as `first()` or `next()` are structural
185//! and do see trivia; `is_trivia()` tells it apart. The flag lives in the top
186//! bit of a token's parent pointer, so it costs no space, which halves the
187//! number of interior nodes a pointer width can address.
188//!
189//! ```
190//! let mut tree = syntree::Builder::new();
191//!
192//! tree.open("call")?;
193//! tree.token("ident", 3)?;
194//! tree.trivia("whitespace", 1)?;
195//! tree.token("args", 2)?;
196//! tree.close()?;
197//!
198//! let tree = tree.build()?;
199//! let call = tree.first().ok_or("missing call")?;
200//!
201//! let kinds = call.children().map(|e| e.value()).collect::<Vec<_>>();
202//! assert_eq!(kinds, ["ident", "args"]);
203//!
204//! let kinds = call.children().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
205//! assert_eq!(kinds, ["ident", "whitespace", "args"]);
206//! assert_eq!(call.span(), syntree::Span::new(0, 6));
207//! # Ok::<_, Box<dyn core::error::Error>>(())
208//! ```
209//!
210//! <br>
211//!
212//! ## Compact or empty spans
213//!
214//! The [`Flavor`] of a tree decides the types used for its spans and pointers.
215//! The default flavor, [`FlavorDefault`], uses `u32` indexes for spans and
216//! `u32`-based pointers to address nodes, which bounds a tree to about 4
217//! billion elements. A custom flavor declared with [`flavor!`] can change
218//! both, and is used through constructors such as [`Builder::new_with`]:
219//!
220//! * `type Index` is the type of span positions: `u32`, `usize`, or [`Empty`]
221//!   for no spans at all (see below).
222//! * `type Width` is the width of node pointers, such as `u8`, `u16`, `u32`
223//!   or `usize`, and defaults to `u32`. It bounds how many elements a tree
224//!   can hold, adding more fails with [`Error::Overflow`].
225//!
226//! ```
227//! use syntree::{Builder, Span};
228//!
229//! syntree::flavor! {
230//!     struct FlavorCompact {
231//!         type Index = u32;
232//!         type Width = u16;
233//!     }
234//! };
235//!
236//! let mut tree = Builder::<_, FlavorCompact>::new_with();
237//!
238//! tree.open("root")?;
239//! tree.open("child")?;
240//! tree.token("token", 100)?;
241//! tree.close()?;
242//! tree.open("child2")?;
243//! tree.close()?;
244//! tree.close()?;
245//!
246//! let tree = tree.build()?;
247//!
248//! // Trees of different flavors compare equal if their structure, values and
249//! // spans do.
250//! let expected = syntree::tree! {
251//!     "root" => {
252//!         "child" => { ("token", 100) },
253//!         "child2" => {}
254//!     }
255//! };
256//!
257//! assert_eq!(tree, expected);
258//! assert_eq!(tree.span(), Span::new(0, 100));
259//! # Ok::<_, Box<dyn core::error::Error>>(())
260//! ```
261//!
262//! Using [`Empty`] as the index allows for building trees without spans, if
263//! that is something you want to do:
264//!
265//! ```
266//! use syntree::{Builder, Empty, Tree};
267//!
268//! syntree::flavor! {
269//!     struct FlavorEmpty {
270//!         type Index = Empty;
271//!     }
272//! };
273//!
274//! let mut tree = Builder::<_, FlavorEmpty>::new_with();
275//!
276//! tree.open("root")?;
277//! tree.open("child")?;
278//! tree.token("token", Empty)?;
279//! tree.close()?;
280//! tree.open("child2")?;
281//! tree.close()?;
282//! tree.close()?;
283//!
284//! let tree = tree.build()?;
285//!
286//! let expected: Tree<_, FlavorEmpty> = syntree::tree_with! {
287//!     "root" => {
288//!         "child" => { "token" },
289//!         "child2" => {}
290//!     }
291//! };
292//!
293//! assert_eq!(tree, expected);
294//! assert!(tree.span().is_empty());
295//! # Ok::<_, Box<dyn core::error::Error>>(())
296//! ```
297//!
298//! <br>
299//!
300//! ## Why not `rowan`?
301//!
302//! I love [`rowan`]. It's the reason why I started this project. But this crate
303//! still exists for a few philosophical differences that would be hard to
304//! reconcile directly in `rowan`.
305//!
306//! `rowan` only supports adding types which in some way can be coerced into an
307//! `repr(u16)` as part of the syntax tree. I think this decision is reasonable,
308//! but it precludes you from designing trees which contain anything else other
309//! than source references without having to perform some form of indirect
310//! lookup. This is something needed in order to move [Rune] to lossless syntax
311//! trees (see [the representation of `Kind::Str` variant][kind-str]).
312//!
313//! To exemplify this scenario consider the following syntax:
314//!
315//! ```
316//! #[derive(Debug, Clone, Copy)]
317//! enum Syntax {
318//!     /// A string referenced somewhere else using the provided ID.
319//!     Synthetic(usize),
320//!     /// A literal string from the source.
321//!     Literal,
322//!     /// Whitespace.
323//!     Whitespace,
324//!     /// A lexer error.
325//!     Error,
326//! }
327//! ```
328//!
329//! You can see the [full `synthetic_strings` example][synthetic_strings] for
330//! how this might be used. But not only can the `Synthetic` token correspond to
331//! some source location (as it should because it was expanded from one!). It
332//! also directly represents that it's *not* a literal string referencing a
333//! source location.
334//!
335//! In [Rune] this became needed once we started [expanding
336//! macros][rune-macros]. Because macros expand to things which do not reference
337//! source locations so we need some other mechanism to include what the tokens
338//! represent in the syntax trees.
339//!
340//! You can try a *very* simple lex-time variable expander in the
341//! [`synthetic_strings` example][synthetic_strings]:
342//!
343//! ```sh
344//! cargo run --example synthetic_strings -- "Hello $world"
345//! ```
346//!
347//! Which would output:
348//!
349//! ```text
350//! Tree:
351//! Literal@0..5 "Hello"
352//! Whitespace@5..6 " "
353//! Synthetic(0)@6..12 "$world"
354//! Eval:
355//! 0 = "Hello"
356//! 1 = "Earth"
357//! ```
358//!
359//! So in essence `syntree` doesn't believe you need to store strings in the
360//! tree itself. Even if you want to deduplicate string storage. All of that can
361//! be done on the side and encoded into the syntax tree as you wish.
362//!
363//! <br>
364//!
365//! ### Errors instead of panics
366//!
367//! Another point where this crate differs is that we rely on propagating a
368//! [`Error`] during tree construction if the API is used incorrectly
369//! *instead* of panicking.
370//!
371//! While on the surface this might seem like a minor difference in opinion on
372//! whether programming mistakes should be errors or not. In my experience
373//! parsers tend to be part of a crate in a larger project. And errors triggered
374//! by edge cases in user-provided input that once encountered can usually be
375//! avoided.
376//!
377//! So let's say [Rune] is embedded in [OxidizeBot] and there's a piece of code
378//! in a user-provided script which triggers a bug in the rune compiler. Which
379//! in turn causes an illegal tree to be constructed. If tree construction
380//! simply panics, the whole bot will go down. But if we instead propagate an
381//! error this would have to be handled in [OxidizeBot] which could panic if it
382//! wanted to. In this instance it's simply more appropriate to log the error
383//! and unload the script (and hopefully receive a bug report!) than to crash
384//! the bot.
385//!
386//! Rust has great diagnostics for indicating that results should be handled,
387//! and while it is [more awkward to deal with results][syntree-math] than [to
388//! simply panic][rowan-math] I believe that the end result is more robust
389//! software.
390//!
391//! <br>
392//!
393//! ## Performance and memory use
394//!
395//! The only goal in terms of performance is to be as performant as `rowan`. And
396//! cursory testing shows `syntree` to be a bit faster on synthetic workloads
397//! which can probably be solely attributed to storing and manipulating the
398//! entire tree in a single contiguous memory region. This might or might not
399//! change in the future, depending on if the needs for `syntree` changes. While
400//! performance is important, it *is not* a primary focus.
401//!
402//! I also expect (but haven't verified) that `syntree` could end up having a
403//! similarly low memory profile as `rowan` which performs node deduplication.
404//! The one caveat is that it depends on how the original source is stored and
405//! queried. Something which `rowan` solves for you, but `syntree` leaves as an
406//! exercise to the reader.
407//!
408//! <br>
409//!
410//! ## Features
411//!
412//! * `alloc` (default) stores trees in `Vec`s.
413//! * `std` (default) enables [`edit`] and [`print`], and implies `alloc`.
414//!
415//! Without `alloc` the default storage is [`EmptyVec`], which discards
416//! everything pushed into it. A tree built with [`Builder::new`] or any flavor
417//! using default storage then holds nothing, and building it fails with an
418//! error such as [`Error::MissingNode`]. To build trees without `alloc`,
419//! declare a flavor through [`flavor!`] with its own `type Storage<T>`, such
420//! as a fixed-capacity array implementing [`Storage`].
421//!
422//! Checkpoints are kept in the same storage, so no allocator is needed.
423//!
424//! [`Builder::new_with`]: crate::Builder::new_with
425//! [`Builder::new`]: crate::Builder::new
426//! [`Builder`]: crate::Builder
427//! [`close`]: crate::Builder::close
428//! [`edit`]: crate::edit
429//! [`Empty`]: crate::Empty
430//! [`EmptyVec`]: crate::EmptyVec
431//! [`Element`]: crate::Element
432//! [`Error::Overflow`]: crate::Error::Overflow
433//! [`Error::MissingNode`]: crate::Error::MissingNode
434//! [`Error`]: crate::Error
435//! [`Flavor`]: crate::Flavor
436//! [`FlavorDefault`]: crate::FlavorDefault
437//! [`flavor!`]: crate::flavor!
438//! [`Node`]: crate::Node
439//! [`open`]: crate::Builder::open
440//! [`print_with_source`]: crate::print::print_with_source
441//! [`print`]: crate::print
442//! [`rowan`]: https://docs.rs/rowan/latest/rowan/
443//! [`Span`]: crate::Span
444//! [`Storage`]: crate::Storage
445//! [`syntree::tree!`]: crate::tree!
446//! [`Token`]: crate::Token
447//! [`Builder::token`]: crate::Builder::token
448//! [`trivia`]: crate::Builder::trivia
449//! [`Tree::node_with_span`]: crate::Tree::node_with_span
450//! [`Tree`]: crate::Tree
451//! [abstract syntax trees]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
452//! [any-syntax]: https://github.com/udoprog/syntree/blob/main/examples/iterator.rs
453//! [calculator]: https://github.com/udoprog/syntree/blob/main/examples/calculator
454//! [kind-str]: https://github.com/rune-rs/rune/blob/e97a32e/crates/rune/src/ast/generated.rs#L4359
455//! [OxidizeBot]: https://github.com/udoprog/OxidizeBot
456//! [pratt]: https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html
457//! [rowan-math]: https://github.com/rust-analyzer/rowan/blob/master/examples/math.rs
458//! [rune-macros]: https://github.com/rune-rs/rune/blob/main/crates/rune-modules/src/core.rs#L36
459//! [Rune]: https://github.com/rune-rs/rune
460//! [synthetic_strings]: https://github.com/udoprog/syntree/blob/main/examples/synthetic_strings.rs
461//! [syntree-math]: https://github.com/udoprog/syntree/blob/main/examples/math.rs
462
463#![deny(missing_docs)]
464#![cfg_attr(docsrs, feature(doc_cfg))]
465#![no_std]
466
467#[cfg(feature = "alloc")]
468extern crate alloc;
469
470#[cfg(feature = "std")]
471extern crate std;
472
473#[macro_use]
474mod macros;
475mod builder;
476
477#[cfg(feature = "std")]
478#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
479pub mod edit;
480
481mod empty;
482mod error;
483#[macro_use]
484mod flavor;
485mod index;
486mod links;
487pub mod node;
488pub mod pointer;
489pub mod print;
490mod span;
491mod tree;
492
493#[doc(inline)]
494pub use self::builder::{Builder, Checkpoint};
495#[doc(inline)]
496pub use self::empty::{Empty, EmptyVec};
497#[doc(inline)]
498pub use self::error::Error;
499#[doc(inline)]
500pub use self::flavor::{Flavor, FlavorDefault, Storage};
501#[doc(inline)]
502pub use self::index::{Index, Length};
503#[doc(inline)]
504pub use self::node::{Element, Node, NodeOrToken, Token};
505#[doc(inline)]
506pub use self::pointer::{Pointer, Width};
507#[doc(inline)]
508pub use self::span::Span;
509#[doc(inline)]
510pub use self::tree::Tree;
511
512#[doc(hidden)]
513pub mod macro_support {
514    #[cfg(feature = "alloc")]
515    pub type Vec<T> = alloc::vec::Vec<T>;
516
517    #[cfg(not(feature = "alloc"))]
518    pub type Vec<T> = crate::empty::EmptyVec<T>;
519}