nml/src/elements/text.rs

88 lines
1.9 KiB
Rust
Raw Normal View History

2024-07-24 13:20:29 +02:00
use std::any::Any;
use std::ops::Range;
use std::rc::Rc;
2024-07-21 15:56:56 +02:00
2024-07-24 13:20:29 +02:00
use ariadne::Report;
use mlua::Function;
use mlua::Lua;
use crate::compiler::compiler::Compiler;
use crate::document::document::Document;
use crate::document::element::ElemKind;
use crate::document::element::Element;
use crate::lua::kernel::CTX;
2024-08-05 18:40:17 +02:00
use crate::parser::parser::ParserState;
2024-07-24 13:20:29 +02:00
use crate::parser::rule::Rule;
use crate::parser::source::Cursor;
use crate::parser::source::Source;
use crate::parser::source::Token;
2024-07-21 15:56:56 +02:00
#[derive(Debug)]
2024-07-24 13:20:29 +02:00
pub struct Text {
2024-08-01 14:23:41 +02:00
pub location: Token,
pub content: String,
2024-07-21 15:56:56 +02:00
}
2024-07-24 13:20:29 +02:00
impl Text {
pub fn new(location: Token, content: String) -> Text {
2024-07-21 15:56:56 +02:00
Text {
2024-07-24 13:20:29 +02:00
location: location,
content: content,
2024-07-21 15:56:56 +02:00
}
}
}
2024-07-24 13:20:29 +02:00
impl Element for Text {
fn location(&self) -> &Token { &self.location }
fn kind(&self) -> ElemKind { ElemKind::Inline }
2024-07-21 15:56:56 +02:00
fn element_name(&self) -> &'static str { "Text" }
2024-07-24 13:20:29 +02:00
fn compile(&self, compiler: &Compiler, _document: &dyn Document) -> Result<String, String> {
2024-07-29 16:45:14 +02:00
Ok(Compiler::sanitize(compiler.target(), self.content.as_str()))
2024-07-24 13:20:29 +02:00
}
2024-07-21 15:56:56 +02:00
}
#[derive(Default)]
pub struct TextRule;
2024-07-24 13:20:29 +02:00
impl Rule for TextRule {
fn name(&self) -> &'static str { "Text" }
2024-07-21 15:56:56 +02:00
2024-08-05 18:40:17 +02:00
fn next_match(&self, _state: &ParserState, _cursor: &Cursor) -> Option<(usize, Box<dyn Any>)> { None }
2024-07-21 15:56:56 +02:00
2024-07-24 13:20:29 +02:00
fn on_match(
&self,
2024-08-06 18:58:41 +02:00
_state: &ParserState,
2024-07-24 13:20:29 +02:00
_document: &dyn Document,
_cursor: Cursor,
2024-08-06 18:58:41 +02:00
_match_data: Box<dyn Any>,
2024-07-24 13:20:29 +02:00
) -> (Cursor, Vec<Report<'_, (Rc<dyn Source>, Range<usize>)>>) {
panic!("Text cannot match");
}
2024-07-21 15:56:56 +02:00
2024-08-05 18:40:17 +02:00
fn register_bindings<'lua>(&self, lua: &'lua Lua) -> Vec<(String, Function<'lua>)> {
2024-07-21 15:56:56 +02:00
let mut bindings = vec![];
2024-07-24 13:20:29 +02:00
bindings.push((
"push".to_string(),
lua.create_function(|_, content: String| {
CTX.with_borrow(|ctx| {
ctx.as_ref().map(|ctx| {
2024-08-06 18:58:41 +02:00
ctx.state.push(
2024-07-24 13:20:29 +02:00
ctx.document,
Box::new(Text {
location: ctx.location.clone(),
content,
}),
);
})
});
Ok(())
})
.unwrap(),
));
2024-08-05 18:40:17 +02:00
bindings
2024-07-24 13:20:29 +02:00
}
2024-07-21 15:56:56 +02:00
}