clml-proc-macro 0.2.0

Implementation for the package clml
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! This module permits to determine which ANSI sequences have to be added at a given position in
//! the format string, by saving the current tags in a "context". When a new tag is encountered, a
//! diff between the old state and the new state is performed to determine the right ANSI sequences
//! to add.

use proc_macro2::Span;

use crate::error::{Error, SpanError};

/// Stores all the current open tags encountered in the format string.
#[derive(Debug, PartialEq, Default)]
pub struct Context<'a>(Vec<ColorTag<'a>>);

impl<'a> Context<'a> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Applies a group of tags to the current context, and returns the ANSI sequences to be added
    /// into the format string.
    ///
    /// For each given tag:
    ///  - if the tag is an open tag, push it into the context;
    ///  - if it's a valid close tag, pop the last open tag.
    pub fn ansi_apply_tags(&mut self, tag_group: Vec<ColorTag<'a>>) -> Result<String, SpanError> {
        let state_diff = self.apply_tags_and_get_diff(tag_group)?;
        Ok(state_diff.ansi_string())
    }

    /// Applies a group of tags to the current context, with no return on success. Used by the macro
    /// `untagged!()`.
    ///
    /// For each given tag:
    ///  - if the tag is an open tag, push it into the context;
    ///  - if it's a valid close tag, pop the last open tag.
    pub fn apply_tags(&mut self, tag_group: Vec<ColorTag<'a>>) -> Result<(), SpanError> {
        self.apply_tags_and_get_diff(tag_group).map(|_| ())
    }

    /// Returns the actual color/style state, which is the result of the changes made by each tag
    /// sequentially.
    pub fn state(&self) -> State {
        let mut state = State::default();
        for tag in &self.0 {
            if let Some(ref color) = tag.change_set.foreground {
                state.foreground = ExtColor::Color(color.clone());
            }
            if let Some(ref color) = tag.change_set.background {
                state.background = ExtColor::Color(color.clone());
            }
            state.bold |= tag.change_set.bold;
            state.dim |= tag.change_set.dim;
            state.underline |= tag.change_set.underline;
            state.italics |= tag.change_set.italics;
            state.blink |= tag.change_set.blink;
            state.strike |= tag.change_set.strike;
            state.reverse |= tag.change_set.reverse;
            state.conceal |= tag.change_set.conceal;
            if let Some(ref url) = tag.change_set.link {
                state.link = Some(url.clone());
            }
        }
        state
    }

    /// Common code between [`Self::ansi_apply_tags()`] and [`Self::apply_tags()`].
    fn apply_tags_and_get_diff(&mut self, tags: Vec<ColorTag<'a>>) -> Result<StateDiff, SpanError> {
        let old_state = self.state();

        for tag in tags {
            if tag.is_close {
                let last_tag = self
                    .0
                    .last()
                    .ok_or_else(|| SpanError::new(Error::NoTagToClose, tag.span))?;
                // If the tag is "void" (it is a "</>" tag), we don't need to check if the change
                // sets are matching:
                if !tag.change_set.is_void() && last_tag.change_set != tag.change_set {
                    let (last_src, src) = (
                        // We can unwrap the last tag source, because we know that all the tags
                        // stored inside the context are *open tags*, and open tag are always taken
                        // from the source input:
                        last_tag.source.unwrap(),
                        // We can unwrap the source of the tag currently being processed, because
                        // we just checked above that the tag is not void,
                        // and non-void tags are always taken from the
                        // source input:
                        tag.source.unwrap(),
                    );
                    return Err(SpanError::new(
                        Error::MismatchCloseTag(last_src.to_owned(), src.to_owned()),
                        tag.span,
                    ));
                }
                self.0.pop().unwrap();
            } else {
                self.0.push(tag);
            }
        }

        let new_state = self.state();
        Ok(StateDiff::from_diff(&old_state, &new_state))
    }
}

/// Describes the state of each color and style attributes at a given position in the format string.
/// Two states can be compared together by creating a [`StateDiff`] instance.
#[derive(Debug, PartialEq, Default)]
pub struct State {
    foreground: ExtColor,
    background: ExtColor,
    bold: bool,
    dim: bool,
    underline: bool,
    italics: bool,
    blink: bool,
    strike: bool,
    reverse: bool,
    conceal: bool,
    link: Option<String>,
}

/// The result of the comparison between two [`State`]s.
///
/// Each field is an [`Action`], which indicates if the given value has to be changed or left
/// unchanged in order to reach the new state.
#[derive(Debug)]
pub struct StateDiff {
    foreground: Action<ExtColor>,
    background: Action<ExtColor>,
    bold: Action<bool>,
    dim: Action<bool>,
    underline: Action<bool>,
    italics: Action<bool>,
    blink: Action<bool>,
    strike: Action<bool>,
    reverse: Action<bool>,
    conceal: Action<bool>,
    link: Action<Option<String>>,
}

impl StateDiff {
    /// Creates a new [`StateDiff`] by comparing two [`State`]s.
    pub fn from_diff(old: &State, new: &State) -> Self {
        StateDiff {
            foreground: Action::from_diff(
                Some(old.foreground.clone()),
                Some(new.foreground.clone()),
            ),
            background: Action::from_diff(
                Some(old.background.clone()),
                Some(new.background.clone()),
            ),
            bold: Action::from_diff(Some(old.bold), Some(new.bold)),
            dim: Action::from_diff(Some(old.dim), Some(new.dim)),
            underline: Action::from_diff(Some(old.underline), Some(new.underline)),
            italics: Action::from_diff(Some(old.italics), Some(new.italics)),
            blink: Action::from_diff(Some(old.blink), Some(new.blink)),
            strike: Action::from_diff(Some(old.strike), Some(new.strike)),
            reverse: Action::from_diff(Some(old.reverse), Some(new.reverse)),
            conceal: Action::from_diff(Some(old.conceal), Some(new.conceal)),
            link: Action::from_diff(Some(old.link.clone()), Some(new.link.clone())),
        }
    }

    /// Returns the ANSI sequence(s) which has to added to the format string in order to reach the
    /// new state.
    pub fn ansi_string(&self) -> String {
        use crate::ansi_constants::*;

        let mut output = String::new();

        macro_rules! push_code {
            ($($codes:expr),*) => { output.push_str(&generate_ansi_code(&[$($codes),*])) };
        }

        if let Action::Change(ref ext_color) = self.foreground {
            match ext_color {
                ExtColor::Normal => push_code!(DEFAULT_FOREGROUND),
                ExtColor::Color(Color::Color16(color)) => match color.intensity {
                    Intensity::Normal => {
                        push_code!(SET_FOREGROUND_BASE + color.base_color.index())
                    },
                    Intensity::Bright => {
                        push_code!(SET_BRIGHT_FOREGROUND_BASE + color.base_color.index())
                    },
                },
                ExtColor::Color(Color::Color256(color)) => {
                    push_code!(SET_FOREGROUND, 5, color.0);
                },
                ExtColor::Color(Color::ColorRgb(color)) => {
                    push_code!(SET_FOREGROUND, 2, color.r, color.g, color.b);
                },
            }
        }

        if let Action::Change(ref ext_color) = self.background {
            match ext_color {
                ExtColor::Normal => push_code!(DEFAULT_BACKGROUND),
                ExtColor::Color(Color::Color16(color)) => match color.intensity {
                    Intensity::Normal => {
                        push_code!(SET_BACKGROUND_BASE + color.base_color.index())
                    },
                    Intensity::Bright => {
                        push_code!(SET_BRIGHT_BACKGROUND_BASE + color.base_color.index())
                    },
                },
                ExtColor::Color(Color::Color256(color)) => {
                    push_code!(SET_BACKGROUND, 5, color.0);
                },
                ExtColor::Color(Color::ColorRgb(color)) => {
                    push_code!(SET_BACKGROUND, 2, color.r, color.g, color.b);
                },
            }
        }

        macro_rules! handle_attr {
            ($attr:expr, $true_val:expr, $false_val:expr) => {
                match $attr {
                    Action::Change(true) => push_code!($true_val),
                    Action::Change(false) => push_code!($false_val),
                    _ => (),
                }
            };
        }

        handle_attr!(self.bold, BOLD, NO_BOLD);
        handle_attr!(self.dim, DIM, NO_BOLD);
        handle_attr!(self.underline, UNDERLINE, NO_UNDERLINE);
        handle_attr!(self.italics, ITALIC, NO_ITALIC);
        handle_attr!(self.blink, BLINK, NO_BLINK);
        handle_attr!(self.strike, STRIKE, NO_STRIKE);
        handle_attr!(self.reverse, REVERSE, NO_REVERSE);
        handle_attr!(self.conceal, CONCEAL, NO_CONCEAL);

        // Hyperlinks use the OSC 8 sequence, not SGR, so they're handled separately from
        // `push_code!` above. An empty URL is how OSC 8 closes a previously opened link.
        if let Action::Change(ref link) = self.link {
            let url = link.as_deref().unwrap_or("");
            output.push_str(&generate_osc8_link(url));
        }

        output
    }
}

/// The action to be performed on a given color/style attribute in order to reach a new state.
#[derive(Debug, PartialEq)]
pub enum Action<T> {
    /// Nothing has to be done, because this value was never modified.
    None,
    /// This attribute has to be kept the same. The value is tracked even so, because reaching a new
    /// state may require resetting and reapplying it.
    Keep(T),
    /// This attribute value has to be changed.
    Change(T),
}

impl<T> Action<T>
where
    T: PartialEq,
{
    /// Creates a new [`Action`].
    pub fn from_diff(old: Option<T>, new: Option<T>) -> Self {
        let eq = old == new;
        match (old, new, eq) {
            (Some(old_val), Some(_), true) | (Some(old_val), None, _) => Action::Keep(old_val),
            (_, Some(new_val), _) => Action::Change(new_val),
            _ => Action::None,
        }
    }
}

/// A parsed color/style tag.
#[derive(Debug, Default)]
pub struct ColorTag<'a> {
    /// Source of the tag in the format string.
    pub source: Option<&'a str>,
    /// Span of the tag in the format string.
    pub span: Option<Span>,
    /// Is it a close tag like `</red>`.
    pub is_close: bool,
    /// The changes that are implied by this tag.
    pub change_set: ChangeSet,
}

impl PartialEq for ColorTag<'_> {
    fn eq(&self, other: &Self) -> bool {
        and!(
            self.source == other.source,
            self.is_close == other.is_close,
            self.change_set == other.change_set,
        )
    }
}

impl<'a> ColorTag<'a> {
    /// Creates a new close tag; only used in order to auto-close unclosed tags at the end of the
    /// format string.
    pub fn new_close() -> Self {
        ColorTag {
            source: None,
            span: None,
            is_close: true,
            change_set: ChangeSet::default(),
        }
    }

    /// Sets the span of the tag.
    pub fn set_span(&mut self, span: Span) {
        self.span = Some(span);
    }
}

/// The changes that are implied by a tag.
#[derive(Debug, PartialEq, Default)]
pub struct ChangeSet {
    /// If it is `Some`, then the foreground color has to be changed.
    pub foreground: Option<Color>,
    /// If it is `Some`, then the background color has to be changed.
    pub background: Option<Color>,
    /// If it is `true`, then the bold attribute has to be set (or unset for a close tag).
    pub bold: bool,
    /// If it is `true`, then the dim attribute has to be set (or unset for a close tag).
    pub dim: bool,
    /// If it is `true`, then the underline attribute has to be set (or unset for a close tag).
    pub underline: bool,
    /// If it is `true`, then the italics attribute has to be set (or unset for a close tag).
    pub italics: bool,
    /// If it is `true`, then the blink attribute has to be set (or unset for a close tag).
    pub blink: bool,
    /// If it is `true`, then the strike attribute has to be set (or unset for a close tag).
    pub strike: bool,
    /// If it is `true`, then the reverse attribute has to be set (or unset for a close tag).
    pub reverse: bool,
    /// If it is `true`, then the conceal attribute has to be set (or unset for a close tag).
    pub conceal: bool,
    /// If it is `Some`, then the hyperlink target has to be changed.
    pub link: Option<String>,
}

impl ChangeSet {
    /// Checks if there is nothing to change (used to detect the `</>` tag).
    pub fn is_void(&self) -> bool {
        and!(
            self.foreground.is_none(),
            self.background.is_none(),
            !self.bold,
            !self.dim,
            !self.underline,
            !self.italics,
            !self.blink,
            !self.strike,
            !self.reverse,
            !self.conceal,
            self.link.is_none(),
        )
    }
}

impl From<&[Change]> for ChangeSet {
    fn from(changes: &[Change]) -> ChangeSet {
        let mut change_set = ChangeSet::default();
        for change in changes {
            match change {
                Change::Foreground(color) => change_set.foreground = Some(color.clone()),
                Change::Background(color) => change_set.background = Some(color.clone()),
                Change::Bold => change_set.bold = true,
                Change::Dim => change_set.dim = true,
                Change::Underline => change_set.underline = true,
                Change::Italics => change_set.italics = true,
                Change::Blink => change_set.blink = true,
                Change::Strike => change_set.strike = true,
                Change::Reverse => change_set.reverse = true,
                Change::Conceal => change_set.conceal = true,
                Change::Link(url) => change_set.link = Some(url.clone()),
            }
        }
        change_set
    }
}

/// A single change to be done inside a tag. Tags with multiple keywords like `<red;bold>` will have
/// multiple [`Change`]s.
#[derive(Debug, PartialEq, Clone)]
pub enum Change {
    Foreground(Color),
    Background(Color),
    Bold,
    Dim,
    Underline,
    Italics,
    Blink,
    Strike,
    Reverse,
    Conceal,
    Link(String),
}

impl TryFrom<&str> for Change {
    type Error = ();

    /// Tries to convert a keyword like `red`, `bold` into a [`Change`] instance.
    #[rustfmt::skip]
    fn try_from(input: &str) -> Result<Self, Self::Error> {
        macro_rules! color16 {
            ($kind:ident $intensity:ident $base_color:ident) => {
                Change::$kind(Color::Color16(Color16::new(
                    BaseColor::$base_color,
                    Intensity::$intensity,
                )))
            };
        }

        let change = match input {
            "s" | "strong" | "bold" | "em" => Change::Bold,
            "dim" => Change::Dim,
            "u" | "underline" => Change::Underline,
            "i" | "italic" | "italics" => Change::Italics,
            "blink" => Change::Blink,
            "strike" => Change::Strike,
            "reverse" | "rev" => Change::Reverse,
            "conceal" | "hide" => Change::Conceal,

            "k" | "black"   => color16!(Foreground Normal Black),
            "r" | "red"     => color16!(Foreground Normal Red),
            "g" | "green"   => color16!(Foreground Normal Green),
            "y" | "yellow"  => color16!(Foreground Normal Yellow),
            "b" | "blue"    => color16!(Foreground Normal Blue),
            "m" | "magenta" => color16!(Foreground Normal Magenta),
            "c" | "cyan"    => color16!(Foreground Normal Cyan),
            "w" | "white"   => color16!(Foreground Normal White),

            "k!" | "black!" | "bright-black"     => color16!(Foreground Bright Black),
            "r!" | "red!" | "bright-red"         => color16!(Foreground Bright Red),
            "g!" | "green!" | "bright-green"     => color16!(Foreground Bright Green),
            "y!" | "yellow!" | "bright-yellow"   => color16!(Foreground Bright Yellow),
            "b!" | "blue!" | "bright-blue"       => color16!(Foreground Bright Blue),
            "m!" | "magenta!" | "bright-magenta" => color16!(Foreground Bright Magenta),
            "c!" | "cyan!" | "bright-cyan"       => color16!(Foreground Bright Cyan),
            "w!" | "white!" | "bright-white"     => color16!(Foreground Bright White),

            "K" | "bg-black"   => color16!(Background Normal Black),
            "R" | "bg-red"     => color16!(Background Normal Red),
            "G" | "bg-green"   => color16!(Background Normal Green),
            "Y" | "bg-yellow"  => color16!(Background Normal Yellow),
            "B" | "bg-blue"    => color16!(Background Normal Blue),
            "M" | "bg-magenta" => color16!(Background Normal Magenta),
            "C" | "bg-cyan"    => color16!(Background Normal Cyan),
            "W" | "bg-white"   => color16!(Background Normal White),

            "K!" | "bg-black!" | "bg-bright-black"     => color16!(Background Bright Black),
            "R!" | "bg-red!" | "bg-bright-red"         => color16!(Background Bright Red),
            "G!" | "bg-green!" | "bg-bright-green"     => color16!(Background Bright Green),
            "Y!" | "bg-yellow!" | "bg-bright-yellow"   => color16!(Background Bright Yellow),
            "B!" | "bg-blue!" | "bg-bright-blue"       => color16!(Background Bright Blue),
            "M!" | "bg-magenta!" | "bg-bright-magenta" => color16!(Background Bright Magenta),
            "C!" | "bg-cyan!" | "bg-bright-cyan"       => color16!(Background Bright Cyan),
            "W!" | "bg-white!" | "bg-bright-white"     => color16!(Background Bright White),

            _ => return Err(()),
        };

        Ok(change)
    }
}

/// Which "kind" of color has to be changed.
#[derive(Debug, PartialEq, Clone)]
pub enum ColorKind {
    Background,
    Foreground,
}

impl ColorKind {
    pub fn to_change(&self, color: Color) -> Change {
        match self {
            Self::Foreground => Change::Foreground(color),
            Self::Background => Change::Background(color),
        }
    }
}

/// An "extended" color, which can be either a real color or the "normal", default color.
#[derive(Debug, Default, PartialEq, Clone)]
pub enum ExtColor {
    #[default]
    Normal,
    Color(Color),
}

#[derive(Debug, PartialEq, Clone)]
#[allow(clippy::enum_variant_names)]
pub enum Color {
    Color16(Color16),
    Color256(Color256),
    ColorRgb(ColorRgb),
}

/// A terminal color.
#[derive(Debug, PartialEq, Clone)]
pub struct Color16 {
    base_color: BaseColor,
    intensity: Intensity,
}

impl Color16 {
    pub fn new(base_color: BaseColor, intensity: Intensity) -> Self {
        Self {
            base_color,
            intensity,
        }
    }
}

/// The intensity of a terminal color.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Intensity {
    Normal,
    Bright,
}

impl Intensity {
    pub fn new(is_bright: bool) -> Self {
        if is_bright {
            Self::Bright
        } else {
            Self::Normal
        }
    }
}

/// A "base" terminal color, which has to be completed with an [`Intensity`] in order to describe a
/// whole terminal color.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum BaseColor {
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
}

impl BaseColor {
    /// Return the index of a color, in the same ordering as the ANSI color sequences.
    pub fn index(&self) -> u8 {
        match self {
            Self::Black => 0,
            Self::Red => 1,
            Self::Green => 2,
            Self::Yellow => 3,
            Self::Blue => 4,
            Self::Magenta => 5,
            Self::Cyan => 6,
            Self::White => 7,
        }
    }
}

/// A color in the 256-color palette.
#[derive(Debug, PartialEq, Clone)]
pub struct Color256(pub u8);

/// An RGB color.
#[derive(Debug, PartialEq, Clone)]
pub struct ColorRgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

#[cfg(test)]
mod tests {}