monty 0.0.19-beta.2

A sandboxed, snapshotable Python interpreter written in Rust.
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Python `pathlib.Path` type implementation.
//!
//! Provides a path object with both pure methods (no I/O) and filesystem methods
//! (require `OsAccess` implementation). Pure methods are handled directly by the VM,
//! while filesystem methods yield external function calls for the host to resolve.

use std::{
    cell::Cell,
    collections::hash_map::DefaultHasher,
    fmt::Write,
    hash::{Hash, Hasher},
    mem,
};

use smallvec::SmallVec;

use crate::{
    args::ArgValues,
    builtins::open::builtin_open,
    bytecode::{CallResult, VM},
    defer_drop,
    exception_private::{ExcType, RunResult, SimpleException},
    hash::HashValue,
    heap::{DropWithHeap, Heap, HeapData, HeapId, HeapItem, HeapRead, HeapReadOutput},
    intern::{Interns, StaticStrings},
    os::{MontyPath, build_path_os_call, is_path_os_method},
    resource::ResourceTracker,
    types::{LazyHeapSet, PyTrait, Type, allocate_tuple, str::allocate_string},
    value::{EitherStr, Value},
};

/// Python `pathlib.Path` object representing a filesystem path.
///
/// Stores a normalized POSIX path string. Windows-style paths are converted
/// to POSIX format (backslashes to forward slashes).
///
/// The path is immutable - all operations that would modify the path return
/// new `Path` objects or strings.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct Path {
    /// The normalized path string.
    path: String,
    /// Lazily-computed Python hash. Paths are immutable (all "modifying"
    /// operations return new `Path` objects). Skipped on serde — see
    /// [`super::Str::cached_hash`] for the rationale.
    #[serde(skip)]
    cached_hash: Cell<Option<HashValue>>,
}

impl PartialEq for Path {
    /// Compares only the path string — `cached_hash` is a pure optimisation.
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path
    }
}

impl Path {
    /// Creates a new `Path` from a path string.
    ///
    /// The path is normalized:
    /// - Backslashes are converted to forward slashes
    /// - Trailing slashes are preserved for root paths only
    #[must_use]
    pub fn new(path: String) -> Self {
        Self {
            path: normalize_path(path),
            cached_hash: Cell::new(None),
        }
    }

    /// Returns the path as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Returns the final component of the path.
    ///
    /// Returns an empty string if the path ends with a separator or is empty.
    #[must_use]
    pub fn name(&self) -> &str {
        self.path.rsplit_once('/').map_or(self.path.as_str(), |(_, name)| name)
    }

    /// Returns the path without its final component (parent directory).
    ///
    /// For relative paths without a directory (like `file.txt`), returns `.`.
    /// Returns `None` only for the root path `/`.
    #[must_use]
    pub fn parent(&self) -> Option<&str> {
        if self.path == "/" {
            return None;
        }
        match self.path.rsplit_once('/') {
            Some((parent, _)) => Some(if parent.is_empty() { "/" } else { parent }),
            None => Some("."), // Relative path without directory component
        }
    }

    /// Returns the final component without its last suffix.
    ///
    /// If the name has multiple suffixes (e.g., "file.tar.gz"), only the
    /// last suffix is removed.
    #[must_use]
    pub fn stem(&self) -> &str {
        let name = self.name();
        if name.starts_with('.') && !name[1..].contains('.') {
            // Hidden file without extension (e.g., ".bashrc")
            return name;
        }
        name.rsplit_once('.').map_or(name, |(stem, _)| stem)
    }

    /// Returns the file extension (last suffix), including the leading dot.
    ///
    /// Returns an empty string if there is no extension.
    #[must_use]
    pub fn suffix(&self) -> &str {
        let name = self.name();
        if name.starts_with('.') && !name[1..].contains('.') {
            // Hidden file without extension (e.g., ".bashrc")
            return "";
        }
        name.rfind('.').map_or("", |idx| &name[idx..])
    }

    /// Returns all file extensions as a list of strings.
    ///
    /// Each suffix includes its leading dot. Returns an empty list if no extensions.
    #[must_use]
    pub fn suffixes(&self) -> Vec<&str> {
        let name = self.name();
        if name.is_empty() || name == "." || name == ".." {
            return Vec::new();
        }

        let start_idx = usize::from(name.starts_with('.'));
        let search_str = &name[start_idx..];

        let mut result = Vec::new();
        let mut pos = 0;
        while let Some(idx) = search_str[pos..].find('.') {
            let abs_idx = pos + idx;
            // Each suffix is from this dot to the end or next dot
            let suffix_end = search_str[abs_idx + 1..]
                .find('.')
                .map_or(search_str.len(), |next| abs_idx + 1 + next);
            result.push(&name[start_idx + abs_idx..start_idx + suffix_end]);
            pos = abs_idx + 1;
        }
        result
    }

    /// Returns the path components as a list of strings.
    ///
    /// Absolute paths start with "/" as the first component.
    #[must_use]
    pub fn parts(&self) -> Vec<&str> {
        if self.path.is_empty() {
            return Vec::new();
        }

        let mut parts = Vec::new();
        if self.path.starts_with('/') {
            parts.push("/");
            let rest = &self.path[1..];
            if !rest.is_empty() {
                parts.extend(rest.split('/').filter(|s| !s.is_empty()));
            }
        } else {
            parts.extend(self.path.split('/').filter(|s| !s.is_empty()));
        }
        parts
    }

    /// Returns `true` if the path is absolute (starts with `/`).
    #[must_use]
    pub fn is_absolute(&self) -> bool {
        self.path.starts_with('/')
    }

    /// Joins this path with another path component.
    ///
    /// If `other` is an absolute path, it replaces `self` entirely.
    #[must_use]
    pub fn joinpath(&self, other: &str) -> String {
        if other.starts_with('/') || self.path.is_empty() || self.path == "." {
            normalize_path(other.to_owned())
        } else if self.path.ends_with('/') {
            normalize_path(format!("{}{}", self.path, other))
        } else {
            normalize_path(format!("{}/{}", self.path, other))
        }
    }

    /// Returns a new path with the name changed.
    ///
    /// # Errors
    /// Returns an error if the path has no name or if the new name is empty.
    pub fn with_name(&self, name: &str) -> Result<String, String> {
        if name.is_empty() {
            return Err("Invalid name: empty string".to_owned());
        }
        if name.contains('/') {
            return Err(format!("Invalid name: {name:?} contains path separator"));
        }
        if self.name().is_empty() {
            return Err("Path has no name".to_owned());
        }

        if let Some(parent) = self.parent() {
            if parent == "/" {
                Ok(format!("/{name}"))
            } else if parent == "." {
                // Relative path without directory - just use the new name
                Ok(name.to_owned())
            } else {
                Ok(format!("{parent}/{name}"))
            }
        } else {
            Ok(name.to_owned())
        }
    }

    /// Returns a new path with the stem changed (keeps the suffix).
    ///
    /// # Errors
    /// Returns an error if the path has no name or if the new stem is empty.
    pub fn with_stem(&self, stem: &str) -> Result<String, String> {
        if stem.is_empty() {
            return Err("Invalid stem: empty string".to_owned());
        }
        if stem.contains('/') {
            return Err(format!("Invalid stem: {stem:?} contains path separator"));
        }
        if self.name().is_empty() {
            return Err("Path has no name".to_owned());
        }

        let suffix = self.suffix();
        let new_name = format!("{stem}{suffix}");
        self.with_name(&new_name)
    }

    /// Returns a new path with the suffix changed.
    ///
    /// If the suffix is empty, removes the existing suffix.
    /// If the suffix doesn't start with '.', it's added.
    pub fn with_suffix(&self, suffix: &str) -> Result<String, String> {
        if self.name().is_empty() {
            return Err("Path has no name".to_owned());
        }

        let suffix = if suffix.is_empty() || suffix.starts_with('.') {
            suffix.to_owned()
        } else {
            format!(".{suffix}")
        };

        if suffix.contains('/') {
            return Err(format!("Invalid suffix: {suffix:?} contains path separator"));
        }

        let stem = self.stem();
        let new_name = format!("{stem}{suffix}");
        self.with_name(&new_name)
    }

    /// Returns the path as a POSIX string (forward slashes).
    ///
    /// Since paths are already stored in POSIX format, this just returns the path.
    #[must_use]
    pub fn as_posix(&self) -> &str {
        &self.path
    }

    /// Creates a `Path` from the `Path()` constructor call.
    ///
    /// Accepts zero or more path segments that are joined together.
    /// - `Path()` returns `Path('.')`
    /// - `Path('a')` returns `Path('a')`
    /// - `Path('a', 'b', 'c')` returns `Path('a/b/c')`
    /// - If an absolute path appears, it replaces everything before it.
    pub fn init(vm: &mut VM<'_, impl ResourceTracker>, args: ArgValues) -> RunResult<Value> {
        let pos_args = args.into_pos_only("Path", vm.heap)?;
        defer_drop!(pos_args, vm);

        let path = match pos_args.as_slice() {
            [] => {
                // No arguments, return Path('.')
                Self::new(".".to_owned())
            }
            [single] => {
                // Single argument, just convert to Path
                Self::new(extract_path_string(single, vm)?.to_owned())
            }
            [first_arg, rest @ ..] => {
                let base = Self::new(extract_path_string(first_arg, vm)?.to_owned());
                fold_joinpath(base, rest, vm)?
            }
        };
        Ok(Value::Ref(vm.heap.allocate(HeapData::Path(path))?))
    }
}

/// Extracts a string from a Value for use as a path.
fn extract_path_string<'a>(val: &Value, vm: &'a VM<'_, impl ResourceTracker>) -> RunResult<&'a str> {
    match val {
        Value::InternString(string_id) => Ok(vm.interns.get_str(*string_id)),
        Value::Ref(heap_id) => match vm.heap.get(*heap_id) {
            HeapData::Str(s) => Ok(s.as_str()),
            HeapData::Path(p) => Ok(p.as_str()),
            _ => Err(ExcType::type_error(format!(
                "expected str or Path, got {}",
                val.py_type_name(vm)
            ))),
        },
        _ => Err(ExcType::type_error(format!(
            "expected str or Path, got {}",
            val.py_type_name(vm)
        ))),
    }
}

fn fold_joinpath(mut path: Path, parts: &[Value], vm: &VM<'_, impl ResourceTracker>) -> RunResult<Path> {
    for part in parts {
        path = Path::new(path.joinpath(extract_path_string(part, vm)?));
    }
    Ok(path)
}

/// Handles the `/` operator for Path objects (path concatenation).
///
/// In Python, `Path('/usr') / 'bin'` produces `Path('/usr/bin')`.
pub(crate) fn path_div(
    path_id: HeapId,
    other: &Value,
    heap: &Heap<impl ResourceTracker>,
    interns: &Interns,
) -> RunResult<Option<Value>> {
    // Extract the right-hand side as a string
    let other_str = match other {
        Value::InternString(string_id) => interns.get_str(*string_id).to_owned(),
        Value::Ref(other_id) => match heap.get(*other_id) {
            HeapData::Str(s) => s.as_str().to_owned(),
            HeapData::Path(p) => p.as_str().to_owned(),
            _ => return Ok(None),
        },
        _ => return Ok(None),
    };

    // Get the path string
    let path_str = match heap.get(path_id) {
        HeapData::Path(p) => p.as_str().to_owned(),
        _ => return Ok(None),
    };

    // Perform path concatenation
    let result = Path::new(path_str).joinpath(&other_str);
    Ok(Some(Value::Ref(heap.allocate(HeapData::Path(Path::new(result)))?)))
}

/// Normalizes a path string to POSIX format, matching CPython's `pathlib.PurePosixPath`.
///
/// - Converts backslashes to forward slashes
/// - Removes `.` components (e.g. `/a/./b` → `/a/b`)
/// - Collapses consecutive slashes (e.g. `//a///b` → `/a/b`)
/// - Removes trailing slashes (except for root "/")
/// - Does NOT resolve `..` components (that requires I/O for symlinks)
fn normalize_path(mut path: String) -> String {
    // Convert backslashes to forward slashes
    if path.contains('\\') {
        path = path.replace('\\', "/");
    }

    // Fast path: no `.` component and no consecutive or trailing slashes
    if !path.contains("/.") && !path.contains("//") && !path.starts_with("./") {
        // Still strip trailing slashes
        while path.len() > 1 && path.ends_with('/') {
            path.pop();
        }
        return path;
    }

    let is_absolute = path.starts_with('/');
    let mut components: Vec<&str> = Vec::new();

    for part in path.split('/') {
        match part {
            "" | "." => {} // skip empty segments (from consecutive/trailing slashes) and "."
            other => components.push(other),
        }
    }

    if components.is_empty() {
        return if is_absolute { "/".to_owned() } else { ".".to_owned() };
    }

    let mut result = String::with_capacity(path.len());
    if is_absolute {
        result.push('/');
    }
    for (i, comp) in components.iter().enumerate() {
        if i > 0 {
            result.push('/');
        }
        result.push_str(comp);
    }
    result
}

impl Path {
    /// Resolves a known attribute by its `StaticStrings` variant.
    ///
    /// Returns `Ok(Some(value))` for recognized property names (`name`, `parent`,
    /// `stem`, `suffix`, `suffixes`, `parts`), or `Ok(None)` if the variant doesn't
    /// correspond to a Path attribute. Used by `py_getattr` to share logic between
    /// the interned fast path and the heap string slow path.
    pub(crate) fn getattr_by_static(
        &self,
        ss: StaticStrings,
        heap: &Heap<impl ResourceTracker>,
    ) -> RunResult<Option<Value>> {
        let v = match ss {
            StaticStrings::Name => allocate_string(self.name(), heap)?,
            StaticStrings::Parent => {
                if let Some(parent) = self.parent() {
                    let parent_path = Self::new(parent.to_owned());
                    Value::Ref(heap.allocate(HeapData::Path(parent_path))?)
                } else {
                    // Return self when there's no parent (root or relative path)
                    let same_path = Self::new(self.as_str().to_owned());
                    Value::Ref(heap.allocate(HeapData::Path(same_path))?)
                }
            }
            StaticStrings::Stem => allocate_string(self.stem(), heap)?,
            StaticStrings::Suffix => allocate_string(self.suffix(), heap)?,
            StaticStrings::Suffixes => {
                use crate::types::List;

                let suffixes = self.suffixes();
                let mut items = Vec::with_capacity(suffixes.len());
                for suffix in suffixes {
                    items.push(allocate_string(suffix, heap)?);
                }
                Value::Ref(heap.allocate(HeapData::List(List::new(items)))?)
            }
            StaticStrings::Parts => {
                let parts = self.parts();
                let mut items = SmallVec::with_capacity(parts.len());
                for part in parts {
                    items.push(allocate_string(part, heap)?);
                }
                allocate_tuple(items, heap)?
            }
            _ => return Ok(None),
        };
        Ok(Some(v))
    }
}

impl<'h> PyTrait<'h> for HeapRead<'h, Path> {
    fn py_type(&self, _vm: &VM<'h, impl ResourceTracker>) -> Type {
        Type::Path
    }

    fn py_len(&self, _vm: &VM<'h, impl ResourceTracker>) -> Option<usize> {
        // Paths don't have a length in Python
        None
    }

    fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h, impl ResourceTracker>) -> RunResult<Option<bool>> {
        let Some(HeapReadOutput::Path(other)) = other.read_heap(vm) else {
            return Ok(None);
        };
        Ok(Some(self.get(vm.heap).path == other.get(vm.heap).path))
    }

    fn py_hash(&self, _self_id: HeapId, vm: &mut VM<'h, impl ResourceTracker>) -> RunResult<Option<HashValue>> {
        let p = self.get(vm.heap);
        if let Some(cached) = p.cached_hash.get() {
            return Ok(Some(cached));
        }
        let mut hasher = DefaultHasher::new();
        p.as_str().hash(&mut hasher);
        let hash = HashValue::new(hasher.finish());
        p.cached_hash.set(Some(hash));
        Ok(Some(hash))
    }

    fn py_bool(&self, _vm: &mut VM<'h, impl ResourceTracker>) -> bool {
        // Paths are always truthy (even empty paths)
        true
    }

    fn py_repr_fmt(
        &self,
        f: &mut impl Write,
        vm: &mut VM<'h, impl ResourceTracker>,
        _heap_ids: &mut LazyHeapSet,
    ) -> RunResult<()> {
        // Format like: PosixPath('/usr/bin')
        Ok(write!(f, "PosixPath('{}')", self.get(vm.heap).path)?)
    }

    /// Handles attribute calls on Path objects, including both pure methods (no I/O)
    /// and OS methods that require host system access.
    ///
    /// OS methods (exists, read_text, etc.) are detected via `OsFunction::try_from`
    /// and returned as `CallResult::OsCall` for the VM to yield to the host.
    /// Pure methods (is_absolute, joinpath, etc.) are handled directly.
    fn py_call_attr(
        &mut self,
        self_id: HeapId,
        vm: &mut VM<'h, impl ResourceTracker>,
        attr: &EitherStr,
        args: ArgValues,
    ) -> RunResult<CallResult> {
        let Some(method) = attr.static_string() else {
            args.drop_with_heap(vm);
            return Err(ExcType::attribute_error(Type::Path, attr.as_str(vm.interns)));
        };

        // Check if this is an OS method that requires host system access.
        //
        // Pre-flight via `is_path_os_method` lets us extract the path string
        // and commit ownership of `args` to the builder; the builder yields
        // an `OsFunctionCall` variant with the typed args struct populated.
        if is_path_os_method(method) {
            let path = MontyPath::new(self.get(vm.heap).as_str().to_owned());
            // SAFETY: builder owns `args` and is responsible for dropping it
            // on every error path; `self_id` is a separate heap entry that
            // we don't transfer here.
            return match build_path_os_call(method, path, args, vm)? {
                Some(call) => Ok(CallResult::OsCall(call)),
                None => unreachable!("is_path_os_method gates the call"),
            };
        }

        // Pure methods (no I/O)
        let value = match method {
            StaticStrings::IsAbsolute => {
                args.check_zero_args("is_absolute", vm.heap)?;
                Ok(Value::Bool(self.get(vm.heap).is_absolute()))
            }
            StaticStrings::Joinpath => {
                let pos_args = args.into_pos_only("joinpath", vm.heap)?;
                defer_drop!(pos_args, vm);
                let path = fold_joinpath(self.get(vm.heap).clone(), pos_args.as_slice(), vm)?;
                Ok(Value::Ref(vm.heap.allocate(HeapData::Path(path))?))
            }
            StaticStrings::WithName => {
                let name_val = args.get_one_arg("with_name", vm.heap)?;
                defer_drop!(name_val, vm);
                let name = extract_path_string(name_val, vm)?.to_owned();
                let result = self
                    .get(vm.heap)
                    .with_name(&name)
                    .map_err(|e| SimpleException::new_msg(ExcType::ValueError, &e))?;
                Ok(Value::Ref(vm.heap.allocate(HeapData::Path(Path::new(result)))?))
            }
            StaticStrings::WithStem => {
                let stem_val = args.get_one_arg("with_stem", vm.heap)?;
                defer_drop!(stem_val, vm);
                let stem = extract_path_string(stem_val, vm)?.to_owned();
                let result = self
                    .get(vm.heap)
                    .with_stem(&stem)
                    .map_err(|e| SimpleException::new_msg(ExcType::ValueError, &e))?;
                Ok(Value::Ref(vm.heap.allocate(HeapData::Path(Path::new(result)))?))
            }
            StaticStrings::WithSuffix => {
                let suffix_val = args.get_one_arg("with_suffix", vm.heap)?;
                defer_drop!(suffix_val, vm);
                let suffix = extract_path_string(suffix_val, vm)?.to_owned();
                let result = self
                    .get(vm.heap)
                    .with_suffix(&suffix)
                    .map_err(|e| SimpleException::new_msg(ExcType::ValueError, &e))?;
                Ok(Value::Ref(vm.heap.allocate(HeapData::Path(Path::new(result)))?))
            }
            StaticStrings::AsPosix | StaticStrings::Fspath => {
                args.check_zero_args(method.into(), vm.heap)?;
                Ok(allocate_string(self.get(vm.heap).as_posix(), vm.heap)?)
            }
            StaticStrings::Open => {
                // `Path.open(mode='r', ...)` is `open(self, mode, ...)` with
                // `self` prepended as the implicit `file` argument. Reuses
                // `builtin_open`'s mode/kwarg validation (including rejection
                // of `+`/`x` modes and non-default `buffering`/`encoding`/
                // `errors`/`newline`) so the two entry points stay in sync.
                //
                // The `inc_ref` is required because the prepended `Value::Ref`
                // is dropped by `builtin_open` via `defer_drop!` once the path
                // string has been extracted, balancing the refcount.
                vm.heap.inc_ref(self_id);
                let args = args.prepend(Value::Ref(self_id));
                return builtin_open(vm, args);
            }
            _ => {
                args.drop_with_heap(vm);
                return Err(ExcType::attribute_error(Type::Path, attr.as_str(vm.interns)));
            }
        };
        value.map(CallResult::Value)
    }

    fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h, impl ResourceTracker>) -> RunResult<Option<CallResult>> {
        // Fast path: interned strings can be matched by ID without string comparison
        if let Some(ss) = attr.static_string() {
            if let Some(v) = self.get(vm.heap).getattr_by_static(ss, vm.heap)? {
                return Ok(Some(CallResult::Value(v)));
            }
            return Err(ExcType::attribute_error(Type::Path, attr.as_str(vm.interns)));
        }
        // Slow path: heap-allocated strings need string comparison
        let attr_str = attr.as_str(vm.interns);
        let ss = match attr_str {
            "name" => StaticStrings::Name,
            "parent" => StaticStrings::Parent,
            "stem" => StaticStrings::Stem,
            "suffix" => StaticStrings::Suffix,
            "suffixes" => StaticStrings::Suffixes,
            "parts" => StaticStrings::Parts,
            _ => return Err(ExcType::attribute_error(Type::Path, attr_str)),
        };
        let v = self
            .get(vm.heap)
            .getattr_by_static(ss, vm.heap)?
            .expect("matched attribute must produce a value");
        Ok(Some(CallResult::Value(v)))
    }
}

impl HeapItem for Path {
    fn py_estimate_size(&self) -> usize {
        mem::size_of::<Self>() + self.path.capacity()
    }

    fn py_dec_ref_ids(&mut self, _stack: &mut Vec<HeapId>) {
        // Path doesn't contain heap references, nothing to do
    }
}