mise 2026.4.11

The front-end to your dev env
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
use std::collections::BTreeMap;
use std::str::FromStr;

use serde::Serialize;
use serde_json::ser::PrettyFormatter;

use crate::sysconfig::cursor::Cursor;

/// A value in the [`SysconfigData`] map.
///
/// Values are assumed to be either strings or integers.
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)]
#[serde(untagged)]
pub(super) enum Value {
    String(String),
    Int(i32),
}

/// The data extracted from a `_sysconfigdata_` file.
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)]
pub(super) struct SysconfigData(BTreeMap<String, Value>);

impl SysconfigData {
    /// Returns an iterator over the key-value pairs in the map.
    pub(super) fn iter_mut(&mut self) -> std::collections::btree_map::IterMut<'_, String, Value> {
        self.0.iter_mut()
    }

    /// Inserts a key-value pair into the map.
    pub(super) fn insert(&mut self, key: String, value: Value) -> Option<Value> {
        self.0.insert(key, value)
    }

    /// Formats the `sysconfig` data as a pretty-printed string.
    pub(super) fn to_string_pretty(&self) -> Result<String, serde_json::Error> {
        let output = {
            let mut buf = Vec::new();
            let mut serializer = serde_json::Serializer::with_formatter(
                &mut buf,
                PrettyFormatter::with_indent(b"    "),
            );
            self.0.serialize(&mut serializer)?;
            String::from_utf8(buf).unwrap()
        };
        Ok(format!(
            "# system configuration generated and used by the sysconfig module\nbuild_time_vars = {output}\n",
        ))
    }
}

impl std::fmt::Display for SysconfigData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let output = {
            let mut buf = Vec::new();
            let mut serializer = serde_json::Serializer::new(&mut buf);
            self.0.serialize(&mut serializer).unwrap();
            String::from_utf8(buf).unwrap()
        };
        write!(f, "{output}",)
    }
}

impl FromIterator<(String, Value)> for SysconfigData {
    fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

/// Parse the `_sysconfigdata_` file (e.g., `{real_prefix}/lib/python3.12/_sysconfigdata__darwin_darwin.py"`
/// on macOS).
///
/// `_sysconfigdata_` is structured as follows:
///
/// 1. A comment on the first line (e.g., `# system configuration generated and used by the sysconfig module`).
/// 2. An assignment to `build_time_vars` (e.g., `build_time_vars = { ... }`).
///
/// The right-hand side of the assignment is a JSON object. The keys are strings, and the values
/// are strings or numbers.
impl FromStr for SysconfigData {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Read the first line of the file.
        let Some(s) =
            s.strip_prefix("# system configuration generated and used by the sysconfig module\n")
        else {
            return Err(Error::MissingHeader);
        };

        // Read the assignment to `build_time_vars`.
        let Some(s) = s.strip_prefix("build_time_vars") else {
            return Err(Error::MissingAssignment);
        };

        let mut cursor = Cursor::new(s);

        cursor.eat_while(is_python_whitespace);
        if !cursor.eat_char('=') {
            return Err(Error::MissingAssignment);
        }
        cursor.eat_while(is_python_whitespace);

        if !cursor.eat_char('{') {
            return Err(Error::MissingOpenBrace);
        }

        let mut map = BTreeMap::new();
        loop {
            let Some(next) = cursor.bump() else {
                return Err(Error::UnexpectedEof);
            };

            match next {
                '\'' | '"' => {
                    // Parse key.
                    let key = parse_string(&mut cursor, next)?;

                    cursor.eat_while(is_python_whitespace);
                    cursor.eat_char(':');
                    cursor.eat_while(is_python_whitespace);

                    // Parse value
                    let value = match cursor.first() {
                        '\'' | '"' => Value::String(parse_concatenated_string(&mut cursor)?),
                        '-' => {
                            cursor.bump();
                            Value::Int(-parse_int(&mut cursor)?)
                        }
                        c if c.is_ascii_digit() => Value::Int(parse_int(&mut cursor)?),
                        c => return Err(Error::UnexpectedCharacter(c)),
                    };

                    // Insert into map.
                    map.insert(key, value);

                    // Skip optional comma.
                    cursor.eat_while(is_python_whitespace);
                    cursor.eat_char(',');
                    cursor.eat_while(is_python_whitespace);
                }

                // Skip whitespace.
                ' ' | '\n' | '\r' | '\t' => {}

                // When we see a closing brace, we're done.
                '}' => {
                    break;
                }

                c => return Err(Error::UnexpectedCharacter(c)),
            }
        }

        Ok(Self(map))
    }
}

/// Parse a Python string literal.
///
/// Expects the previous character to be the opening quote character.
fn parse_string(cursor: &mut Cursor, quote: char) -> Result<String, Error> {
    let mut result = String::new();
    loop {
        let Some(c) = cursor.bump() else {
            return Err(Error::UnexpectedEof);
        };
        match c {
            '\\' => {
                // Handle escaped quotes.
                if cursor.first() == quote {
                    // Consume the backslash.
                    cursor.bump();
                    result.push(quote);
                    continue;
                }

                // Keep the backslash and following character.
                result.push('\\');
                result.push(cursor.first());
                cursor.bump();
            }

            // Consume closing quote.
            c if c == quote => {
                break;
            }

            c => {
                result.push(c);
            }
        }
    }
    Ok(result)
}

/// Parse a Python string, which may be a concatenation of multiple string literals.
///
/// Expects the cursor to start at an opening quote character.
fn parse_concatenated_string(cursor: &mut Cursor) -> Result<String, Error> {
    let mut result = String::new();
    loop {
        let Some(c) = cursor.bump() else {
            return Err(Error::UnexpectedEof);
        };
        match c {
            '\'' | '"' => {
                // Parse a new string fragment and append it.
                result.push_str(&parse_string(cursor, c)?);
            }
            c if is_python_whitespace(c) => {
                // Skip whitespace between fragments
            }
            c => return Err(Error::UnexpectedCharacter(c)),
        }

        // Lookahead to the end of the string.
        if matches!(cursor.first(), ',' | '}') {
            break;
        }
    }
    Ok(result)
}

/// Parse an integer literal.
///
/// Expects the cursor to start at the first digit of the integer.
fn parse_int(cursor: &mut Cursor) -> Result<i32, std::num::ParseIntError> {
    let mut result = String::new();
    loop {
        let c = cursor.first();
        if !c.is_ascii_digit() {
            break;
        }
        result.push(c);
        cursor.bump();
    }
    result.parse()
}

/// Returns `true` for [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens)
/// characters.
const fn is_python_whitespace(c: char) -> bool {
    matches!(
        c,
        // Space, tab, form-feed, newline, or carriage return
        ' ' | '\t' | '\x0C' | '\n' | '\r'
    )
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Missing opening brace")]
    MissingOpenBrace,
    #[error("Unexpected character: {0}")]
    UnexpectedCharacter(char),
    #[error("Unexpected end of file")]
    UnexpectedEof,
    #[error("Failed to parse integer")]
    ParseInt(#[from] std::num::ParseIntError),
    #[error("`_sysconfigdata_` is missing a header comment")]
    MissingHeader,
    #[error("`_sysconfigdata_` is missing an assignment to `build_time_vars`")]
    MissingAssignment,
}

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

    #[test]
    fn test_parse_string() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": "value1",
                "key2": 42,
                "key3": "multi-part" " string"
            }
        "#
        );

        let result = input.parse::<SysconfigData>().expect("Parsing failed");
        let snapshot = result.to_string_pretty().unwrap();

        insta::assert_snapshot!(snapshot, @r###"
        # system configuration generated and used by the sysconfig module
        build_time_vars = {
            "key1": "value1",
            "key2": 42,
            "key3": "multi-part string"
        }
        "###);
    }

    #[test]
    fn test_parse_trailing_comma() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": "value1",
                "key2": 42,
                "key3": "multi-part" " string",
            }
        "#
        );

        let result = input.parse::<SysconfigData>().expect("Parsing failed");
        let snapshot = result.to_string_pretty().unwrap();

        insta::assert_snapshot!(snapshot, @r###"
        # system configuration generated and used by the sysconfig module
        build_time_vars = {
            "key1": "value1",
            "key2": 42,
            "key3": "multi-part string"
        }
        "###);
    }

    #[test]
    fn test_parse_integer_values() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": 12345,
                "key2": -15
            }
        "#
        );

        let result = input.parse::<SysconfigData>().expect("Parsing failed");
        let snapshot = result.to_string_pretty().unwrap();

        insta::assert_snapshot!(snapshot, @r###"
        # system configuration generated and used by the sysconfig module
        build_time_vars = {
            "key1": 12345,
            "key2": -15
        }
        "###);
    }

    #[test]
    fn test_parse_escaped_quotes() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": "value with \"escaped quotes\"",
                "key2": 'single-quoted \'escaped\''
            }
        "#
        );

        let result = input.parse::<SysconfigData>().expect("Parsing failed");
        let snapshot = result.to_string_pretty().unwrap();

        insta::assert_snapshot!(snapshot, @r###"
        # system configuration generated and used by the sysconfig module
        build_time_vars = {
            "key1": "value with \"escaped quotes\"",
            "key2": "single-quoted 'escaped'"
        }
        "###);
    }

    #[test]
    fn test_parse_concatenated_strings() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": "multi-"
                        "line "
                        "string"
            }
        "#
        );

        let result = input.parse::<SysconfigData>().expect("Parsing failed");
        let snapshot = result.to_string_pretty().unwrap();

        insta::assert_snapshot!(snapshot, @r###"
        # system configuration generated and used by the sysconfig module
        build_time_vars = {
            "key1": "multi-line string"
        }
        "###);
    }

    #[test]
    fn test_missing_header_error() {
        let input = indoc::indoc!(
            r#"
            build_time_vars = {
                "key1": "value1"
            }
        "#
        );

        let result = input.parse::<SysconfigData>();
        assert!(matches!(result, Err(Error::MissingHeader)));
    }

    #[test]
    fn test_missing_assignment_error() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            {
                "key1": "value1"
            }
        "#
        );

        let result = input.parse::<SysconfigData>();
        assert!(matches!(result, Err(Error::MissingAssignment)));
    }

    #[test]
    fn test_unexpected_character_error() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": &123
            }
        "#
        );

        let result = input.parse::<SysconfigData>();
        assert!(
            result.is_err(),
            "Expected parsing to fail due to unexpected character"
        );
    }

    #[test]
    fn test_unexpected_eof() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": 123
        "#
        );

        let result = input.parse::<SysconfigData>();
        assert!(
            result.is_err(),
            "Expected parsing to fail due to unexpected character"
        );
    }

    #[test]
    fn test_unexpected_comma() {
        let input = indoc::indoc!(
            r#"
            # system configuration generated and used by the sysconfig module
            build_time_vars = {
                "key1": 123,,
            }
        "#
        );

        let result = input.parse::<SysconfigData>();
        assert!(
            result.is_err(),
            "Expected parsing to fail due to unexpected character"
        );
    }
}