luau_parser/impl/
cst.rs

1//! All `impl` blocks for [`Cst`].
2
3use luau_lexer::prelude::{Lexer, Token};
4use smol_str::SmolStr;
5
6use crate::types::{AstStatus, Block, Cst, ParseWithArgs, Print, PrintingError};
7
8impl Cst {
9    /// The actual parsing logic for the [`Cst`].
10    pub(crate) fn parse<T: Into<SmolStr>>(token: Token, lexer: &mut Lexer, uri: T) -> Self {
11        let mut errors = Vec::new();
12
13        let block = Block::parse_with(token, lexer, &mut errors, None::<Token>);
14        let status = if errors.is_empty() {
15            AstStatus::Complete
16        } else {
17            AstStatus::HasErrors
18        };
19
20        Self {
21            uri: uri.into(),
22            block: block.unwrap_or_default(),
23            errors,
24            status,
25        }
26    }
27
28    /// Whether or not this [`Cst`] has errors.
29    #[inline]
30    pub fn has_errors(&self) -> bool {
31        //FIXME:
32        // Check this or `self.errors`? The result will be the same as long
33        // as the users don't edit the CST themselves.
34        self.status == AstStatus::HasErrors
35    }
36
37    /// Try printing the [`Cst`] back into source code.
38    ///
39    /// # Errors
40    ///
41    /// This'll only fail if [`Cst.has_errors()`](Self::has_errors()) returns `true`.
42    pub fn try_print(&self) -> Result<String, PrintingError> {
43        if self.has_errors() {
44            Err(PrintingError::ErroneousCst)
45        } else {
46            Ok(self.block.print())
47        }
48    }
49}