farben-macros 0.7.1

Procedural macros for Farben
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
//! Procedural macros for the Farben terminal styling library.
//!
//! Provides compile-time processing of farben markup, baking the final ANSI-escaped
//! strings directly into the binary with zero runtime overhead. Also provides
//! compile-time format string splitting via [`cformat`] and [`cformatb`].
//! All macros in this crate are re-exported through `farben` and should not be
//! used directly in most cases.
//!
//! ## Macros
//!
//! - [`color!`] -- parse and render markup at compile time, returns a `FarbenStr`
//! - [`colorb!`] -- same as `color!` but without a trailing reset
//! - [`cformat!`] -- compile-time split of markup format strings with runtime args
//! - [`cformatb!`] -- bleed variant of `cformat!`
//! - [`validate_color!`] -- validates markup at compile time, returns the original string

mod template;

use litext::litext;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;

/// Reads `farben_registry.lsv` from `OUT_DIR` and pre-populates the compile-time registry.
///
/// Calls `insert_style` for each style entry and `set_prefix` for each prefix entry
/// written by the build script from `.frb` config files. Called at the start of each
/// proc macro invocation. If the file does not exist, the function returns silently.
fn load_registry() {
    let out_dir = std::env::var("OUT_DIR").unwrap_or_default();
    let path = std::path::Path::new(&out_dir).join("farben_registry.lsv");
    if let Ok(content) = std::fs::read_to_string(&path) {
        let mut sections = content.splitn(2, "---\n");
        let styles_section = sections.next().unwrap_or("");
        let prefixes_section = sections.next().unwrap_or("");

        for line in styles_section.lines() {
            if line.is_empty() {
                continue;
            }
            let (key, value) = line.split_once('=').unwrap();

            farben_core::registry::insert_style(
                key,
                farben_core::ansi::Style::parse(format!("[{value}]"))
                    .unwrap_or_else(|e| panic!("farben: invalid style in registry '{key}': {e}")),
            )
            .unwrap_or_else(|e| panic!("farben: invalid style name in registry '{key}': {e}"));
        }

        for line in prefixes_section.lines() {
            if line.is_empty() {
                continue;
            }
            let (key, value) = line.split_once('=').unwrap();

            farben_core::registry::set_prefix(key, value)
                .unwrap_or_else(|e| panic!("farben: failure while setting prefix '{key}': {e}"));
        }
    }
}

/// Parses and colorizes a farben markup string at compile time.
///
/// Tokenizes and renders the input at compile time, emitting the final ANSI-escaped
/// string as a string literal baked into the binary. Invalid markup produces a
/// compiler error at the call site.
///
/// # Examples
///
/// ```ignore
/// use farben_macros::color;
/// println!("{}", color!("[bold red]Hello!"));
/// ```
#[proc_macro]
pub fn color(input: TokenStream) -> TokenStream {
    load_registry();

    let input = litext!(input as litext::LitStr);
    let value = input.value();
    let tokens = match farben_core::lexer::tokenize(value) {
        Ok(t) => t,
        Err(e) => {
            let msg = e.to_string();
            return comperr::error(input.span(), msg).into();
        }
    };
    let styled = format!("{}\x1b[0m", farben_core::parser::render_forced(tokens));
    quote! {
        ::farben::FarbenStr { styled: #styled }
    }
    .into()
}

/// Parses and colorizes a farben markup string at compile time, without appending a
/// trailing SGR reset.
///
/// Behaves identically to [`color!`] except the final `\x1b[0m` reset is omitted.
/// Styles applied by this macro bleed into subsequent terminal output, making it
/// useful for chaining multiple colored segments where the style should carry forward.
///
/// Invalid markup produces a compiler error at the call site.
///
/// # Examples
///
/// ```ignore
/// use farben_macros::colorb;
/// println!("{}", colorb!("[bold red]Bleeds..."));
/// ```
#[proc_macro]
pub fn colorb(input: TokenStream) -> TokenStream {
    load_registry();

    let input = litext!(input as litext::LitStr);
    let value = input.value();
    let tokens = match farben_core::lexer::tokenize(value) {
        Ok(t) => t,
        Err(e) => {
            let msg = e.to_string();
            return comperr::error(input.span(), msg).into();
        }
    };
    let styled = farben_core::parser::render_forced(tokens);
    quote! {
        ::farben::FarbenStr { styled: #styled }
    }
    .into()
}

/// Validates farben markup at compile time and returns the original string literal unchanged.
///
/// On success, emits the input string literal as-is. On failure, emits a compiler error
/// at the call site. Used internally by `color_fmt!`, `cprint!`, and `cprintln!` to validate
/// the format string before runtime processing with format arguments.
///
/// This macro is part of the internal API. Prefer [`color!`] for static strings or
/// `color_fmt!` for strings with format arguments.
#[proc_macro]
pub fn validate_color(input: TokenStream) -> TokenStream {
    load_registry();

    let original = input.clone();

    let input = litext!(input as litext::LitStr);
    let value = input.value();

    match farben_core::lexer::tokenize(value) {
        Ok(_) => original,
        Err(e) => {
            let msg = e.to_string();
            comperr::error(input.span(), msg).into()
        }
    }
}

/// Parses and renders an inline markdown string at compile time.
///
/// Tokenizes and renders the input at compile time, emitting the final
/// ANSI-escaped string as a string literal baked into the binary.
/// Supports `**bold**`, `*italic*`, `_italic_`, `__underline__`,
/// `~~strikethrough~~`, and `` `inline code` ``.
///
/// # Examples
///
/// Compiles inline markdown to ANSI-escaped terminal output at compile time.
///
/// Parses markdown syntax (`**bold**`, `*italic*`, `` `code` ``, `~~strike~~`, `__underline__`)
/// and produces terminal-compatible ANSI output.
#[cfg(feature = "markdown")]
#[deprecated]
#[proc_macro]
pub fn markdown(input: TokenStream) -> TokenStream {
    let input = litext!(input as litext::LitStr);
    let value = input.value();
    let result = farben_md::renderer::render(&farben_md::lexer::tokenize(value));
    quote! { #result }.into()
}

/// Compiles a farben markup format string into an inlined `String`-building block.
///
/// Splits the format string at `{...}` placeholders at compile time. Static
/// segments between placeholders are rendered to ANSI escape sequences once,
/// baked into the binary as string literals, and written with a single
/// `push_str`. Dynamic arguments are written via `format_args!` at the call
/// site, preserving full format-spec support (`{name}`, `{0}`, `{:.2}`, etc.)
/// and allowing variable captures from the surrounding scope.
///
/// A trailing `\x1b[0m` reset is appended. For the bleed variant see
/// [`cformatb!`]. This macro is the compile-time backend for `cformat!` from
/// the `farben` crate.
#[proc_macro]
pub fn cformat(input: TokenStream) -> TokenStream {
    build_cformat(input, false)
}

/// Like [`cformat!`] but omits the trailing SGR reset.
///
/// Styles applied by the emitted block bleed into subsequent terminal output.
/// This macro is the compile-time backend for `cformatb!` from the `farben` crate.
#[proc_macro]
pub fn cformatb(input: TokenStream) -> TokenStream {
    build_cformat(input, true)
}

/// Shared implementation for [`cformat`] and [`cformatb`].
fn build_cformat(input: TokenStream, bleed: bool) -> TokenStream {
    load_registry();

    let mut iter = proc_macro2::TokenStream::from(input).into_iter();

    let Some(fmt_tt) = iter.next() else {
        return quote! { ::std::string::String::new() }.into();
    };

    let s = fmt_tt.to_string();
    let fmt_str = if s.starts_with('"') && s.ends_with('"') {
        let inner = &s[1..s.len() - 1];
        inner
            .replace("\\n", "\n")
            .replace("\\t", "\t")
            .replace("\\r", "\r")
            .replace("\\\\", "\\")
            .replace("\\\"", "\"")
    } else {
        let msg = "cformat: expected a string literal as first argument";
        return comperr::error(fmt_tt.span(), msg).into();
    };

    let rest: Vec<proc_macro2::TokenTree> = iter.collect();
    let args: Vec<TokenStream2> = split_args(rest);

    let pieces = match template::split(&fmt_str, bleed) {
        Ok(p) => p,
        Err(e) => {
            return comperr::error(fmt_tt.span(), e.to_string()).into();
        }
    };

    let capacity: usize = pieces
        .iter()
        .filter_map(|p| {
            if let template::Piece::Static { ansi, .. } = p {
                Some(ansi.len())
            } else {
                None
            }
        })
        .sum();

    let mut arg_iter = args.iter();
    let mut stmts: Vec<TokenStream2> = Vec::new();

    for piece in &pieces {
        match piece {
            template::Piece::Static { ansi, .. } => {
                if ansi.is_empty() {
                    continue;
                }
                stmts.push(quote! {
                    ::std::fmt::Write::write_fmt(
                        &mut __out,
                        ::std::format_args!(
                            "{}",
                            ::farben::FarbenStr { styled: #ansi },
                        ),
                    ).unwrap();
                });
            }
            template::Piece::Arg(spec) => {
                let fmt_spec = format!("{{{spec}}}");
                let fmt_lit_str = format!(r#""{fmt_spec}""#);
                let fmt_lit: proc_macro2::TokenStream = fmt_lit_str.parse().unwrap();

                match arg_iter.next() {
                    Some(arg) => {
                        stmts.push(quote! {
                            ::std::fmt::Write::write_fmt(
                                &mut __out,
                                ::std::format_args!(#fmt_lit, #arg),
                            ).unwrap();
                        });
                    }
                    None => {
                        stmts.push(quote! {
                            ::std::fmt::Write::write_fmt(
                                &mut __out,
                                ::std::format_args!(#fmt_lit),
                            ).unwrap();
                        });
                    }
                }
            }
        }
    }

    quote! {
        {
            use ::std::fmt::Write as _;
            let mut __out = ::std::string::String::with_capacity(#capacity);
            #(#stmts)*
            __out
        }
    }
    .into()
}

/// Proc-macro backend for the compile-variant `($fmt:literal)` arms of
/// `cprint!`, `cprintln!`, `cprintb!`, etc.
///
/// If the format string contains NO format arguments (`{...}` placeholders),
/// renders the markup at compile time and returns a [`FarbenStr`]. This makes
/// `cargo expand` show the intended `FarbenStr { styled: "…" }` for bare
/// literals.
///
/// If the format string DOES contain `{…}` placeholders (including implicit
/// capture like `{name}`), compile-time rendering is impossible because
/// mixed-site macro hygiene prevents the proc-macro from reaching the
/// call-site variable scope. In that case we fall back to runtime
/// processing via `color_runtime(format!(…), false)`, where the `format!`
/// expansion at the call site correctly resolves the variables. The markup
/// was already validated at compile time by the `validate_color!` call in
/// the macro-rules arm, so the runtime parse is guaranteed to succeed.
#[proc_macro]
pub fn compile_cprint(input: TokenStream) -> TokenStream {
    load_registry();
    let input_ts = proc_macro2::TokenStream::from(input);

    let Some(fmt_tt) = input_ts.clone().into_iter().next() else {
        return quote! { ::farben::FarbenStr { styled: "" } }.into();
    };

    let s = fmt_tt.to_string();
    let fmt_str = if s.starts_with('"') && s.ends_with('"') {
        let inner = &s[1..s.len() - 1];
        inner
            .replace("\\n", "\n")
            .replace("\\t", "\t")
            .replace("\\r", "\r")
            .replace("\\\\", "\\")
            .replace("\\\"", "\"")
    } else {
        let msg = "compile_cprint: expected a string literal";
        return comperr::error(fmt_tt.span(), msg).into();
    };

    let has_args = {
        let mut chars = fmt_str.chars().peekable();
        let mut found = false;
        while let Some(c) = chars.next() {
            if c == '{' {
                if let Some('{') = chars.peek() {
                    chars.next();
                } else {
                    found = true;
                    break;
                }
            }
        }
        found
    };

    if !has_args {
        let tokens = match farben_core::lexer::tokenize(&fmt_str) {
            Ok(t) => t,
            Err(e) => {
                return comperr::error(fmt_tt.span(), e.to_string()).into();
            }
        };
        let styled = format!("{}\x1b[0m", farben_core::parser::render_forced(tokens));
        return quote! {
            ::farben::FarbenStr { styled: #styled }
        }
        .into();
    }

    if let Err(e) = farben_core::lexer::tokenize(&fmt_str) {
        return comperr::error(fmt_tt.span(), e.to_string()).into();
    }

    quote! {
        ::farben::color_runtime(
            ::std::format!(#fmt_tt),
            false,
        )
    }
    .into()
}

/// Proc-macro backend for the compile-variant `($fmt:literal)` arms of the
/// bleed variants (`cprintb!`, `cprintbln!`, etc.).
/// Same logic as [`compile_cprint`] but omits the trailing SGR reset.
#[proc_macro]
pub fn compile_cprintb(input: TokenStream) -> TokenStream {
    load_registry();
    let input_ts = proc_macro2::TokenStream::from(input);

    let Some(fmt_tt) = input_ts.clone().into_iter().next() else {
        return quote! { ::farben::FarbenStr { styled: "" } }.into();
    };

    let s = fmt_tt.to_string();
    let fmt_str = if s.starts_with('"') && s.ends_with('"') {
        let inner = &s[1..s.len() - 1];
        inner
            .replace("\\n", "\n")
            .replace("\\t", "\t")
            .replace("\\r", "\r")
            .replace("\\\\", "\\")
            .replace("\\\"", "\"")
    } else {
        let msg = "compile_cprintb: expected a string literal";
        return comperr::error(fmt_tt.span(), msg).into();
    };

    let mut chars = fmt_str.chars().peekable();
    let mut has_args = false;
    while let Some(c) = chars.next() {
        if c == '{' {
            if let Some('{') = chars.peek() {
                chars.next();
            } else {
                has_args = true;
                break;
            }
        }
    }

    if !has_args {
        let tokens = match farben_core::lexer::tokenize(&fmt_str) {
            Ok(t) => t,
            Err(e) => {
                return comperr::error(fmt_tt.span(), e.to_string()).into();
            }
        };
        let styled = farben_core::parser::render_forced(tokens);
        return quote! {
            ::farben::FarbenStr { styled: #styled }
        }
        .into();
    }

    if let Err(e) = farben_core::lexer::tokenize(&fmt_str) {
        return comperr::error(fmt_tt.span(), e.to_string()).into();
    }

    quote! {
        ::farben::color_runtime(
            ::std::format!(#fmt_tt),
            true,
        )
    }
    .into()
}

/// Splits a flat list of token trees on top-level commas into individual arg
/// token streams. The leading comma (between the format literal and first arg)
/// is consumed before this is called via `iter` already being past the literal.
fn split_args(tts: Vec<proc_macro2::TokenTree>) -> Vec<TokenStream2> {
    let mut args: Vec<TokenStream2> = Vec::new();
    let mut current: Vec<proc_macro2::TokenTree> = Vec::new();
    let mut depth = 0usize;

    for tt in tts {
        match &tt {
            proc_macro2::TokenTree::Punct(p) if p.as_char() == ',' && depth == 0 => {
                if !current.is_empty() {
                    args.push(current.drain(..).collect());
                }
            }
            proc_macro2::TokenTree::Group(_) => {
                depth += 1;
                current.push(tt);
                depth -= 1;
            }
            _ => current.push(tt),
        }
    }
    if !current.is_empty() {
        args.push(current.into_iter().collect());
    }
    args
}