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