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