murkdown 0.1.1

An experimental semantic markup language and static site generator for composing and decomposing hypertext documents
Documentation
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::sync::OnceLock;
use std::{borrow::Cow, collections::HashSet, sync::Arc};

use htmlize::escape_text;
use itertools::Itertools;
use regex::Regex;

use super::{
    rule::{self, Context, LangInstr, LangRule, LangSettings},
    rule_argument::Arg,
};
use crate::{
    ast::Node,
    types::{Dependency, ExecArtifact, LibError, RuleMap},
};

#[derive(Debug, Clone)]
pub struct Lang {
    pub name: String,
    pub media_type: String,
    pub(crate) rules: RuleMap,
}

static VARIABLE_RE: OnceLock<Regex> = OnceLock::new();

/// A set of compiler rules
impl Lang {
    pub fn new(input: &str) -> Result<Lang, LibError> {
        let (name, media_type, rules) = rule::parse(input)?;

        Ok(Lang { name, rules, media_type })
    }

    #[cfg(test)]
    pub fn markdown() -> Self {
        Self::new(include_str!("../../lib/compiler/markdown.lang"))
            .expect("builtin markdown to work")
    }

    /// Get rules for an AST path
    pub(crate) fn get_rules(
        &self,
        stage: &'static str,
        path: &str,
    ) -> impl Iterator<Item = &LangRule> {
        let rules = self.rules.get(stage);
        let path = path.to_string();
        rules
            .unwrap()
            .iter()
            .filter(move |r| r.matches(&path))
            .take_while_inclusive(|&v| v.settings.is_composable)
    }

    /// Get instructions for an AST path
    #[cfg(test)]
    pub(crate) fn get_instructions(
        &self,
        stage: &'static str,
        path: &str,
    ) -> (impl Iterator<Item = &LangInstr>, LangSettings) {
        let rules = self.rules.get(stage);
        match rules.unwrap().iter().find(|r| r.matches(path)) {
            Some(rule) => (rule.instructions.iter(), rule.settings),
            None => ((&[] as &[LangInstr]).iter(), LangSettings::default()),
        }
    }

    /// Evaluate instructions to apply mutations and produce output
    pub(crate) fn evaluate<'a, 'b, 'c>(
        &self,
        instructions: &'b mut impl Iterator<Item = &'a LangInstr>,
        ctx: &'b mut Context<'a>,
        deps: &mut HashSet<Dependency>,
        node: &'c mut Node,
        set: &LangSettings,
    ) -> Result<String, LibError> {
        let mut out = String::new();
        for inst in instructions {
            use Arg::*;
            match (inst.op.as_str(), inst.args.as_slice()) {
                ("DRAIN", [StackRef(stack)]) => {
                    if let Some(stack) = ctx.stacks.get_mut(stack.as_str()) {
                        stack.clear();
                    }
                }
                ("EXEC", [Str(cmd), destination @ (MediaType(_) | File(_)), URIPath(id)]) => {
                    let cmd = replace(cmd, ctx, &*node, set).to_string();
                    let id = replace(id, ctx, &*node, set).to_string();
                    let artifact = match destination {
                        MediaType(t) => {
                            ExecArtifact::Stdout(replace(t, ctx, &*node, set).to_string())
                        }
                        File(p) => ExecArtifact::Path(replace(p, ctx, &*node, set).as_ref().into()),
                        _ => unreachable!(),
                    };
                    let input = node.children.as_ref().map(|children| {
                        children
                            .iter()
                            .filter_map(|n| n.value.clone())
                            .map(|v| v.replace("\n", r"\n"))
                            .collect::<Vec<_>>()
                            .join("\n")
                    });
                    deps.insert(Dependency::Exec { cmd, input, id, artifact });
                }
                ("POP", [StackRef(stack)]) => {
                    if let Some(stack) = ctx.stacks.get_mut(stack.as_str()) {
                        stack.pop();
                    }
                }
                ("POP", [PropRef(prop)]) => {
                    if let Some(props) = node.props.as_mut() {
                        if let Some(idx) = props.iter().position(|(k, _)| **k == *prop) {
                            props.remove(idx);
                        }
                    }
                }
                ("PUSH", [StackRef(target), Str(value)])
                    if ["src", "ref"].contains(&target.as_str()) =>
                {
                    let value = replace(value, ctx, &*node, set);
                    ctx.stacks
                        .entry(Arc::from(target.as_str()))
                        .or_default()
                        .push(value.clone());
                    node.add_prop(target.as_str(), Arc::from(value));
                }
                ("PUSH", [StackRef(target), Str(value)]) => {
                    let value = replace(value, ctx, &*node, set);
                    ctx.stacks
                        .entry(Arc::from(target.as_str()))
                        .or_default()
                        .push(value);
                }
                ("PUSH", [StackRef(target), StackRef(source)]) => {
                    let value = ctx
                        .stacks
                        .get(source.as_str())
                        .and_then(|v| v.last().cloned());
                    if let Some(value) = value {
                        ctx.stacks
                            .raw_entry_mut()
                            .from_key(target.as_str())
                            .or_insert(Arc::from(target.as_str()), vec![])
                            .1
                            .push(value);
                    }
                }
                ("PUSH", [StackRef(target), PropRef(prop)]) => {
                    if let Some(value) = node.find_prop(prop) {
                        ctx.stacks
                            .raw_entry_mut()
                            .from_key(target.as_str())
                            .or_insert(Arc::from(target.as_str()), vec![])
                            .1
                            .push(value.to_string().into());
                    }
                }
                ("SET", [StackRef(target), Str(value)]) => {
                    let value = replace(value, ctx, node, set);
                    let v = ctx
                        .stacks
                        .raw_entry_mut()
                        .from_key(target.as_str())
                        .or_insert(Arc::from(target.as_str()), vec![])
                        .1;
                    v.pop();
                    v.push(Cow::Owned(value.to_string()));
                }
                ("SWAP", [StackRef(target), StackRef(source)]) => {
                    let source_value = ctx.stacks.remove(source.as_str());
                    let target_value = match source_value {
                        Some(v) => ctx.stacks.insert(target.as_str().into(), v),
                        None => None,
                    };
                    match target_value {
                        Some(v) => ctx.stacks.insert(source.as_str().into(), v),
                        None => None,
                    };
                }
                ("WRITE", [StackRef(stack)]) => {
                    let stack = ctx.stacks.get(stack.as_str());
                    if let Some(value) = stack.and_then(|v| v.last()) {
                        out.push_str(value);
                    }
                }
                ("WRITE", [Str(value)]) => out.push_str(&replace(value, ctx, node, set)),
                ("WRITEALL", [StackRef(stack)]) => {
                    let stack = ctx.stacks.get(stack.as_str());
                    if let Some(stack) = stack {
                        stack.iter().for_each(|v| out.push_str(v));
                    }
                }
                ("YIELD", _) => {
                    break;
                }
                ("NOOP", _) => {}
                _ => return Err(LibError::invalid_rule(inst.to_string())),
            }
        }
        Ok(out)
    }
}

fn replace<'a>(
    template: &'a str,
    ctx: &mut Context,
    node: &Node,
    settings: &LangSettings,
) -> Cow<'a, str> {
    // template without substititions
    if !template.contains(r"\") && !template.contains("$") {
        return Cow::Borrowed(template);
    }

    let value = match settings.is_unescaped_value {
        true => node.value.as_deref().map(Cow::Borrowed),
        false => node.value.as_deref().map(escape_text).to_owned(),
    };

    // escapes
    let mut result = template.replace(r#"\""#, "\"").replace(r"\n", "\n");

    // variables from props
    if template.contains("$") {
        for (key, value) in node.props.iter().flatten() {
            result = result.replace(&["$", key].concat(), value);
        }
    }

    // variables from stacks with modifiers
    if result.contains("$") && result.contains(":") {
        for (key, stack) in ctx.stacks.iter() {
            result = result.replace(&["$", key, ":j"].concat(), &stack.join(" "));
        }
    }

    // variables from stacks
    if result.contains("$") {
        for (key, stack) in ctx.stacks.iter() {
            if let Some(last) = stack.last() {
                result = result.replace(&["$", key].concat(), last);
            }
        }
    }

    // unset variables
    if result.contains("$") {
        let re = VARIABLE_RE.get_or_init(|| Regex::new(r"\$(\w+)(?::([j]))?").unwrap());
        result = re.replace(&result, "").to_string();
    }

    // builtin
    result = result
        .replace(r"\r", &ctx.rng.sample_string())
        .replace(r"\v", value.as_deref().unwrap_or_default())
        .replace(r"\i", &ctx.index.to_string())
        .replace(r"\V", ctx.parent_value.as_deref().unwrap_or_default())
        .replace(r"\m", node.marker.as_deref().unwrap_or_default());

    if result.contains(r"\h") {
        let headers = node.headers.as_ref();
        result = result.replace(r"\h:j", &headers.map(|h| h.join(" ")).unwrap_or_default());
    }
    if result.contains(r"\H") {
        let headers = ctx.parent_headers.as_ref();
        result = result.replace(r"\H:j", &headers.map(|h| h.join(" ")).unwrap_or_default());
    }

    Cow::Owned(result)
}

#[cfg(test)]
mod tests {
    use indoc::indoc;

    use super::*;
    use crate::ast::NodeBuilder;

    #[test]
    fn test_get_instructions() {
        let input = indoc! {
            r#"
            RULES FOR test PRODUCE text/plain
            PREPROCESS RULES:
            [SEC...]$
              IS PARAGRAPHABLE
              NOOP
            "#
        };
        let lang = Lang::new(input).unwrap();

        let (instructions, settings) = lang.get_instructions("PREPROCESS", "[SEC]");
        let instructions = instructions.collect::<Vec<&LangInstr>>();
        assert_eq!(
            instructions,
            vec![&LangInstr { op: "NOOP".into(), args: vec![] }]
        );
        assert!(settings.is_paragraphable);
    }

    #[test]
    fn test_get_rules() {
        let input = indoc! {
            r#"
            RULES FOR test PRODUCE text/plain
            PREPROCESS RULES:
            [FOO] [SEC...]$
              IS COMPOSABLE
              NOOP
            [SEC...]$
              NOOP
            "#
        };
        let lang = Lang::new(input).unwrap();

        let rules = lang.get_rules("PREPROCESS", "[FOO] [SEC]");
        assert_eq!(rules.count(), 2);
    }

    #[test]
    fn test_evaluate() {
        let input = indoc! {
            r#"
            RULES FOR test PRODUCE text/plain
            COMPILE RULES:
            [rule]
              PUSH foo "hello"
              PUSH indent foo
              PUSH indent "world"
              WRITE "ok"
            "#
        };
        let mut deps = HashSet::new();
        let lang = Lang::new(input).unwrap();
        let mut node = Node::default();

        let (mut instructions, settings) = lang.get_instructions("COMPILE", "[rule]");
        let mut ctx = Context::default();

        let value = lang
            .evaluate(&mut instructions, &mut ctx, &mut deps, &mut node, &settings)
            .unwrap();
        assert_eq!(ctx.stacks.get("indent").unwrap(), &["hello", "world"]);
        assert_eq!(value, "ok");
    }

    #[test]
    fn test_evaluate_props() {
        let input = indoc! {
            r#"
            RULES FOR test PRODUCE text/plain
            COMPILE RULES:
            [rule]
              WRITE "$word "
              POP PROP word
              WRITE "$word"
            "#
        };
        let mut deps = HashSet::new();
        let lang = Lang::new(input).unwrap();
        let mut node = NodeBuilder::root()
            .add_prop(("word".into(), "hello".into()))
            .add_prop(("word".into(), "world".into()))
            .done();

        let (mut instructions, settings) = lang.get_instructions("COMPILE", "[rule]");
        let mut ctx = Context::default();

        let value = lang
            .evaluate(&mut instructions, &mut ctx, &mut deps, &mut node, &settings)
            .unwrap();
        assert_eq!(value, "hello world");
    }

    #[test]
    fn test_evaluate_misc() {
        let input = indoc! {
            r#"
            RULES FOR test PRODUCE text/plain
            COMPILE RULES:
            [rule]
              WRITE "$var\n"
              WRITE "$var:j\n"
              WRITE "\v and \V"
            "#
        };
        let mut deps = HashSet::new();
        let lang = Lang::new(input).unwrap();
        let mut node = Node::default();
        node.value = Some("value".into());

        let (mut instructions, settings) = lang.get_instructions("COMPILE", "[rule]");
        let mut ctx = Context::default();
        ctx.parent_value = Some("parent value".into());
        ctx.stacks
            .entry(Arc::from("var"))
            .or_default()
            .extend(["foo".into(), "bar".into()]);

        let value = lang
            .evaluate(&mut instructions, &mut ctx, &mut deps, &mut node, &settings)
            .unwrap();
        assert_eq!(value, "bar\nfoo bar\nvalue and parent value");
    }
}