use std::{fs, path::Path, sync::Arc};
use hemplate_parser::parse_template;
use tree_sitter::{Node, Range};
use crate::error::{BuildError, ExtractionError, ParseError};
mod interpolation_validation;
pub mod attribute;
pub mod element;
pub mod node;
pub mod tag;
pub mod text;
pub mod text_extractor;
pub mod value;
pub mod visitor;
pub mod whitespace;
pub use attribute::{
Attribute, AttributeName, Attributes, DynamicAttribute, RegularAttribute, TemplateDirective,
TemplateDirectiveName,
};
pub use element::{
Element, RawText, RegularElement, ScriptElement, SelfClosingElement, StyleElement, VoidElement,
};
pub use node::{Comment, DocType, Document, Entity, HemplateNode};
pub use tag::{StartTag, TagName};
pub use text::{
Interpolation, InterpolationExpression, RawInterpolation, Text, TextChunk, TextSegment,
};
pub use value::{AttributeValue, QuotedExpression};
pub use whitespace::WhitespaceSegment;
trait NodeKind {
fn node_kind() -> &'static str;
}
pub trait Extractable<S: AsRef<str>>: Sized {
fn extract(node: &Node, source: Arc<S>) -> Result<Option<Self>, ExtractionError>;
}
pub struct RangeNode<S: AsRef<str>, T> {
source: Arc<S>,
hemplate: T,
range: Range,
}
impl<S: AsRef<str>, T: Clone> Clone for RangeNode<S, T> {
fn clone(&self) -> Self {
RangeNode::new(self.source.clone(), self.hemplate.clone(), self.range)
}
}
impl<S: AsRef<str>, T> RangeNode<S, T> {
fn convert<Z: Clone>(&self, other: Z) -> RangeNode<S, Z> {
RangeNode::<S, Z>::new(self.source.clone(), other, self.range)
}
}
impl<S: AsRef<str> + std::fmt::Debug, T: std::fmt::Debug> std::fmt::Debug for RangeNode<S, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RangeNode")
.field("source", self.source.as_ref())
.field("hemplate", &self.hemplate)
.field("range", &self.range)
.finish()
}
}
impl<S: AsRef<str>, T> RangeNode<S, T> {
fn new(source: Arc<S>, hemplate: T, range: Range) -> Self {
Self {
source,
hemplate,
range,
}
}
pub fn hemplate(&self) -> &T {
&self.hemplate
}
}
impl<S: AsRef<str>, T: NodeKind> NodeKind for RangeNode<S, T> {
fn node_kind() -> &'static str {
T::node_kind()
}
}
impl<S: AsRef<str>, T> RangeNode<S, T> {
pub fn content(&self) -> &str {
let s = self.source.as_ref().as_ref();
&s[self.range.start_byte..self.range.end_byte]
}
pub fn range(&self) -> &Range {
&self.range
}
}
pub fn build_ast<S>(input: Arc<S>) -> Result<Option<RangeNode<S, Document<S>>>, BuildError>
where
S: AsRef<str> + Clone,
{
let tree = parse_template(input.as_ref(), None).ok_or_else(|| ParseError {
byte_offset: 0,
message: "parser returned None".to_string(),
})?;
let root = tree.root_node();
interpolation_validation::validate_interpolations(root, input.as_ref().as_ref())?;
Ok(RangeNode::<S, Document<S>>::extract(&root, input)?)
}
pub fn build_ast_from_file(path: &Path) -> Result<RangeNode<String, Document<String>>, BuildError> {
let source = fs::read_to_string(path)?;
build_ast(Arc::new(source))?.ok_or_else(|| {
BuildError::Extraction(ExtractionError {
node_kind: "document".to_string(),
message: format!("failed to extract document from {}", path.display()),
})
})
}