Skip to main content

lisette_syntax/
lib.rs

1pub mod ast;
2pub mod attributes;
3pub mod casing;
4pub mod collections;
5pub mod constant;
6pub mod containment;
7pub mod dependency_block;
8pub mod display;
9pub mod display_form;
10pub mod doc;
11pub mod go_names;
12pub mod go_platform;
13pub mod imports;
14pub mod lex;
15pub mod parse;
16pub mod program;
17pub mod types;
18pub mod walk;
19
20pub use ecow::EcoString;
21pub use parse::{FileParseStatus, ParseError};
22
23pub const ENTRY_PACKAGE_ID: &str = "_entry_";
24pub const ROOT_IMPORT: &str = "root";
25
26pub type AstBuildResult = parse::ParseResult;
27
28#[cfg(target_pointer_width = "64")]
29mod size_assertions {
30    use std::mem::size_of;
31    const _: () = assert!(size_of::<super::ast::Expression>() == 312);
32    const _: () = assert!(size_of::<super::ast::Pattern>() == 152);
33    const _: () = assert!(size_of::<super::types::Type>() == 40);
34    const _: () = assert!(size_of::<super::ast::Span>() == 12);
35}
36
37const MAX_SOURCE_BYTES: usize = 10 * 1024 * 1024; // 10 MiB
38
39pub fn build_ast(source: &str, file_id: u32) -> AstBuildResult {
40    let parse_result = match oversize(source, file_id) {
41        Some(result) => return result,
42        None => parse::Parser::lex_and_parse_file(source, file_id),
43    };
44    if parse_result.has_errors() {
45        return parse::ParseResult {
46            ast: vec![],
47            errors: parse_result.errors,
48            file_comment: None,
49            truncated: true,
50            status: FileParseStatus::Failed,
51        };
52    }
53
54    parse_result
55}
56
57pub fn build_ast_recovering(source: &str, file_id: u32) -> AstBuildResult {
58    match oversize(source, file_id) {
59        Some(result) => result,
60        None => parse::Parser::lex_and_parse_file(source, file_id),
61    }
62}
63
64fn oversize(source: &str, file_id: u32) -> Option<AstBuildResult> {
65    (source.len() > MAX_SOURCE_BYTES).then(|| parse::ParseResult {
66        ast: vec![],
67        errors: vec![
68            ParseError::new(
69                "File too large",
70                ast::Span::new(file_id, 0, 0),
71                format!(
72                    "file is {} bytes, maximum is {} bytes",
73                    source.len(),
74                    MAX_SOURCE_BYTES,
75                ),
76            )
77            .with_parse_code("file_too_large"),
78        ],
79        file_comment: None,
80        truncated: true,
81        status: FileParseStatus::Failed,
82    })
83}
84
85#[cfg(test)]
86mod tests {
87    use super::ast::{BinaryOperator, Expression};
88
89    fn contains_pipeline(expression: &Expression) -> bool {
90        matches!(
91            expression,
92            Expression::Binary {
93                operator: BinaryOperator::Pipeline,
94                ..
95            }
96        ) || expression.children().into_iter().any(contains_pipeline)
97    }
98
99    #[test]
100    fn a_parser_error_before_any_item_is_recovered_not_failed() {
101        let result = super::build_ast_recovering(")", 0);
102
103        assert!(!result.errors.is_empty() && result.ast.is_empty());
104        assert_eq!(result.status, super::FileParseStatus::Recovered);
105    }
106
107    #[test]
108    fn a_lexer_failure_is_the_only_recovering_failure() {
109        let result = super::build_ast_recovering("fn main() { \"unterminated }", 0);
110
111        assert_eq!(result.status, super::FileParseStatus::Failed);
112    }
113
114    #[test]
115    fn a_strict_parse_error_discards_the_ast() {
116        let result = super::build_ast("fn valid() {}\nfn broken(", 0);
117
118        assert!(result.ast.is_empty());
119        assert_eq!(result.status, super::FileParseStatus::Failed);
120    }
121
122    #[test]
123    fn build_ast_preserves_pipeline_expression() {
124        let result = super::build_ast("fn test() { value |> transform }", 0);
125
126        assert!(result.errors.is_empty());
127        assert!(result.ast.iter().any(contains_pipeline));
128    }
129
130    #[test]
131    fn a_shebang_leaves_the_items_and_their_offsets_alone() {
132        let body = "import \"go:fmt\"\n\nfn main() {}\n";
133        let with_shebang = format!("#!/usr/bin/env -S lis run\n\n{body}");
134        let shift = with_shebang.len() - body.len();
135
136        let bare = super::build_ast(body, 0);
137        let result = super::build_ast(&with_shebang, 0);
138
139        assert!(result.errors.is_empty(), "{:?}", result.errors);
140        let offsets = |items: &[Expression]| {
141            items
142                .iter()
143                .map(|item| item.get_span().byte_offset as usize)
144                .collect::<Vec<_>>()
145        };
146        assert_eq!(
147            offsets(&result.ast),
148            offsets(&bare.ast)
149                .into_iter()
150                .map(|offset| offset + shift)
151                .collect::<Vec<_>>()
152        );
153    }
154
155    #[test]
156    fn a_file_comment_may_open_what_the_shebang_leaves() {
157        for source in [
158            "#!/usr/bin/env -S lis run\n//! A tool.\nfn main() {}",
159            "#!/usr/bin/env -S lis run\n\n//! A tool.\nfn main() {}",
160        ] {
161            let result = super::build_ast(source, 0);
162
163            assert!(result.errors.is_empty(), "{source:?}: {:?}", result.errors);
164            assert_eq!(
165                result.file_comment.as_deref(),
166                Some("A tool."),
167                "{source:?}"
168            );
169        }
170    }
171
172    #[test]
173    fn a_file_comment_detached_from_the_shebang_is_misplaced() {
174        for source in [
175            "#!/usr/bin/env -S lis run\n\n\n//! A tool.\nfn main() {}",
176            "#!/usr/bin/env -S lis run\r\n\r\n\r\n//! A tool.\r\nfn main() {}",
177        ] {
178            let result = super::build_ast(source, 0);
179
180            assert_eq!(
181                result
182                    .errors
183                    .iter()
184                    .map(|error| error.code.as_str())
185                    .collect::<Vec<_>>(),
186                ["parse.misplaced_file_comment"],
187                "{source:?}"
188            );
189        }
190    }
191
192    #[test]
193    fn a_file_comment_below_an_item_stays_misplaced_under_a_shebang() {
194        let result = super::build_ast("#!/usr/bin/env -S lis run\nfn main() {}\n//! Late.\n", 0);
195
196        assert_eq!(
197            result
198                .errors
199                .iter()
200                .map(|error| error.code.as_str())
201                .collect::<Vec<_>>(),
202            ["parse.misplaced_file_comment"]
203        );
204    }
205}