hemoglobin 0.14.0

Utilities for Bloodless
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#![warn(clippy::pedantic)]
//! Redcell is a markup language used to represent hemolymph card text.
//!
//! It is a subset of markdown. Hemolinks work as \[markdown\](links), and sagas are lists enumerated with plus signs (`+`).
//!
//! This module has a parser parses for Redcell into `RedellString`s, an AST that can be used in multiple contexts. Currently, Hemolymph uses them to show clickable Hemolinks. In the future, Redcell will also have markup that'll be used in cards' typst templates.

use serde::Deserialize;
use serde::Serialize;
use std::{
    error::Error,
    fmt::{Display, Write},
    ops::RangeInclusive,
};

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
/// An element of a `RichString`.
pub enum RedcellNode {
    String(String),
    /// A hemolink
    CardSearch {
        /// What is shown
        display: String,
        /// Query
        search: String,
    },
    Saga(Vec<RedcellString>),
    LineBreak,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
/// A vec of `RichElement`s.
pub struct RedcellString {
    pub elements: Vec<RedcellNode>,
}

impl RedcellString {
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }
    /// Convert to a raw, unformatted string.
    #[must_use]
    pub fn to_raw(&self) -> String {
        let mut result = String::new();

        for el in &self.elements {
            match el {
                RedcellNode::String(string) => result += string,
                RedcellNode::CardSearch { display, .. } => result += display,
                RedcellNode::Saga(rich_strings) => {
                    for el in rich_strings {
                        writeln!(&mut result, "+ {}", el.to_raw())
                            .expect("Write impl on strings is infallible.");
                    }
                }
                RedcellNode::LineBreak => result.push('\n'),
            }
        }

        result
    }
    /// Convert to redcell text.
    #[must_use]
    pub fn to_redcell(&self) -> String {
        let mut result = String::new();

        for el in &self.elements {
            match el {
                RedcellNode::String(string) => result += string,
                RedcellNode::CardSearch { display, search } => {
                    write!(&mut result, "[{display}]({search})")
                        .expect("Write impl on strings is infallible.");
                }
                RedcellNode::Saga(rich_strings) => {
                    for el in rich_strings {
                        // result += &format!("+ {}\n", el.to_redcell())
                        writeln!(&mut result, "+ {}", el.to_redcell())
                            .expect("Write impl on strings is infallible.");
                    }
                }
                RedcellNode::LineBreak => result.push('\n'),
            }
        }

        result
    }
}

#[derive(Debug)]
pub enum ParseErr {
    IncompleteHemolinkBody { starts_at: usize },
    IncompleteHemolinkLink { starts_at: usize },
    HemolinkMissingLink { range: RangeInclusive<usize> },
    EscapedWrong { escaped: Option<char> },
}

impl Display for ParseErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IncompleteHemolinkBody { starts_at } => {
                write!(f, "Hemolink body was ended prematurely at byte {starts_at}")
            }
            Self::IncompleteHemolinkLink { starts_at } => {
                write!(f, "Hemolink link was ended prematurely at byte {starts_at}")
            }
            Self::HemolinkMissingLink { range } => {
                write!(
                    f,
                    "Hemolink link was ended without a link at bytes {}..={}",
                    range.start(),
                    range.end()
                )
            }
            Self::EscapedWrong { escaped } => match escaped {
                Some(char) => write!(f, "Tried to escape a `{char:?}` character."),
                None => write!(f, "Expecting escaped character, but file ended."),
            },
        }
    }
}

impl Error for ParseErr {}

/// The state the parser, defining the things that are expected of the syntax.
#[derive(Default)]
enum ParserState {
    /// Just text. Ended by anything that would be understood as not-just-raw-text.
    #[default]
    String,
    /// The body of a Hemolink.
    HemolinkBody { starts_at: usize },
    /// We are waiting for a Hemolink's link.
    HemolinkAwaitLink {
        display: String,
        display_at: RangeInclusive<usize>,
    },
    /// The link of a Hemolink
    HemolinkLink { display: String, starts_at: usize },
}

/// The parser itself, defining a few things not directly related to the syntax nodes expected.
#[derive(Default)]
struct Parser {
    /// The main register contains the elements at the current level of nesting. If `in_saga_line` is false, we are not at the top level.
    main_reg: Vec<RedcellNode>,
    /// The side register contains the elements at the level of nesting above. If `in_saga_line` is true, this register contains the top level. If it is false, this is empty.
    side_reg: Vec<RedcellNode>,
    /// Escape the next character.
    escape: bool,
    /// Current string to be added to whatever we're currently parsing.
    current_string: String,

    /// Are we in a saga line? If this is true, `main_reg` contains the current nesting level and `side_reg` contains the top level. Otherwise, `main_reg` is the top level and this is empty.
    ///
    /// Normally we'd use a stack for nested structures, but since the nesting always has
    /// a depth of one I don't want to deal with stacking.
    in_saga_line: bool,

    /// What are we expecting to consume?
    state: ParserState,
}

impl Parser {
    /// Ends a line. This can mean that \n has been consumed, or that the end of the file has been reached properly (that is, in the Start state). To differentiate those two cases, `eof` is used. If it is false, it inserts a line break.
    fn end_line(mut self, eof: bool) -> Self {
        if !self.current_string.is_empty() {
            self.main_reg.push(RedcellNode::String(self.current_string));
            self.current_string = String::new();
        }

        if self.in_saga_line {
            // If we're in a saga line, that means string and saga_string have been swapped.
            // We swap them back se we can work with saga_string as the inner nesting level.
            std::mem::swap(&mut self.main_reg, &mut self.side_reg);
            self.in_saga_line = false;
            if let Some(RedcellNode::String(thing)) = self.side_reg.first_mut() {
                *thing = thing.trim_start().to_string();
            }
            if let Some(RedcellNode::Saga(ongoing)) = self.main_reg.last_mut() {
                ongoing.push(RedcellString {
                    elements: self.side_reg,
                });
            } else {
                self.main_reg.push(RedcellNode::Saga(vec![RedcellString {
                    elements: self.side_reg,
                }]));
            }
            self.side_reg = vec![];
        } else if !eof {
            self.main_reg.push(RedcellNode::LineBreak);
        }
        self
    }
}

/// Parse a string as Redcell into a `RichString`.
/// # Errors
/// If the string isn't correct Redcell.
#[allow(clippy::too_many_lines)]
pub fn parse(text: &str) -> Result<RedcellString, ParseErr> {
    let text = text.char_indices().filter(|(_, x)| *x != '\r');

    let mut parser = Parser::default();

    for (idx, char) in text {
        // FUCK this character and Windows.
        if char == '\r' {
            continue;
        }
        match parser.state {
            ParserState::String => match char {
                '[' if !parser.escape => {
                    if !parser.current_string.is_empty() {
                        parser
                            .main_reg
                            .push(RedcellNode::String(parser.current_string));
                        parser.current_string = String::new();
                    }
                    parser.state = ParserState::HemolinkBody { starts_at: idx };
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                '\n' => {
                    // If we're escaping this thing I'm going to assume you forgot something or just REALLY like typst.
                    if parser.escape {
                        return Err(ParseErr::EscapedWrong {
                            escaped: Some('\n'),
                        });
                    }

                    parser = parser.end_line(false);
                }
                // If we're at the beginning of a line and not already building a saga line,
                // a plus sign begins a saga line.
                '+' if !parser.escape && !parser.in_saga_line => {
                    if parser.current_string.trim().is_empty()
                        && parser.main_reg.last().is_none_or(|x| {
                            matches!(x, RedcellNode::LineBreak | RedcellNode::Saga(_))
                        })
                    {
                        // Line was already empty anyways, but it might have spaces.
                        parser.current_string = String::new();

                        // We nest to the lower level.
                        std::mem::swap(&mut parser.main_reg, &mut parser.side_reg);

                        parser.in_saga_line = true;
                    } else {
                        parser.current_string.push(char);
                        parser.escape = false;
                    }
                }
                _ => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
            ParserState::HemolinkBody { starts_at } => match char {
                ']' if !parser.escape => {
                    parser.state = ParserState::HemolinkAwaitLink {
                        display: parser.current_string,
                        display_at: starts_at..=idx,
                    };
                    parser.current_string = String::new();
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                _ => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
            ParserState::HemolinkAwaitLink { ref display, .. } => match char {
                '(' => {
                    parser.state = ParserState::HemolinkLink {
                        display: display.clone(),
                        starts_at: idx,
                    }
                }
                char if char.is_whitespace() => (),
                _ => (),
            },
            ParserState::HemolinkLink { ref display, .. } => match char {
                ')' if !parser.escape => {
                    parser.main_reg.push(RedcellNode::CardSearch {
                        display: display.clone(),
                        search: parser.current_string.trim().to_string(),
                    });
                    parser.current_string = String::new();
                    parser.state = ParserState::String;
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                char => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
        }
    }

    if parser.escape {
        return Err(ParseErr::EscapedWrong { escaped: None });
    }

    match parser.state {
        ParserState::String => parser = parser.end_line(true),
        ParserState::HemolinkBody { starts_at } => {
            return Err(ParseErr::IncompleteHemolinkBody { starts_at });
        }
        ParserState::HemolinkAwaitLink { display_at, .. } => {
            return Err(ParseErr::HemolinkMissingLink { range: display_at });
        }
        ParserState::HemolinkLink { starts_at, .. } => {
            return Err(ParseErr::IncompleteHemolinkLink { starts_at });
        }
    }

    Ok(RedcellString {
        elements: parser.main_reg,
    })
}

#[cfg(test)]
mod tests {
    //! # Structure of a test
    //! These tests consist of:
    //! - An input string that will be parsed. These must use exclusively Unix-style line breaks.
    //! - An expected output manually constructed in Rust.
    //!
    //! The input is parsed into redcell and we assert that the output is equal to the expected output.
    //! A second comparison is made, replacing all instances of `\n` in the input for `\n\r` and parsing that. We assert that the output is equal to the same expected output.
    //!
    //! Then, the expected output (which, at this point, we know is correct) is converted back into a string. We assert that it's equal to the original input string.
    //!
    //! # When to make a new test
    //! There are two situations when a test must be made:
    //! - A new feature is added.
    //! - A bug is found. If the bug is found through a bug report, the report should be linked as a doc comment on the test. This helps prevent regressions.

    use super::*;

    #[test]
    fn simple_line() {
        let input = "this is an example text.";
        let expected = RedcellString {
            elements: vec![RedcellNode::String(input.to_string())],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn multiline() {
        let input = "this is an example text.\nwith multiple lines.";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this is an example text.".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::String("with multiple lines.".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn hemolink() {
        let input = "this has a [hemolink](thing) in the middle";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a ".to_string()),
                RedcellNode::CardSearch {
                    display: "hemolink".to_string(),
                    search: "thing".to_string(),
                },
                RedcellNode::String(" in the middle".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn hemolink_in_newline() {
        let input = "this has a line.\nand a newline with a [hemolink](thing).";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a line.".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::String("and a newline with a ".to_string()),
                RedcellNode::CardSearch {
                    display: "hemolink".to_string(),
                    search: "thing".to_string(),
                },
                RedcellNode::String(".".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn saga() {
        let input = "this has a line\n+ and a saga\n+ with stuff\n";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a line".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::Saga(vec![
                    RedcellString {
                        elements: vec![RedcellNode::String("and a saga".to_string())],
                    },
                    RedcellString {
                        elements: vec![RedcellNode::String("with stuff".to_string())],
                    },
                ]),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }
}