tinymist_vfs/
path_mapper.rs

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
//! Maps paths to compact integer ids. We don't care about clearings paths which
//! no longer exist -- the assumption is total size of paths we ever look at is
//! not too big.

use core::fmt;
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use parking_lot::RwLock;
use tinymist_std::path::PathClean;
use tinymist_std::ImmutPath;
use typst::diag::{eco_format, EcoString, FileError, FileResult};
use typst::syntax::package::{PackageSpec, PackageVersion};
use typst::syntax::VirtualPath;

use super::TypstFileId;

#[derive(Debug)]
pub enum PathResolution {
    Resolved(PathBuf),
    Rootless(Cow<'static, VirtualPath>),
}

impl PathResolution {
    pub fn to_err(self) -> FileResult<PathBuf> {
        match self {
            PathResolution::Resolved(path) => Ok(path),
            PathResolution::Rootless(_) => Err(FileError::AccessDenied),
        }
    }

    pub fn as_path(&self) -> &Path {
        match self {
            PathResolution::Resolved(path) => path.as_path(),
            PathResolution::Rootless(path) => path.as_rooted_path(),
        }
    }

    pub fn join(&self, path: &str) -> FileResult<PathResolution> {
        match self {
            PathResolution::Resolved(root) => Ok(PathResolution::Resolved(root.join(path))),
            PathResolution::Rootless(root) => {
                Ok(PathResolution::Rootless(Cow::Owned(root.join(path))))
            }
        }
    }
}

pub trait RootResolver {
    fn path_for_id(&self, file_id: TypstFileId) -> FileResult<PathResolution> {
        use WorkspaceResolution::*;
        let root = match WorkspaceResolver::resolve(file_id)? {
            Workspace(id) => id.path().clone(),
            Package => {
                self.resolve_package_root(file_id.package().expect("not a file in package"))?
            }
            UntitledRooted(..) | Rootless => {
                return Ok(PathResolution::Rootless(Cow::Borrowed(file_id.vpath())))
            }
        };

        file_id
            .vpath()
            .resolve(&root)
            .map(PathResolution::Resolved)
            .ok_or_else(|| FileError::AccessDenied)
    }

    fn resolve_root(&self, file_id: TypstFileId) -> FileResult<Option<ImmutPath>> {
        use WorkspaceResolution::*;
        match WorkspaceResolver::resolve(file_id)? {
            Workspace(id) | UntitledRooted(id) => Ok(Some(id.path().clone())),
            Rootless => Ok(None),
            Package => self
                .resolve_package_root(file_id.package().expect("not a file in package"))
                .map(Some),
        }
    }

    fn resolve_package_root(&self, pkg: &PackageSpec) -> FileResult<ImmutPath>;
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct WorkspaceId(u16);

const NO_VERSION: PackageVersion = PackageVersion {
    major: 0,
    minor: 0,
    patch: 0,
};

const UNTITLED_ROOT: PackageVersion = PackageVersion {
    major: 0,
    minor: 0,
    patch: 1,
};

impl WorkspaceId {
    fn package(&self) -> PackageSpec {
        PackageSpec {
            namespace: WorkspaceResolver::WORKSPACE_NS.clone(),
            name: eco_format!("p{}", self.0),
            version: NO_VERSION,
        }
    }

    fn untitled_root(&self) -> PackageSpec {
        PackageSpec {
            namespace: WorkspaceResolver::WORKSPACE_NS.clone(),
            name: eco_format!("p{}", self.0),
            version: UNTITLED_ROOT,
        }
    }

    pub fn path(&self) -> ImmutPath {
        let interner = INTERNER.read();
        interner
            .from_id
            .get(self.0 as usize)
            .expect("invalid workspace id")
            .clone()
    }

    fn from_package_name(name: &str) -> Option<WorkspaceId> {
        if !name.starts_with("p") {
            return None;
        }

        let num = name[1..].parse().ok()?;
        Some(WorkspaceId(num))
    }
}

/// The global package-path interner.
static INTERNER: LazyLock<RwLock<Interner>> = LazyLock::new(|| {
    RwLock::new(Interner {
        to_id: HashMap::new(),
        from_id: Vec::new(),
    })
});

pub enum WorkspaceResolution {
    Workspace(WorkspaceId),
    UntitledRooted(WorkspaceId),
    Rootless,
    Package,
}

/// A package-path interner.
struct Interner {
    to_id: HashMap<ImmutPath, WorkspaceId>,
    from_id: Vec<ImmutPath>,
}

#[derive(Default)]
pub struct WorkspaceResolver {}

impl WorkspaceResolver {
    pub const WORKSPACE_NS: EcoString = EcoString::inline("ws");

    pub fn is_workspace_file(fid: TypstFileId) -> bool {
        fid.package()
            .is_some_and(|p| p.namespace == WorkspaceResolver::WORKSPACE_NS)
    }

    pub fn is_package_file(fid: TypstFileId) -> bool {
        fid.package()
            .is_some_and(|p| p.namespace != WorkspaceResolver::WORKSPACE_NS)
    }

    /// Id of the given path if it exists in the `Vfs` and is not deleted.
    pub fn workspace_id(root: &ImmutPath) -> WorkspaceId {
        // Try to find an existing entry that we can reuse.
        //
        // We could check with just a read lock, but if the pair is not yet
        // present, we would then need to recheck after acquiring a write lock,
        // which is probably not worth it.
        let mut interner = INTERNER.write();
        if let Some(&id) = interner.to_id.get(root) {
            return id;
        }

        let root = ImmutPath::from(root.clean());

        // Create a new entry forever by leaking the pair. We can't leak more
        // than 2^16 pair (and typically will leak a lot less), so its not a
        // big deal.
        let num = interner.from_id.len().try_into().expect("out of file ids");
        let id = WorkspaceId(num);
        interner.to_id.insert(root.clone(), id);
        interner.from_id.push(root.clone());
        id
    }

    /// Creates a file id for a rootless file.
    pub fn rootless_file(path: VirtualPath) -> TypstFileId {
        TypstFileId::new(None, path)
    }

    /// Creates a file id for a rootless file.
    pub fn file_with_parent_root(path: &Path) -> Option<TypstFileId> {
        if !path.is_absolute() {
            return None;
        }
        let parent = path.parent()?;
        let parent = ImmutPath::from(parent);
        let path = VirtualPath::new(path.file_name()?);
        Some(Self::workspace_file(Some(&parent), path))
    }

    /// Creates a file id for a file in some workspace. The `root` is the root
    /// directory of the workspace. If `root` is `None`, the source code at the
    /// `path` will not be able to access physical files.
    pub fn workspace_file(root: Option<&ImmutPath>, path: VirtualPath) -> TypstFileId {
        let workspace = root.map(Self::workspace_id);
        TypstFileId::new(workspace.as_ref().map(WorkspaceId::package), path)
    }

    /// Mounts an untiled file to some workspace. The `root` is the
    /// root directory of the workspace. If `root` is `None`, the source
    /// code at the `path` will not be able to access physical files.
    pub fn rooted_untitled(root: Option<&ImmutPath>, path: VirtualPath) -> TypstFileId {
        let workspace = root.map(Self::workspace_id);
        TypstFileId::new(workspace.as_ref().map(WorkspaceId::untitled_root), path)
    }

    /// File path corresponding to the given `fid`.
    pub fn resolve(fid: TypstFileId) -> FileResult<WorkspaceResolution> {
        let Some(package) = fid.package() else {
            return Ok(WorkspaceResolution::Rootless);
        };

        match package.namespace.as_str() {
            "ws" => {
                let id = WorkspaceId::from_package_name(&package.name).ok_or_else(|| {
                    FileError::Other(Some(eco_format!("bad workspace id: {fid:?}")))
                })?;

                Ok(if package.version == UNTITLED_ROOT {
                    WorkspaceResolution::UntitledRooted(id)
                } else {
                    WorkspaceResolution::Workspace(id)
                })
            }
            _ => Ok(WorkspaceResolution::Package),
        }
    }

    /// File path corresponding to the given `fid`.
    pub fn display(id: Option<TypstFileId>) -> Resolving {
        Resolving { id }
    }
}

pub struct Resolving {
    id: Option<TypstFileId>,
}

impl fmt::Debug for Resolving {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use WorkspaceResolution::*;
        let Some(id) = self.id else {
            return write!(f, "unresolved-path");
        };

        let path = match WorkspaceResolver::resolve(id) {
            Ok(Workspace(workspace)) => id.vpath().resolve(&workspace.path()),
            Ok(UntitledRooted(..)) => Some(id.vpath().as_rootless_path().to_owned()),
            Ok(Rootless | Package) | Err(_) => None,
        };

        if let Some(path) = path {
            write!(f, "{}", path.display())
        } else {
            write!(f, "{:?}", self.id)
        }
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_interner_untitled() {}
}