Skip to main content

lisette_syntax/program/
file.rs

1use ecow::EcoString;
2
3use crate::ast::{Expression, ImportAlias, Span};
4
5#[derive(Debug, Clone, PartialEq)]
6pub struct File {
7    pub id: u32,
8    pub module_id: String,
9    pub name: String,
10    pub source: String,
11    pub items: Vec<Expression>,
12}
13
14#[derive(Debug, Clone, PartialEq)]
15pub struct FileImport {
16    pub name: EcoString,
17    pub name_span: Span,
18    pub alias: Option<ImportAlias>,
19    pub span: Span,
20}
21
22impl FileImport {
23    pub fn effective_alias(&self) -> Option<String> {
24        match &self.alias {
25            Some(ImportAlias::Named(name, _)) => Some(name.to_string()),
26            Some(ImportAlias::Blank(_)) => None,
27            None => Some(
28                self.name
29                    .strip_prefix("go:")
30                    .unwrap_or(&self.name)
31                    .split('/')
32                    .next_back()
33                    .unwrap_or(&self.name)
34                    .to_string(),
35            ),
36        }
37    }
38}
39
40impl File {
41    pub fn new(module_id: &str, name: &str, source: &str, items: Vec<Expression>, id: u32) -> Self {
42        File {
43            id,
44            module_id: module_id.to_string(),
45            name: name.to_string(),
46            source: source.to_string(),
47            items,
48        }
49    }
50
51    pub fn new_cached(module_id: &str, name: &str, source: &str, id: u32) -> Self {
52        Self {
53            id,
54            module_id: module_id.to_string(),
55            name: name.to_string(),
56            source: source.to_string(),
57            items: vec![],
58        }
59    }
60
61    pub fn is_d_lis(&self) -> bool {
62        self.name.ends_with(".d.lis")
63    }
64
65    pub fn is_lis(&self) -> bool {
66        !self.is_d_lis()
67    }
68
69    pub fn imports(&self) -> Vec<FileImport> {
70        self.items
71            .iter()
72            .filter_map(|item| match item {
73                Expression::ModuleImport {
74                    name,
75                    name_span,
76                    alias,
77                    span,
78                } => Some(FileImport {
79                    name: name.clone(),
80                    name_span: *name_span,
81                    alias: alias.clone(),
82                    span: *span,
83                }),
84                _ => None,
85            })
86            .collect()
87    }
88
89    pub fn go_filename(&self) -> String {
90        std::path::Path::new(&self.name)
91            .with_extension("go")
92            .display()
93            .to_string()
94    }
95}