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