laburnum 1.17.1

An LSP framework for building language servers and compilers, powered by an incremental query tree with content-addressed storage, task-based dataflow, and parallel queries.
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  percent_encoding::AsciiSet,
  serde::{
    Deserialize,
    Serialize,
    de::Error,
  },
  std::{
    borrow::Cow,
    hash::Hash,
    ops::{
      Deref,
      DerefMut,
    },
    path::{
      Path,
      PathBuf,
    },
    str::FromStr,
  },
};

/// Newtype struct around `fluent_uri::Uri<String>` with serialization
/// implementations that use `as_str()` and '`from_str()`' respectively.
#[derive(Clone)]
pub struct Uri {
  inner:          fluent_uri::Uri<String>,
  relative_start: Option<u16>,
}

impl Serialize for Uri {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: serde::Serializer,
  {
    self.as_str().serialize(serializer)
  }
}

impl<'de> Deserialize<'de> for Uri {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    let string = String::deserialize(deserializer)?;
    fluent_uri::Uri::<String>::parse(string)
      .map(|inner| {
        Uri {
          inner,
          relative_start: None,
        }
      })
      .map_err(|err| Error::custom(err.to_string()))
  }
}

impl std::fmt::Display for Uri {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    self.as_str().fmt(f)
  }
}

impl std::fmt::Debug for Uri {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    self.as_str().fmt(f)
  }
}

impl From<fluent_uri::Uri<String>> for Uri {
  fn from(uri: fluent_uri::Uri<String>) -> Self {
    Self {
      inner:          uri,
      relative_start: None,
    }
  }
}

impl Ord for Uri {
  fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    self.as_str().cmp(other.as_str())
  }
}

impl PartialOrd for Uri {
  fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    Some(self.cmp(other))
  }
}

impl FromStr for Uri {
  type Err = fluent_uri::error::ParseError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    fluent_uri::Uri::parse(s).map(|uri| {
      Self {
        inner:          uri.to_owned(),
        relative_start: None,
      }
    })
  }
}

impl Deref for Uri {
  type Target = fluent_uri::Uri<String>;

  fn deref(&self) -> &Self::Target {
    &self.inner
  }
}

impl DerefMut for Uri {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.inner
  }
}

// TOUCH-UP: `PartialEq`, `Eq` and `Hash` could all be derived
// if and when the respective implementations get merged upstream:
// https://github.com/yescallop/fluent-uri-rs/pull/9
impl PartialEq for Uri {
  fn eq(&self, other: &Self) -> bool {
    self.as_str() == other.as_str()
  }
}

impl Eq for Uri {}

impl Hash for Uri {
  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
    self.as_str().hash(state);
  }
}

#[cfg(not(windows))]
pub use std::fs::canonicalize as strict_canonicalize;

/// On Windows, rewrites the wide path prefix `\\?\C:` to `C:`
/// Source: https://stackoverflow.com/a/70970317
#[inline]
#[cfg(windows)]
fn strict_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
  use std::io;

  fn impl_(path: PathBuf) -> std::io::Result<PathBuf> {
    let head = path
      .components()
      .next()
      .ok_or(io::Error::other("empty path"))?;
    let disk_;
    let head = if let std::path::Component::Prefix(prefix) = head {
      if let std::path::Prefix::VerbatimDisk(disk) = prefix.kind() {
        disk_ = format!("{}:", disk as char);
        Path::new(&disk_)
          .components()
          .next()
          .ok_or(io::Error::other("failed to parse disk component"))?
      } else {
        head
      }
    } else {
      head
    };
    Ok(
      std::iter::once(head)
        .chain(path.components().skip(1))
        .collect(),
    )
  }

  let canon = std::fs::canonicalize(path)?;
  impl_(canon)
}

#[cfg(windows)]
fn capitalize_drive_letter(path: &str) -> String {
  if path.len() >= 2 && path.chars().nth(1) == Some(':') {
    let mut chars = path.chars();
    if let Some(first_char) = chars.next() {
      let drive_letter = first_char.to_ascii_uppercase();
      let rest: String = chars.collect();
      format!("{}{}", drive_letter, rest)
    } else {
      path.to_string()
    }
  } else {
    path.to_string()
  }
}

const ASCII_SET: AsciiSet =
  // RFC3986 allows only alphanumeric characters, `-`, `.`, `_`, and `~` in the
  // path.
  percent_encoding::NON_ALPHANUMERIC
        .remove(b'-')
        .remove(b'.')
        .remove(b'_')
        .remove(b'~')
        // we do not want path separators to be percent-encoded
        .remove(b'/');

/// Provide methods to [`Uri`] to fill blanks left by
/// `fluent_uri` (the underlying type) especially when converting to and from
/// file paths.
impl Uri {
  /// Parse a URI string into a `Uri`.
  ///
  /// This is a convenience method that delegates to `FromStr`.
  pub fn parse(s: &str) -> Result<Self, fluent_uri::error::ParseError> {
    Self::from_str(s)
  }

  /// Get the relative path portion of the URI if a root path has been set.
  ///
  /// Returns an error if `set_root_path()` has not been called.
  pub fn relative_path(&self) -> Result<&str, &'static str> {
    match self.relative_start {
      | Some(start) => Ok(&self.as_str()[start as usize..]),
      | None => Err("No root path has been set for this URI"),
    }
  }

  /// Set the root path for this URI to enable relative path extraction.
  ///
  /// Attempts to find the root path as a prefix of this URI.
  /// If found, stores the offset where the relative path begins.
  ///
  /// Returns `true` if the root was found and set, `false` otherwise.
  pub fn set_root_path(&mut self, root: &str) -> bool {
    let uri_str = self.as_str();
    if let Some(offset) = uri_str.find(root) {
      let mut relative_offset = offset + root.len();

      // Skip leading slash if present
      if uri_str.as_bytes().get(relative_offset) == Some(&b'/') {
        relative_offset += 1;
      }

      if relative_offset <= u16::MAX as usize {
        self.relative_start = Some(relative_offset as u16);
        return true;
      }
    }
    false
  }

  /// Join a URI reference to this base URI.
  ///
  /// This method performs URI resolution as defined in RFC 3986.
  ///
  /// Returns `None` if the join operation fails.
  /// Use with `.ok_or_else()` or `.unwrap_or_else()` for error handling.
  pub fn join(&self, reference: &str) -> Option<Self> {
    let reference_uri = fluent_uri::UriRef::parse(reference).ok()?;
    let resolved = reference_uri.resolve_against(&self.inner).ok()?;
    Some(Self {
      inner:          resolved,
      relative_start: None,
    })
  }

  /// Join a URI reference to this base URI, returning a Result.
  ///
  /// This is similar to `join()` but returns a Result for better error
  /// handling.
  pub fn join_result(&self, reference: &str) -> Result<Self, String> {
    self
      .join(reference)
      .ok_or_else(|| format!("Failed to join URI reference: {}", reference))
  }

  /// Get the path component of the URI as a borrowed `Path`.
  ///
  /// This returns the path component directly as a string slice.
  /// For file URIs that need proper conversion, use `to_file_path()` instead.
  #[must_use]
  pub fn as_path(&self) -> &Path {
    Path::new(self.path().as_str())
  }

  /// Get the path component as a string slice.
  ///
  /// This is a convenience method to get the path as &str without going through
  /// EStr.
  #[must_use]
  pub fn path_str(&self) -> &str {
    self.path().as_str()
  }

  /// Returns an iterator over the path segments.
  ///
  /// Similar to url::Url::path_segments(), but returns a simpler iterator.
  pub fn path_segments(&self) -> Option<impl DoubleEndedIterator<Item = &str>> {
    let path = self.path().as_str();
    if path.is_empty() || !path.starts_with('/') {
      return None;
    }
    Some(path.split('/').filter(|s| !s.is_empty()))
  }

  /// Set the path component of the URI.
  ///
  /// Returns a new Uri with the updated path.
  pub fn set_path(&mut self, path: &str) {
    let new_uri_str = format!(
      "{}://{}{}{}{}",
      self.scheme().as_str(),
      self.authority().map(|a| a.as_str()).unwrap_or(""),
      path,
      self
        .query()
        .map(|q| format!("?{}", q.as_str()))
        .unwrap_or_default(),
      self
        .fragment()
        .map(|f| format!("#{}", f.as_str()))
        .unwrap_or_default()
    );
    if let Ok(new_uri) = Self::from_str(&new_uri_str) {
      *self = new_uri;
    }
  }

  /// Returns a new URI representing the parent folder of this URI.
  ///
  /// For file URIs, this converts to a file path, gets the parent directory,
  /// and converts back to a URI. This handles percent-encoding, Windows paths,
  /// and other edge cases properly.
  ///
  /// Returns `None` if:
  /// - The URI cannot be converted to a file path
  /// - The path has no parent (e.g., root directory)
  /// - The parent path cannot be converted back to a URI
  ///
  /// # Examples
  ///
  /// ```
  /// use {
  ///   laburnum::Uri,
  ///   std::str::FromStr,
  /// };
  ///
  /// let uri = Uri::from_str("file:///home/user/project/file.txt").unwrap();
  /// let parent = uri.parent_folder().unwrap();
  /// assert_eq!(parent.as_str(), "file:///home/user/project");
  /// ```
  #[must_use]
  pub fn parent_folder(&self) -> Option<Self> {
    let path = self.path().as_str();

    // Find the last slash that isn't trailing
    let path_trimmed = path.trim_end_matches('/');
    let last_slash = path_trimmed.rfind('/')?;

    // Don't return empty parent path
    if last_slash == 0 {
      return None;
    }

    let parent_path = &path_trimmed[..last_slash];

    // Reconstruct URI preserving scheme and authority
    let scheme = self.scheme();
    let authority = self.authority().map(|a| a.as_str());

    let uri_str = match authority {
      | Some(auth) => format!("{scheme}://{auth}{parent_path}"),
      | None => format!("{scheme}:{parent_path}"),
    };

    Self::parse(&uri_str).ok()
  }

  /// Make a URI relative to a base URI.
  ///
  /// Returns the relative path if this URI is a child of the base URI.
  pub fn make_relative(&self, other: &Uri) -> Option<String> {
    if self.scheme() != other.scheme() {
      return None;
    }

    let self_auth = self.authority().map(|a| a.as_str());
    let other_auth = other.authority().map(|a| a.as_str());
    if self_auth != other_auth {
      return None;
    }

    let base_path = other.path().as_str();
    let self_path = self.path().as_str();

    if !self_path.starts_with(base_path) {
      return None;
    }

    let relative = &self_path[base_path.len()..];
    Some(relative.trim_start_matches('/').to_string())
  }

  /// Assuming the Uri is in the `file` scheme or similar,
  /// convert its path to an absolute `std::path::Path`.
  ///
  /// **Note:** This does not actually check the Uri’s `scheme`, and may
  /// give nonsensical results for other schemes. It is the user’s
  /// responsibility to check the Uri’s scheme before calling this.
  ///
  /// e.g. `Uri("file:///etc/passwd")` becomes `PathBuf("/etc/passwd")`
  #[must_use]
  pub fn to_file_path(&self) -> Option<Cow<'_, Path>> {
    let path_str = self.path().decode().into_string_lossy();
    if path_str.is_empty() {
      return None;
    }

    let path = match path_str {
      | Cow::Borrowed(ref_) => Cow::Borrowed(Path::new(ref_)),
      | Cow::Owned(owned) => Cow::Owned(PathBuf::from(owned)),
    };

    if cfg!(windows) {
      let auth_host =
        self.authority().map(|auth| auth.host()).unwrap_or_default();

      if auth_host.is_empty() {
        // very high chance this is a `file:///c:/...` uri
        // in which case the path will include a leading slash we
        // need to remove to get `c:/...`
        let host = path.to_string_lossy();
        let host = host.get(1..)?;
        return Some(Cow::Owned(PathBuf::from(host)));
      }

      Some(Cow::Owned(
        // `file://server/...` becomes `server:/`
        Path::new(&format!("{auth_host}:"))
          .components()
          .chain(path.components())
          .collect(),
      ))
    } else {
      Some(path)
    }
  }

  /// Returns the filename portion of the URI path, or an empty string if none.
  pub fn file(&self) -> &str {
    self.path().as_str().rsplit('/').next().unwrap_or("")
  }

  /// Convert a file path to a [`Uri`].
  ///
  /// Returns `None` if the file does not exist.
  pub fn from_file_path<A: AsRef<Path>>(path: A) -> Option<Self> {
    let path = path.as_ref();

    let fragment = if path.is_absolute() {
      Cow::Borrowed(path)
    } else {
      match strict_canonicalize(path) {
        | Ok(path) => Cow::Owned(path),
        | Err(_) => return None,
      }
    };

    #[cfg(windows)]
    let raw_uri = {
      // we want to parse a triple-slash path for Windows paths
      // it's a shorthand for `file://localhost/C:/Windows` with the `localhost` omitted.
      // We encode the driver Letter `C:` as well. LSP Specification allows it.
      // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri
      format!(
        "file:///{}",
        percent_encoding::utf8_percent_encode(
          &capitalize_drive_letter(
            &fragment.to_string_lossy().replace('\\', "/")
          ),
          &ASCII_SET
        )
      )
    };

    #[cfg(not(windows))]
    let raw_uri = {
      format!(
        "file://{}",
        percent_encoding::utf8_percent_encode(
          &fragment.to_string_lossy(),
          &ASCII_SET
        )
      )
    };

    Self::from_str(&raw_uri).ok()
  }
}

#[cfg(test)]
mod tests {
  use {
    super::*,
    fluent_uri::encoding::EStr,
    std::{
      path::{
        Path,
        PathBuf,
      },
      str::FromStr,
    },
  };

  #[test]
  fn deref_mut_fragment_add() {
    let mut uri = Uri::from_str("https://www.example.com").unwrap();
    uri.set_fragment(Some(EStr::new_or_panic("L11")));
    assert_eq!(uri.as_str(), "https://www.example.com#L11");
  }

  fn with_schema(path: &str) -> String {
    const EXPECTED_SCHEMA: &str =
      if cfg!(windows) { "file:///" } else { "file://" };
    format!("{EXPECTED_SCHEMA}{path}")
  }

  #[test]
  #[cfg(windows)]
  fn test_idempotent_canonicalization() {
    let lhs = strict_canonicalize(Path::new(".")).unwrap();
    let rhs = strict_canonicalize(&lhs).unwrap();
    assert_eq!(lhs, rhs);
  }

  #[test]
  #[cfg(unix)]
  fn test_path_roundtrip_conversion() {
    let sources = [
      strict_canonicalize(Path::new(".")).unwrap(),
      PathBuf::from("/some/path/to/file.txt"),
      PathBuf::from("/some/path/to/file with spaces.txt"),
      PathBuf::from("/some/path/[[...rest]]/file.txt"),
      PathBuf::from("/some/path/to/файл.txt"),
      PathBuf::from("/some/path/to/文件.txt"),
    ];

    for source in sources {
      let conv = Uri::from_file_path(&source).unwrap();
      let roundtrip = conv.to_file_path().unwrap();
      assert_eq!(source, roundtrip, "conv={conv:?}");
    }
  }

  #[test]
  #[cfg(windows)]
  fn test_path_roundtrip_conversion() {
    let sources = [
      strict_canonicalize(Path::new(".")).unwrap(),
      PathBuf::from("C:\\some\\path\\to\\file.txt"),
      PathBuf::from("C:\\some\\path\\to\\file with spaces.txt"),
      PathBuf::from("C:\\some\\path\\[[...rest]]\\file.txt"),
      PathBuf::from("C:\\some\\path\\to\\файл.txt"),
      PathBuf::from("C:\\some\\path\\to\\文件.txt"),
    ];

    for source in sources {
      let conv = Uri::from_file_path(&source).unwrap();
      let roundtrip = conv.to_file_path().unwrap();
      assert_eq!(source, roundtrip, "conv={conv:?}");
    }
  }

  #[test]
  #[cfg(windows)]
  fn test_windows_uri_roundtrip_conversion() {
    use std::str::FromStr;

    let uris = [
      Uri::from_str("file:///C:/some/path/to/file.txt").unwrap(),
      Uri::from_str("file:///c:/some/path/to/file.txt").unwrap(),
      Uri::from_str("file:///c%3A/some/path/to/file.txt").unwrap(),
    ];

    let final_uri =
      Uri::from_str("file:///C%3A/some/path/to/file.txt").unwrap();

    for uri in uris {
      let path = uri.to_file_path().unwrap();
      assert_eq!(
        &path,
        Path::new("C:\\some\\path\\to\\file.txt"),
        "uri={uri:?}"
      );

      let conv = Uri::from_file_path(&path).unwrap();

      assert_eq!(
        final_uri,
        conv,
        "path={path:?} left={} right={}",
        final_uri.as_str(),
        conv.as_str()
      );
    }
  }

  #[test]
  #[cfg(unix)]
  fn test_path_to_uri() {
    let paths = [
      PathBuf::from("/some/path/to/file.txt"),
      PathBuf::from("/some/path/to/file with spaces.txt"),
      PathBuf::from("/some/path/[[...rest]]/file.txt"),
      PathBuf::from("/some/path/to/файл.txt"),
      PathBuf::from("/some/path/to/文件.txt"),
    ];

    let expected = [
      with_schema("/some/path/to/file.txt"),
      with_schema("/some/path/to/file%20with%20spaces.txt"),
      with_schema("/some/path/%5B%5B...rest%5D%5D/file.txt"),
      with_schema("/some/path/to/%D1%84%D0%B0%D0%B9%D0%BB.txt"),
      with_schema("/some/path/to/%E6%96%87%E4%BB%B6.txt"),
    ];

    for (path, expected) in paths.iter().zip(expected) {
      let uri = Uri::from_file_path(path).unwrap();
      assert_eq!(uri.to_string(), expected);
    }
  }

  #[test]
  #[cfg(windows)]
  fn test_path_to_uri_windows() {
    let paths = [
      PathBuf::from("C:\\some\\path\\to\\file.txt"),
      PathBuf::from("C:\\some\\path\\to\\file with spaces.txt"),
      PathBuf::from("C:\\some\\path\\[[...rest]]\\file.txt"),
      PathBuf::from("C:\\some\\path\\to\\файл.txt"),
      PathBuf::from("C:\\some\\path\\to\\文件.txt"),
    ];

    // yes we encode `:` too, LSP allows it
    // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri
    let expected = [
      with_schema("C%3A/some/path/to/file.txt"),
      with_schema("C%3A/some/path/to/file%20with%20spaces.txt"),
      with_schema("C%3A/some/path/%5B%5B...rest%5D%5D/file.txt"),
      with_schema("C%3A/some/path/to/%D1%84%D0%B0%D0%B9%D0%BB.txt"),
      with_schema("C%3A/some/path/to/%E6%96%87%E4%BB%B6.txt"),
    ];

    for (path, expected) in paths.iter().zip(expected) {
      let uri = Uri::from_file_path(path).unwrap();
      assert_eq!(uri.to_string(), expected);
    }
  }

  #[test]
  fn test_invalid_uri_on_windows() {
    let uri = Uri::from_str("file://").unwrap();
    let path = uri.to_file_path();
    assert!(path.is_none());
  }

  #[test]
  fn test_join() {
    let base = Uri::from_str("file:///root/").unwrap();
    let joined = base.join("subdir/file.txt").unwrap();
    assert_eq!(joined.as_str(), "file:///root/subdir/file.txt");

    let base2 = Uri::from_str("file:///root").unwrap();
    let joined2 = base2.join("file.txt").unwrap();
    assert_eq!(joined2.as_str(), "file:///file.txt");

    let base3 = Uri::from_str("https://example.com/path/").unwrap();
    let joined3 = base3.join("../other.html").unwrap();
    assert_eq!(joined3.as_str(), "https://example.com/other.html");
  }

  #[test]
  #[cfg(unix)]
  fn test_parent_folder_unix() {
    // Basic file in nested directory
    let uri = Uri::from_str("file:///home/user/project/file.txt").unwrap();
    let parent = uri.parent_folder().unwrap();
    assert_eq!(parent.as_str(), "file:///home/user/project");

    // Get parent of parent
    let grandparent = parent.parent_folder().unwrap();
    assert_eq!(grandparent.as_str(), "file:///home/user");

    // File with spaces in path
    let uri_spaces =
      Uri::from_str("file:///home/user/my%20project/file.txt").unwrap();
    let parent_spaces = uri_spaces.parent_folder().unwrap();
    assert_eq!(parent_spaces.as_str(), "file:///home/user/my%20project");

    // File with unicode in path
    let uri_unicode =
      Uri::from_str("file:///home/user/%E6%96%87%E4%BB%B6/test.txt").unwrap();
    let parent_unicode = uri_unicode.parent_folder().unwrap();
    assert_eq!(
      parent_unicode.as_str(),
      "file:///home/user/%E6%96%87%E4%BB%B6"
    );

    // Root level file - should return root
    let uri_root = Uri::from_str("file:///file.txt").unwrap();
    let parent_root = uri_root.parent_folder();
    // Root "/" has no parent in the traditional sense
    assert!(
      parent_root.is_none() || parent_root.unwrap().as_str() == "file:///"
    );
  }

  #[test]
  #[cfg(windows)]
  fn test_parent_folder_windows() {
    // Basic file in nested directory
    let uri =
      Uri::from_str("file:///C%3A/Users/user/project/file.txt").unwrap();
    let parent = uri.parent_folder().unwrap();
    assert_eq!(parent.as_str(), "file:///C%3A/Users/user/project");

    // Get parent of parent
    let grandparent = parent.parent_folder().unwrap();
    assert_eq!(grandparent.as_str(), "file:///C%3A/Users/user");

    // File with spaces in path
    let uri_spaces =
      Uri::from_str("file:///C%3A/Users/user/my%20project/file.txt").unwrap();
    let parent_spaces = uri_spaces.parent_folder().unwrap();
    assert_eq!(
      parent_spaces.as_str(),
      "file:///C%3A/Users/user/my%20project"
    );
  }

  #[test]
  fn test_parent_folder_sibling_comparison() {
    // Two files in the same folder should have the same parent
    let file1 = Uri::from_str("file:///project/src/main.rs").unwrap();
    let file2 = Uri::from_str("file:///project/src/lib.rs").unwrap();

    let parent1 = file1.parent_folder().unwrap();
    let parent2 = file2.parent_folder().unwrap();

    assert_eq!(parent1, parent2);

    // Files in different folders should have different parents
    let file3 = Uri::from_str("file:///project/tests/test.rs").unwrap();
    let parent3 = file3.parent_folder().unwrap();

    assert_ne!(parent1, parent3);
  }

  #[test]
  fn test_file_returns_filename() {
    let uri =
      Uri::from_str("file:///home/user/project/gold.bld").unwrap();
    assert_eq!(uri.file(), "gold.bld");
  }

  #[test]
  fn test_file_workspace_manifest() {
    let uri =
      Uri::from_str("file:///home/user/project/workspace.bld").unwrap();
    assert_eq!(uri.file(), "workspace.bld");
  }

  #[test]
  fn test_file_nested_path() {
    let uri =
      Uri::from_str("file:///a/b/c/d/file.txt").unwrap();
    assert_eq!(uri.file(), "file.txt");
  }

  #[test]
  fn test_file_root_file() {
    let uri = Uri::from_str("file:///file.txt").unwrap();
    assert_eq!(uri.file(), "file.txt");
  }

  #[test]
  fn test_file_trailing_slash() {
    let uri =
      Uri::from_str("file:///home/user/project/").unwrap();
    // Trailing slash means the last segment is empty
    assert_eq!(uri.file(), "");
  }

  #[test]
  fn test_file_no_path() {
    let uri = Uri::from_str("file://").unwrap();
    assert_eq!(uri.file(), "");
  }

  #[test]
  fn test_file_percent_encoded() {
    let uri =
      Uri::from_str("file:///home/user/my%20file.txt").unwrap();
    assert_eq!(uri.file(), "my%20file.txt");
  }
}