1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
use std::collections::HashMap;

use crate::arena::{Arena, ArenaId};
use crate::system::LSystem;
use crate::token::{Token, TokenType};

#[derive(Debug, Clone)]
struct TransformationRule {
    predecessor: ArenaId,
    successor: Vec<ArenaId>,
}

impl TransformationRule {
    pub fn new(predecessor: ArenaId, successor: Vec<ArenaId>) -> Self {
        Self {
            predecessor,
            successor,
        }
    }
}

#[derive(Default, Clone)]
pub struct LSystemBuilder {
    arena: Arena<Token>,
    axiom: Option<Vec<ArenaId>>,
    rules: Vec<TransformationRule>,
}

impl LSystemBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new token.
    ///
    /// Returns a TokenId which can be used (in this LSystem) to refer to the registered token.
    pub fn token<S: Into<String>>(&mut self, name: S, token_type: TokenType) -> ArenaId {
        let token = Token::new(name.into(), token_type);

        self.arena.push(token)
    }

    /// Register a new transformation rule in this LSystem.
    ///
    /// If any of the provided TokenId are invalid, this function will panic.
    pub fn transformation_rule(&mut self, predecessor: ArenaId, successor: Vec<ArenaId>) {
        // Verify that the TokenId corresponds to a token in this LSystem
        if !self.arena.is_valid(predecessor) || !self.arena.is_valid_slice(&successor) {
            panic!("Invalid token id provided to Lsystem::transformation_rule");
        }

        // Add the rule to this system
        self.rules
            .push(TransformationRule::new(predecessor, successor));
    }

    /// Set the axiom for this LSystem.
    pub fn axiom(&mut self, axiom: Vec<ArenaId>) {
        self.axiom = Some(axiom);
    }

    /// Consumes the builder, returning an LSystem instance.
    ///
    /// This function will panic if you have not set an axiom before proceeding.
    pub fn finish(self) -> LSystem {
        let axiom = self.axiom.expect("finish called before axiom set");

        // Construct a HashMap associating each variable with its corresponding transformation rule
        let mut rules_map = HashMap::new();

        for rule in self.rules.into_iter() {
            rules_map.insert(rule.predecessor, rule.successor);
        }

        // We also add constant production rules of the form P => P.
        for (id, token) in self.arena.enumerate() {
            if token.is_constant() {
                rules_map.insert(id, vec![id]);
            }
        }

        // If we set our system up correctly, it should be that each token
        // contributes exactly one rule, so we check for that here.
        assert_eq!(self.arena.len(), rules_map.len());

        LSystem::new(self.arena, axiom, rules_map)
    }
}

#[macro_export]
macro_rules! variable {
    ( $x:expr, $y:expr ) => {
        $x.token($y, $crate::TokenType::Variable)
    };
}

#[macro_export]
macro_rules! constant {
    ( $x:expr, $y:expr ) => {
        $x.token($y, $crate::TokenType::Constant)
    };
}

fn build_rules_string(rules: &[TransformationRule], arena: &Arena<Token>) -> String {
    let mut st = Vec::new();

    for rule in rules {
        st.push(format!(
            "{} => {}",
            arena.render(&[rule.predecessor]),
            arena.render(&rule.successor)
        ));
    }

    st.join(",")
}

impl std::fmt::Debug for LSystemBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.debug_struct("LSystemBuilder")
            .field("arena", &self.arena)
            .field("axiom", &self.axiom)
            .field("rules", &build_rules_string(&self.rules, &self.arena))
            .finish()
    }
}