parse_tree/
lib.rs

1//! `parse_tree` is a library to represent so-called parse tree.
2//! A parse tree is a non-abstract AST: it's a generic syntax tree
3//! which remembers all whitespace, comments and other trivia.
4extern crate text_unit;
5
6use std::{ops};
7
8mod top_down_builder;
9mod bottom_up_builder;
10pub mod algo;
11
12pub use text_unit::{TextRange, TextUnit};
13pub use top_down_builder::TopDownBuilder;
14pub use bottom_up_builder::BottomUpBuilder;
15
16/// A type of a syntactic construct, including both leaf tokens
17/// and composite nodes, like "a comma" or "a function".
18#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
19pub struct Symbol(pub u16);
20
21/// A token of source code.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct Token {
24    /// The kind of token.
25    pub symbol: Symbol,
26    /// The length of the token.
27    pub len: TextUnit,
28}
29
30#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
31pub struct PtNodeId(u32);
32
33#[derive(Debug, Clone)]
34pub struct PtNode {
35    symbol: Symbol,
36    range: TextRange,
37    parent: Option<PtNodeId>,
38    first_child: Option<PtNodeId>,
39    next_sibling: Option<PtNodeId>,
40}
41
42/// The parse tree for a single source file.
43#[derive(Debug, Clone)]
44pub struct ParseTree {
45    root: PtNodeId,
46    nodes: Vec<PtNode>,
47}
48
49impl ParseTree {
50    /// The root node of this tree.
51    pub fn root(&self) -> PtNodeId {
52        self.root
53    }
54}
55
56impl ops::Index<PtNodeId> for ParseTree {
57    type Output = PtNode;
58
59    fn index(&self, id: PtNodeId) -> &PtNode {
60        &self.nodes[id.0 as usize]
61    }
62}
63
64impl PtNode {
65    /// The symbol of the token at this node.
66    pub fn symbol(&self) -> Symbol {
67        self.symbol
68    }
69
70    /// The text range covered by the token at this node.
71    pub fn range(&self) -> TextRange {
72        self.range
73    }
74
75    /// The parent node of this node.
76    pub fn parent(&self) -> Option<PtNodeId> {
77        self.parent
78    }
79
80    /// The first child of this node.
81    pub fn first_child(&self) -> Option<PtNodeId> {
82        self.first_child
83    }
84
85    /// The next sibling of this node
86    pub fn next_sibling(&self) -> Option<PtNodeId> {
87        self.next_sibling
88    }
89}
90
91impl ops::Index<PtNodeId> for Vec<PtNode> {
92    type Output = PtNode;
93
94    fn index(&self, PtNodeId(idx): PtNodeId) -> &PtNode {
95        &self[idx as usize]
96    }
97}
98
99impl ops::IndexMut<PtNodeId> for Vec<PtNode> {
100    fn index_mut(&mut self, PtNodeId(idx): PtNodeId) -> &mut PtNode {
101        &mut self[idx as usize]
102    }
103}
104
105fn fill<T>(slot: &mut Option<T>, value: T) {
106    assert!(slot.is_none());
107    *slot = Some(value);
108}