fea_rs/parse/
tree.rs

1//! the result of a parsing operation
2
3use std::sync::Arc;
4
5use super::source::Source;
6use super::{FileId, SourceList, SourceMap};
7use crate::{token_tree::typed, Diagnostic, Node};
8
9/// A fully parsed feature file, with attached imports and a sourcemap.
10///
11/// As well as representing the entire AST, this type also allows mapping tokens
12/// and other spans back to a position in a particular source file.
13///
14/// This is cheap to clone, so it can be attached to diagnostics, allowing them
15/// to print themselves where needed.
16#[derive(Clone, Debug, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct ParseTree {
19    pub(crate) root: Node,
20    // Arc so we can send across threads
21    pub(crate) sources: Arc<SourceList>,
22    pub(crate) map: Arc<SourceMap>,
23}
24
25impl ParseTree {
26    /// The root node for this parse tree
27    pub fn root(&self) -> &Node {
28        &self.root
29    }
30
31    /// The root node, as typed AST node
32    pub fn typed_root(&self) -> typed::Root {
33        typed::Root::try_from_node(&self.root).expect("parse tree has invalid root node type")
34    }
35
36    /// Return a refernce to the source map
37    pub fn source_map(&self) -> &SourceMap {
38        &self.map
39    }
40
41    /// Return the source for this id, if it exists in the source map
42    pub fn get_source(&self, id: FileId) -> Option<&Source> {
43        self.sources.get(&id)
44    }
45
46    /// Generate a string suitable for presenting a [`Diagnostic`] to the user.
47    ///
48    /// This associates the message with the appropriate source location and
49    /// syntax highlighting.
50    pub fn format_diagnostic(&self, err: &Diagnostic, colorize: bool) -> String {
51        self.sources.format_diagnostic(err, colorize)
52    }
53}