1//! This module is only used when the feature `terminfo` is not activated.
23use proc_macro::TokenStream;
4use proc_macro2::TokenStream as TokenStream2;
5use quote::{quote, ToTokens};
67use crate::color_context::Context;
8use crate::error::{SpanError, Error};
9use crate::format_args::{
10 parse_args, get_format_string, get_args_and_format_string, parse_format_string, Node
11};
1213/// Common code shared between the public macros, ANSI implementation.
14pub fn get_format_args(input: TokenStream) -> Result<TokenStream2, SpanError> {
15let (format_string_token, args) = get_args_and_format_string(input)?;
16let format_string = format_string_token.value();
1718// Split the format string into a list of nodes; each node is either a string literal (text), a
19 // placeholder for a `format!`-like macro, or a color code:
20let format_nodes = parse_format_string(&format_string, &format_string_token)?;
2122let final_format_string = get_format_string_from_nodes(format_nodes)?;
2324// Group all the final arguments into a single iterator:
25let args = args.iter()
26 .map(|arg| arg.to_token_stream())
27 .skip(1); // Skip the original format string
28let final_args = std::iter::once(final_format_string).chain(args);
2930Ok(quote! { #(#final_args),* })
31}
3233/// Transforms a string literal by parsing its color tags.
34pub fn get_cstr(input: TokenStream) -> Result<TokenStream2, SpanError> {
35let args = parse_args(input)?;
36let format_string_token = get_format_string(args.first())?;
37let format_string = format_string_token.value();
3839if args.len() > 1 {
40return Err(SpanError::new(Error::TooManyArgs, None));
41 }
4243// Split the format string into a list of nodes; each node is either a string literal (text),
44 // or a color code; `format!`-like placeholders will be parsed indenpendently, but as they are
45 // put back unchanged into the format string, it's not a problem:
46let format_nodes = parse_format_string(&format_string, &format_string_token)?;
47 get_format_string_from_nodes(format_nodes)
48}
4950/// Generates a new format string with the color tags replaced by the right ANSI codes.
51fn get_format_string_from_nodes(nodes: Vec<Node>) -> Result<TokenStream2, SpanError> {
52// The final, modified format string which will be given to the `format!`-like macro:
53let mut format_string = String::new();
54// Stores which colors and attributes are set while processing the format string:
55let mut color_context = Context::new();
5657// Generate the final format string:
58for node in nodes {
59match node {
60 Node::Text(s) | Node::Placeholder(s) => {
61 format_string.push_str(s);
62 }
63 Node::ColorTagGroup(tag_group) => {
64let ansi_string = color_context.ansi_apply_tags(tag_group)?;
65 format_string.push_str(&ansi_string);
66 }
67 }
68 }
6970Ok(quote! { #format_string })
71}