render_regex 0.0.0

SVG visualization of regex DFAs.
Documentation
pub mod graph;
pub mod layout;
pub mod plan;
pub mod stage;
pub mod intent;
pub mod render;

use rusty_regex::parser::parse;
use rusty_regex::nfa::compile_ast_to_nfa;
use rusty_regex::dfa::compile_nfa_to_dfa;
use crate::graph::VisualGraph;
use crate::layout::strategies::LayoutStrategy;
use crate::plan::IntentBuilder;
use crate::render::svg::to_svg;

pub enum Stage {
    Ast,
    Nfa,
    Dfa,
}

#[derive(Debug)]
pub enum RenderError {
    Parse(String),
    Compile(String),
}

use std::fmt;
impl fmt::Display for RenderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RenderError::Parse(msg) => write!(f, "Parse error: {}", msg),
            RenderError::Compile(msg) => write!(f, "Compile error: {}", msg),
        }
    }
}
impl std::error::Error for RenderError {}

pub fn render_regex_svg(
    stage: Stage,
    regex: &str,
    _layout: Option<LayoutStrategy>,
    profile: &crate::layout::profile::RenderProfile,
) -> Result<svg::Document, RenderError> {
    let ast = parse(regex).map_err(|e| RenderError::Parse(format!("{:?}", e)))?;

    let graph: VisualGraph = match stage {
        Stage::Ast => crate::stage::ast::ast_to_graph(&ast),
        Stage::Nfa => {
            let nfa = compile_ast_to_nfa(&ast).map_err(|e| RenderError::Compile(format!("{:?}", e)))?;
            crate::stage::nfa::nfa_to_graph(&nfa)
        }
        Stage::Dfa => {
            let nfa = compile_ast_to_nfa(&ast).map_err(|e| RenderError::Compile(format!("{:?}", e)))?;
            let dfa = compile_nfa_to_dfa(&nfa).map_err(|e| RenderError::Compile(format!("{:?}", e)))?;
            crate::stage::dfa::dfa_to_graph(&dfa)
        }
    };

    let intent = IntentBuilder::from_graph(&graph, profile);
    Ok(to_svg(&intent, profile))
}