cly_impl/
lib.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2use crate::ast::{Declaration, Span};
3use anyhow::{anyhow, Result};
4pub use converter::{compute_layouts, extract_layouts};
5pub use enhancer::enhance_declarations;
6pub use printer::{printer, Printer};
7use std::fmt;
8use std::fmt::{Display, Formatter};
9
10pub mod ast;
11pub mod converter;
12mod enhancer;
13mod lexer;
14mod parser;
15mod printer;
16mod result;
17#[cfg(test)]
18mod tests;
19
20pub fn parse(input: &str) -> Result<Vec<Declaration>> {
21    match parser::parse(input.as_bytes()) {
22        Ok(d) => Ok(d),
23        Err(e) => Err(anyhow!("At {}: {}", to_span(input, e.span), e.msg)),
24    }
25}
26
27struct LC(usize, usize);
28
29fn to_line_column(input: &str, pos: usize) -> LC {
30    impl Display for LC {
31        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32            write!(f, "{}:{}", self.0, self.1)
33        }
34    }
35    let newlines: Vec<_> = input[..pos]
36        .char_indices()
37        .filter(|c| c.1 == '\n')
38        .collect();
39    LC(
40        newlines.len() + 1,
41        newlines
42            .last()
43            .copied()
44            .map(|v| pos - v.0 - 1)
45            .unwrap_or(pos),
46    )
47}
48
49struct S(LC, LC);
50
51fn to_span(input: &str, span: Span) -> S {
52    impl Display for S {
53        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
54            if self.0 .0 == self.1 .0 && self.0 .1 + 1 > self.1 .1 {
55                write!(f, "{}", self.0)
56            } else {
57                write!(f, "{} - {}", self.0, self.1)
58            }
59        }
60    }
61    S(to_line_column(input, span.0), to_line_column(input, span.1))
62}