grit_util/
parser.rs

1use crate::{AnalysisLogs, AstNode};
2use std::{borrow::Cow, marker::PhantomData, path::Path};
3
4/// Information on where a file came from, for the parser to be smarter
5#[derive(Clone, Debug)]
6pub enum FileOrigin<'tree, Tree>
7where
8    Tree: Ast,
9{
10    /// A file we are parsing for the first time, from disk
11    Fresh,
12    /// A file we have parsed before, and are re-parsing after mutating
13    Mutated,
14    /// A file that was constructed by Grit
15    New,
16    /// We might need these
17    _Phantom(PhantomData<&'tree Tree>),
18}
19
20impl<'tree, Tree: Ast> FileOrigin<'tree, Tree> {
21    /// Is this a file we are parsing for the first time, from outside Grit?
22    pub fn is_fresh(&self) -> bool {
23        matches!(self, FileOrigin::Fresh)
24    }
25}
26
27pub trait Parser {
28    type Tree: Ast;
29
30    fn parse_file(
31        &mut self,
32        body: &str,
33        path: Option<&Path>,
34        logs: &mut AnalysisLogs,
35        origin: FileOrigin<Self::Tree>,
36    ) -> Option<Self::Tree>;
37
38    fn parse_snippet(
39        &mut self,
40        pre: &'static str,
41        source: &str,
42        post: &'static str,
43    ) -> SnippetTree<Self::Tree>;
44}
45
46pub trait Ast: std::fmt::Debug + PartialEq + Sized {
47    type Node<'a>: AstNode
48    where
49        Self: 'a;
50
51    fn root_node(&self) -> Self::Node<'_>;
52
53    /// Returns the full source code of the tree.
54    fn source(&self) -> Cow<str>;
55}
56
57#[derive(Clone, Debug)]
58pub struct SnippetTree<Tree: Ast> {
59    pub tree: Tree,
60    pub source: String,
61    pub prefix: &'static str,
62    pub postfix: &'static str,
63    pub snippet_start: u32,
64    pub snippet_end: u32,
65}