Skip to main content

lisette_syntax/program/
file.rs

1use std::collections::HashMap;
2use std::hash::BuildHasher;
3use std::path::PathBuf;
4
5use ecow::{EcoString, eco_format};
6
7use crate::FileParseStatus;
8use crate::ast::{Expression, ImportAlias, Span};
9use std::path::Path;
10
11#[derive(Debug, Clone, PartialEq)]
12pub struct File {
13    pub id: u32,
14    pub package_id: String,
15    pub parse_status: FileParseStatus,
16    /// Stable bare filename (e.g. `greet.lis`); identity key for caching and
17    /// LSP path reconstruction.
18    pub name: String,
19    /// Cwd-relative path for diagnostics and `--sourcemap` directives; equals
20    /// `name` for synthetic/test loaders that have no notion of cwd.
21    pub display_path: String,
22    /// Physical source path when it cannot be reconstructed from the package
23    /// and filename, notably for generated Go typedefs.
24    pub source_path: Option<PathBuf>,
25    pub source: String,
26    pub items: Vec<Expression>,
27    pub file_comment: Option<String>,
28}
29
30#[derive(Debug, Clone, PartialEq)]
31pub struct FileImport {
32    pub name: EcoString,
33    pub name_span: Span,
34    pub alias: Option<ImportAlias>,
35    pub span: Span,
36}
37
38impl FileImport {
39    pub fn effective_alias<S: BuildHasher>(
40        &self,
41        go_package_names: &HashMap<String, String, S>,
42    ) -> Option<String> {
43        match &self.alias {
44            Some(ImportAlias::Named(name, _)) => Some(name.to_string()),
45            Some(ImportAlias::Blank(_)) => None,
46            None => Some(unaliased_binding_name(&self.name, go_package_names).to_string()),
47        }
48    }
49}
50
51pub fn is_test_file(name: &str) -> bool {
52    name.ends_with(".test.lis")
53}
54
55pub fn unaliased_binding_name<'a, S: BuildHasher>(
56    path: &'a str,
57    go_package_names: &'a HashMap<String, String, S>,
58) -> &'a str {
59    if let Some(package_name) = go_package_names.get(path) {
60        return package_name;
61    }
62    if path.starts_with("go:") {
63        return go_import_default_name(path);
64    }
65    path.rsplit('/').next().unwrap_or(path)
66}
67
68pub fn go_import_default_name(import_path: &str) -> &str {
69    let path = import_path.strip_prefix("go:").unwrap_or(import_path);
70    let mut segments = path.rsplit('/');
71    let last = segments.next().unwrap_or(path);
72    if is_major_version_segment(last)
73        && let Some(preceding) = segments.next()
74    {
75        return preceding;
76    }
77    last
78}
79
80fn is_major_version_segment(segment: &str) -> bool {
81    segment
82        .strip_prefix('v')
83        .and_then(|digits| digits.parse::<u32>().ok())
84        .is_some_and(|major| major >= 2)
85}
86
87impl File {
88    pub fn new_cached(
89        package_id: &str,
90        name: &str,
91        display_path: &str,
92        source: &str,
93        id: u32,
94    ) -> Self {
95        Self {
96            id,
97            package_id: package_id.to_string(),
98            parse_status: FileParseStatus::Clean,
99            name: name.to_string(),
100            display_path: display_path.to_string(),
101            source_path: None,
102            source: source.to_string(),
103            items: vec![],
104            file_comment: None,
105        }
106    }
107
108    pub fn is_d_lis(&self) -> bool {
109        self.name.ends_with(".d.lis")
110    }
111
112    /// A test file (`*.test.lis`).
113    pub fn is_test(&self) -> bool {
114        is_test_file(&self.name)
115    }
116
117    pub fn imports(&self) -> Vec<FileImport> {
118        self.items
119            .iter()
120            .filter_map(|item| match item {
121                Expression::PackageImport {
122                    name,
123                    name_span,
124                    alias,
125                    span,
126                } => Some(FileImport {
127                    name: name.clone(),
128                    name_span: *name_span,
129                    alias: alias.clone(),
130                    span: *span,
131                }),
132                _ => None,
133            })
134            .collect()
135    }
136
137    pub fn public_declarations(&self) -> Vec<EcoString> {
138        let exports_all = self.is_d_lis();
139        let mut names = Vec::new();
140        for item in &self.items {
141            let (name, visibility) = match item {
142                Expression::Function {
143                    name, visibility, ..
144                }
145                | Expression::Struct {
146                    name, visibility, ..
147                }
148                | Expression::TypeAlias {
149                    name, visibility, ..
150                }
151                | Expression::Interface {
152                    name, visibility, ..
153                }
154                | Expression::VariableDeclaration {
155                    name, visibility, ..
156                } => (name, visibility),
157                Expression::Const {
158                    identifier,
159                    visibility,
160                    ..
161                } => (identifier, visibility),
162                Expression::Enum {
163                    name,
164                    variants,
165                    visibility,
166                    ..
167                } => {
168                    if exports_all || visibility.is_public() {
169                        names.extend(
170                            variants
171                                .iter()
172                                .map(|variant| eco_format!("{}.{}", name, variant.name)),
173                        );
174                    }
175                    (name, visibility)
176                }
177                _ => continue,
178            };
179            if exports_all || visibility.is_public() {
180                names.push(name.clone());
181            }
182        }
183        names
184    }
185
186    /// Redirects `import "{from}"` to `to`, keeping the source spelling as the qualifier.
187    pub fn rewrite_import(&mut self, from: &str, to: &str) {
188        for item in &mut self.items {
189            if let Expression::PackageImport {
190                name,
191                name_span,
192                alias,
193                ..
194            } = item
195                && name.as_str() == from
196            {
197                if alias.is_none() {
198                    *alias = Some(ImportAlias::Named(name.clone(), *name_span));
199                }
200                *name = to.into();
201            }
202        }
203    }
204
205    pub fn go_filename(&self) -> String {
206        if let Some(stem) = self.name.strip_suffix(".test.lis") {
207            return format!("{stem}_test.go");
208        }
209        Path::new(&self.name)
210            .with_extension("go")
211            .display()
212            .to_string()
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::{FileImport, Span, go_import_default_name};
219    use crate::ast::ImportAlias;
220
221    fn import(raw: &str) -> FileImport {
222        let span = Span::new(0, 7, raw.len() as u32 + 2);
223        FileImport {
224            name: raw.into(),
225            name_span: span,
226            alias: None,
227            span,
228        }
229    }
230
231    #[test]
232    fn an_import_path_is_kept_whole() {
233        assert_eq!(
234            import("go:github.com/google/uuid").name,
235            "go:github.com/google/uuid"
236        );
237        assert_eq!(
238            import("go:github.com/google/uuid@v1.6.0").name,
239            "go:github.com/google/uuid@v1.6.0"
240        );
241        assert_eq!(import("helper@v1.0.0").name, "helper@v1.0.0");
242    }
243
244    #[test]
245    fn a_blank_alias_is_preserved() {
246        let span = Span::new(0, 0, 1);
247        let blank = FileImport {
248            name: "go:fmt".into(),
249            name_span: span,
250            alias: Some(ImportAlias::Blank(span)),
251            span,
252        };
253
254        assert!(matches!(blank.alias, Some(ImportAlias::Blank(_))));
255    }
256
257    #[test]
258    fn default_names_come_from_the_last_segment() {
259        assert_eq!(go_import_default_name("go:github.com/google/uuid"), "uuid");
260        assert_eq!(go_import_default_name("go:encoding/json"), "json");
261    }
262
263    #[test]
264    fn major_version_suffix_resolves_to_preceding_segment() {
265        assert_eq!(go_import_default_name("github.com/pion/sdp/v3"), "sdp");
266        assert_eq!(
267            go_import_default_name("go:github.com/pion/webrtc/v4"),
268            "webrtc"
269        );
270        assert_eq!(
271            go_import_default_name("go:github.com/pion/transport/v4"),
272            "transport"
273        );
274    }
275
276    #[test]
277    fn non_version_last_segment_is_kept() {
278        assert_eq!(go_import_default_name("go:strings"), "strings");
279        assert_eq!(
280            go_import_default_name("go:github.com/pion/datachannel"),
281            "datachannel"
282        );
283        assert_eq!(
284            go_import_default_name("go:github.com/pion/transport/v4/packetio"),
285            "packetio"
286        );
287    }
288
289    #[test]
290    fn v0_and_v1_are_ordinary_segments() {
291        assert_eq!(go_import_default_name("go:k8s.io/api/core/v1"), "v1");
292        assert_eq!(go_import_default_name("go:example.com/pkg/v0"), "v0");
293    }
294
295    #[test]
296    fn dotted_version_suffix_is_not_a_major_version_segment() {
297        assert_eq!(go_import_default_name("go:gopkg.in/yaml.v3"), "yaml.v3");
298    }
299
300    #[test]
301    fn version_like_segment_without_preceding_segment_is_kept() {
302        assert_eq!(go_import_default_name("v2"), "v2");
303        assert_eq!(go_import_default_name("go:v2"), "v2");
304    }
305
306    #[test]
307    fn bare_v_or_non_numeric_is_not_a_version() {
308        assert_eq!(go_import_default_name("go:example.com/foo/v"), "v");
309        assert_eq!(go_import_default_name("go:example.com/foo/vx"), "vx");
310    }
311}