nandi/rustnimpublic Fork 0
8354895601e0a0fa3e1962b9ef728d00050ffb97
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Add display.rs and the alloc half: all of base16ct now goes through afb2a6e · on 8354895601e0a0fa3e1962b9ef728d00050ffb97 · nandithebull · 5h ago
fmt.rs · 202 lines · 5.9 KBRust Blame HistoryRaw
  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
//! Rust format strings (`println!`, `format!`) -> Nim string expressions.
//!
//! Only the subset that is reproduced exactly is accepted. An unrecognised
//! format spec is an error, never a best-effort guess: `{:>8.3}` silently
//! rendered as `{}` would produce plausible-looking wrong output, which is the
//! failure mode this project exists to avoid.

/// One piece of a parsed format string.
#[derive(Debug, PartialEq)]
pub enum Piece {
    Lit(String),
    Arg { r#ref: Ref, spec: Spec },
}

#[derive(Debug, PartialEq)]
pub enum Ref {
    /// `{}` — consumes the next positional argument.
    Next,
    /// `{0}` — an explicit index.
    Index(usize),
    /// `{name}` — an inline captured identifier.
    Named(String),
}

#[derive(Debug, PartialEq, Default)]
pub struct Spec {
    pub debug: bool,
    /// `x`, `X`, `b`, `o` — `None` for Display/Debug.
    pub radix: Option<char>,
    pub width: usize,
    pub zero: bool,
}

pub fn parse(s: &str) -> Result<Vec<Piece>, String> {
    let mut out = Vec::new();
    let mut lit = String::new();
    let mut it = s.chars().peekable();

    while let Some(c) = it.next() {
        match c {
            '{' if it.peek() == Some(&'{') => {
                it.next();
                lit.push('{');
            }
            '}' if it.peek() == Some(&'}') => {
                it.next();
                lit.push('}');
            }
            '}' => return Err("unmatched `}` in format string".into()),
            '{' => {
                if !lit.is_empty() {
                    out.push(Piece::Lit(std::mem::take(&mut lit)));
                }
                let mut body = String::new();
                let mut closed = false;
                for c in it.by_ref() {
                    if c == '}' {
                        closed = true;
                        break;
                    }
                    body.push(c);
                }
                if !closed {
                    return Err("unmatched `{` in format string".into());
                }
                let (name, spec) = match body.split_once(':') {
                    Some((n, s)) => (n, parse_spec(s)?),
                    None => (body.as_str(), Spec::default()),
                };
                let r#ref = if name.is_empty() {
                    Ref::Next
                } else if let Ok(i) = name.parse::<usize>() {
                    Ref::Index(i)
                } else if name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                    Ref::Named(name.to_string())
                } else {
                    return Err(format!("unsupported format argument `{name}`"));
                };
                out.push(Piece::Arg { r#ref, spec });
            }
            _ => lit.push(c),
        }
    }
    if !lit.is_empty() {
        out.push(Piece::Lit(lit));
    }
    Ok(out)
}

fn parse_spec(s: &str) -> Result<Spec, String> {
    let mut spec = Spec::default();
    let mut rest = s;

    match rest.chars().last() {
        Some('?') => {
            spec.debug = true;
            rest = &rest[..rest.len() - 1];
        }
        Some(r @ ('x' | 'X' | 'b' | 'o')) => {
            spec.radix = Some(r);
            rest = &rest[..rest.len() - 1];
        }
        _ => {}
    }

    if let Some(r) = rest.strip_prefix('0') {
        spec.zero = true;
        rest = r;
    }
    if !rest.is_empty() {
        spec.width = rest
            .parse::<usize>()
            .map_err(|_| format!("unsupported format spec `:{s}` (precision, alignment and fill are not implemented)"))?;
    }
    Ok(spec)
}

/// Build the Nim expression for one argument, given its already-lowered value.
///
/// `integer` says whether the value is one of Nim's integer types. `{:x}` on
/// an integer formats its two's-complement bit pattern; on anything else it is
/// a call to that type's own `LowerHex`/`UpperHex` impl, which is a different
/// operation and a different proc.
pub fn render_arg(value: &str, spec: &Spec, integer: bool) -> String {
    let core = match spec.radix {
        Some(r) if integer => format!(
            "rsRadix({}, {}, {})",
            value,
            match r {
                'x' | 'X' => 16,
                'b' => 2,
                _ => 8,
            },
            r == 'X'
        ),
        Some(r) => format!(
            "{}({})",
            match r {
                'x' => "rsLowerHex",
                'X' => "rsUpperHex",
                'b' => "rsBinary",
                _ => "rsOctal",
            },
            value
        ),
        None if spec.debug => format!("rsDebug({value})"),
        None => format!("rsDisplay({value})"),
    };
    if spec.width > 0 {
        format!("rsPad({}, {}, {})", core, spec.width, spec.zero)
    } else {
        core
    }
}

/// Nim string literal with Rust's escaping rules applied to the bytes we emit.
pub fn nim_str(s: &str) -> String {
    let mut out = String::from("\"");
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

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

    #[test]
    fn braces_and_specs() {
        assert_eq!(parse("a{{b").unwrap(), vec![Piece::Lit("a{b".into())]);
        assert_eq!(
            parse("{:02x}").unwrap(),
            vec![Piece::Arg {
                r#ref: Ref::Next,
                spec: Spec { debug: false, radix: Some('x'), width: 2, zero: true }
            }]
        );
        assert_eq!(
            parse("{n:?}").unwrap(),
            vec![Piece::Arg {
                r#ref: Ref::Named("n".into()),
                spec: Spec { debug: true, ..Spec::default() }
            }]
        );
    }

    #[test]
    fn unsupported_specs_are_rejected_not_guessed() {
        assert!(parse("{:>8}").is_err());
        assert!(parse("{:.3}").is_err());
        assert!(parse("{").is_err());
    }
}