Skip to main content

lisette_syntax/program/
file.rs

1use super::{is_go_import, strip_go_prefix};
2use std::collections::HashMap;
3use std::hash::BuildHasher;
4use std::path::PathBuf;
5
6use ecow::{EcoString, eco_format};
7
8use crate::FileParseStatus;
9use crate::ast::{Expression, ImportAlias, Span};
10use crate::parse::{ParseError, ParseResult};
11use std::path::Path;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct File {
15    pub id: u32,
16    pub package_id: String,
17    pub parse_status: FileParseStatus,
18    /// Stable bare filename (e.g. `greet.lis`); identity key for caching and
19    /// LSP path reconstruction.
20    pub name: String,
21    /// Cwd-relative path for diagnostics and `--sourcemap` directives, absolute
22    /// outside the cwd. Equals `name` for loaders that have no notion of cwd.
23    pub display_path: String,
24    /// Physical source path when it cannot be reconstructed from the package
25    /// and filename, notably for generated Go typedefs.
26    pub source_path: Option<PathBuf>,
27    pub source: String,
28    pub items: Vec<Expression>,
29    pub file_comment: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub struct FileImport {
34    pub name: EcoString,
35    pub name_span: Span,
36    pub alias: Option<ImportAlias>,
37    pub span: Span,
38}
39
40impl FileImport {
41    pub fn effective_alias<S: BuildHasher>(
42        &self,
43        go_package_names: &HashMap<String, String, S>,
44    ) -> Option<String> {
45        match &self.alias {
46            Some(ImportAlias::Named(name, _)) => Some(name.to_string()),
47            Some(ImportAlias::Blank(_)) => None,
48            None => Some(unaliased_binding_name(&self.name, go_package_names).to_string()),
49        }
50    }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SourceFileKind {
55    Production,
56    Test,
57    MisnamedTest,
58    Typedef,
59    Other,
60}
61
62impl SourceFileKind {
63    pub fn of(name: &str) -> Self {
64        if !name.ends_with(".lis") {
65            Self::Other
66        } else if name.ends_with(".d.lis") {
67            Self::Typedef
68        } else if name.ends_with(".test.lis") {
69            Self::Test
70        } else if name.ends_with("_test.lis") {
71            Self::MisnamedTest
72        } else {
73            Self::Production
74        }
75    }
76
77    pub fn is_lis(self) -> bool {
78        !matches!(self, Self::Other)
79    }
80
81    pub fn emits_go(self) -> bool {
82        match self {
83            Self::Production | Self::MisnamedTest => true,
84            Self::Test | Self::Typedef | Self::Other => false,
85        }
86    }
87}
88
89pub fn is_test_file(name: &str) -> bool {
90    SourceFileKind::of(name) == SourceFileKind::Test
91}
92
93pub fn unaliased_binding_name<'a, S: BuildHasher>(
94    path: &'a str,
95    go_package_names: &'a HashMap<String, String, S>,
96) -> &'a str {
97    if let Some(package_name) = go_package_names.get(path) {
98        return package_name;
99    }
100    if is_go_import(path) {
101        return go_import_default_name(path);
102    }
103    path.rsplit('/').next().unwrap_or(path)
104}
105
106pub fn go_import_default_name(import_path: &str) -> &str {
107    let path = strip_go_prefix(import_path).unwrap_or(import_path);
108    let mut segments = path.rsplit('/');
109    let last = segments.next().unwrap_or(path);
110    if is_major_version_segment(last)
111        && let Some(preceding) = segments.next()
112    {
113        return preceding;
114    }
115    last
116}
117
118pub fn suggested_import_alias(import_path: &str, name: &str) -> String {
119    let path = strip_go_prefix(import_path).unwrap_or(import_path);
120    let mut alias = match path.rsplit_once('/') {
121        Some((head, last)) => {
122            let parent = head.rsplit_once('/').map_or(head, |(_, parent)| parent);
123            format!("{}_{}", alias_segment(parent), alias_segment(last))
124        }
125        None => format!("{}_pkg", alias_segment(path)),
126    };
127    if alias == name {
128        alias.push_str("_pkg");
129    }
130    alias
131}
132
133fn alias_segment(segment: &str) -> String {
134    segment
135        .chars()
136        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
137        .collect()
138}
139
140fn is_major_version_segment(segment: &str) -> bool {
141    segment
142        .strip_prefix('v')
143        .and_then(|digits| digits.parse::<u32>().ok())
144        .is_some_and(|major| major >= 2)
145}
146
147impl File {
148    /// Keep the parsed AST, status, and file comment together while returning its diagnostics.
149    pub fn from_parse(
150        id: u32,
151        package_id: &str,
152        name: String,
153        display_path: String,
154        source: String,
155        result: ParseResult,
156    ) -> (Self, Vec<ParseError>) {
157        let file = Self {
158            id,
159            package_id: package_id.to_string(),
160            name,
161            display_path,
162            source_path: None,
163            source,
164            parse_status: result.status,
165            items: result.ast,
166            file_comment: result.file_comment,
167        };
168        (file, result.errors)
169    }
170
171    pub fn new_cached(
172        package_id: &str,
173        name: &str,
174        display_path: &str,
175        source: &str,
176        id: u32,
177    ) -> Self {
178        Self {
179            id,
180            package_id: package_id.to_string(),
181            parse_status: FileParseStatus::Clean,
182            name: name.to_string(),
183            display_path: display_path.to_string(),
184            source_path: None,
185            source: source.to_string(),
186            items: vec![],
187            file_comment: None,
188        }
189    }
190
191    pub fn is_d_lis(&self) -> bool {
192        SourceFileKind::of(&self.name) == SourceFileKind::Typedef
193    }
194
195    /// A test file (`*.test.lis`).
196    pub fn is_test(&self) -> bool {
197        is_test_file(&self.name)
198    }
199
200    pub fn imports(&self) -> Vec<FileImport> {
201        self.items
202            .iter()
203            .filter_map(|item| match item {
204                Expression::PackageImport {
205                    name,
206                    name_span,
207                    alias,
208                    span,
209                    ..
210                } => Some(FileImport {
211                    name: name.clone(),
212                    name_span: *name_span,
213                    alias: alias.clone(),
214                    span: *span,
215                }),
216                _ => None,
217            })
218            .collect()
219    }
220
221    pub fn public_declarations(&self) -> Vec<EcoString> {
222        let exports_all = self.is_d_lis();
223        let mut names = Vec::new();
224        for item in &self.items {
225            let (name, visibility) = match item {
226                Expression::Function {
227                    name, visibility, ..
228                }
229                | Expression::Struct {
230                    name, visibility, ..
231                }
232                | Expression::TypeAlias {
233                    name, visibility, ..
234                }
235                | Expression::Interface {
236                    name, visibility, ..
237                }
238                | Expression::VariableDeclaration {
239                    name, visibility, ..
240                } => (name, visibility),
241                Expression::Const {
242                    identifier,
243                    visibility,
244                    ..
245                } => (identifier, visibility),
246                Expression::Enum {
247                    name,
248                    variants,
249                    visibility,
250                    ..
251                } => {
252                    if exports_all || visibility.is_public() {
253                        names.extend(
254                            variants
255                                .iter()
256                                .map(|variant| eco_format!("{}.{}", name, variant.name)),
257                        );
258                    }
259                    (name, visibility)
260                }
261                _ => continue,
262            };
263            if exports_all || visibility.is_public() {
264                names.push(name.clone());
265            }
266        }
267        names
268    }
269
270    /// Redirects `import "{from}"` to `to`, keeping the source spelling as the qualifier.
271    pub fn rewrite_import(&mut self, from: &str, to: &str) {
272        for item in &mut self.items {
273            if let Expression::PackageImport {
274                name,
275                name_span,
276                alias,
277                ..
278            } = item
279                && name.as_str() == from
280            {
281                if alias.is_none() {
282                    *alias = Some(ImportAlias::Named(name.clone(), *name_span));
283                }
284                *name = to.into();
285            }
286        }
287    }
288
289    pub fn go_filename(&self) -> String {
290        go_filename(&self.name)
291    }
292}
293
294pub fn go_filename(lisette_filename: &str) -> String {
295    if let Some(stem) = lisette_filename.strip_suffix(".test.lis") {
296        return format!("{stem}_test.go");
297    }
298    Path::new(lisette_filename)
299        .with_extension("go")
300        .display()
301        .to_string()
302}
303
304#[cfg(test)]
305mod tests {
306    use super::{FileImport, SourceFileKind, Span, go_import_default_name};
307    use crate::ast::ImportAlias;
308
309    fn import(raw: &str) -> FileImport {
310        let span = Span::new(0, 7, raw.len() as u32 + 2);
311        FileImport {
312            name: raw.into(),
313            name_span: span,
314            alias: None,
315            span,
316        }
317    }
318
319    #[test]
320    fn an_import_path_is_kept_whole() {
321        assert_eq!(
322            import("go:github.com/google/uuid").name,
323            "go:github.com/google/uuid"
324        );
325        assert_eq!(
326            import("go:github.com/google/uuid@v1.6.0").name,
327            "go:github.com/google/uuid@v1.6.0"
328        );
329        assert_eq!(import("helper@v1.0.0").name, "helper@v1.0.0");
330    }
331
332    #[test]
333    fn a_blank_alias_is_preserved() {
334        let span = Span::new(0, 0, 1);
335        let blank = FileImport {
336            name: "go:fmt".into(),
337            name_span: span,
338            alias: Some(ImportAlias::Blank(span)),
339            span,
340        };
341
342        assert!(matches!(blank.alias, Some(ImportAlias::Blank(_))));
343    }
344
345    #[test]
346    fn default_names_come_from_the_last_segment() {
347        assert_eq!(go_import_default_name("go:github.com/google/uuid"), "uuid");
348        assert_eq!(go_import_default_name("go:encoding/json"), "json");
349    }
350
351    #[test]
352    fn major_version_suffix_resolves_to_preceding_segment() {
353        assert_eq!(go_import_default_name("github.com/pion/sdp/v3"), "sdp");
354        assert_eq!(
355            go_import_default_name("go:github.com/pion/webrtc/v4"),
356            "webrtc"
357        );
358        assert_eq!(
359            go_import_default_name("go:github.com/pion/transport/v4"),
360            "transport"
361        );
362    }
363
364    #[test]
365    fn non_version_last_segment_is_kept() {
366        assert_eq!(go_import_default_name("go:strings"), "strings");
367        assert_eq!(
368            go_import_default_name("go:github.com/pion/datachannel"),
369            "datachannel"
370        );
371        assert_eq!(
372            go_import_default_name("go:github.com/pion/transport/v4/packetio"),
373            "packetio"
374        );
375    }
376
377    #[test]
378    fn v0_and_v1_are_ordinary_segments() {
379        assert_eq!(go_import_default_name("go:k8s.io/api/core/v1"), "v1");
380        assert_eq!(go_import_default_name("go:example.com/pkg/v0"), "v0");
381    }
382
383    #[test]
384    fn dotted_version_suffix_is_not_a_major_version_segment() {
385        assert_eq!(go_import_default_name("go:gopkg.in/yaml.v3"), "yaml.v3");
386    }
387
388    #[test]
389    fn version_like_segment_without_preceding_segment_is_kept() {
390        assert_eq!(go_import_default_name("v2"), "v2");
391        assert_eq!(go_import_default_name("go:v2"), "v2");
392    }
393
394    #[test]
395    fn bare_v_or_non_numeric_is_not_a_version() {
396        assert_eq!(go_import_default_name("go:example.com/foo/v"), "v");
397        assert_eq!(go_import_default_name("go:example.com/foo/vx"), "vx");
398    }
399
400    #[test]
401    fn only_production_files_emit_go() {
402        assert!(SourceFileKind::of("a.lis").emits_go());
403        assert!(!SourceFileKind::of("a.d.lis").emits_go());
404        assert!(!SourceFileKind::of("a.test.lis").emits_go());
405        assert!(!SourceFileKind::of("a.go").emits_go());
406    }
407
408    #[test]
409    fn source_file_suffixes_are_checked_only_by_source_file_kind() {
410        use std::fs;
411        use std::path::Path;
412
413        let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
414        let patterns = [
415            "ends_with(\".lis\")",
416            "ends_with(\".d.lis\")",
417            "ends_with(\".test.lis\")",
418            "ends_with(\"_test.lis\")",
419            "== \"lis\"",
420        ];
421        let mut offenders = Vec::new();
422        let mut stack = vec![crates];
423        while let Some(dir) = stack.pop() {
424            for entry in fs::read_dir(&dir).unwrap().flatten() {
425                let path = entry.path();
426                let name = entry.file_name().to_string_lossy().to_string();
427                if path.is_dir() {
428                    if name != "tests" && name != "target" {
429                        stack.push(path);
430                    }
431                    continue;
432                }
433                if !name.ends_with(".rs") || name == "build.rs" || path.ends_with("program/file.rs")
434                {
435                    continue;
436                }
437                let source = fs::read_to_string(&path).unwrap();
438                let production = source.split("#[cfg(test)]").next().unwrap_or("");
439                for pattern in patterns {
440                    if production.contains(pattern) {
441                        offenders.push(format!("{}: {}", path.display(), pattern));
442                    }
443                }
444            }
445        }
446        assert!(
447            offenders.is_empty(),
448            "use SourceFileKind::of: {offenders:#?}"
449        );
450    }
451}