1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! Formatter for [`rsn`]
#![warn(clippy::pedantic, missing_docs)]
use std::fmt::{Display, Write};
use std::ops::Range;

use rsn::tokenizer::{self, Balanced, Token, TokenKind, Tokenizer};
use thiserror::Error;

/// Configuration for `rsnfmt`
pub mod config;
pub use config::Config;
mod utils;
#[allow(clippy::wildcard_imports)]
use utils::*;

type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Error, Debug)]
/// Error returned from [`format_str`]
pub enum Error {
    /// Error Originating from Tokenization
    #[error("tokenizer error: {_0:?}")]
    Tokenizer(#[from] tokenizer::Error),
    /// Missmatched delimiter e.g. `( ... ]` or `... }`
    #[error("missmatched delimiter at {_0:?}")]
    MissmatchedDelimiter(Range<usize>),
}

/// Unwrapping write, because we only write to [`String`]
// Tried to shadow `std::write` but ra doesn't like: https://github.com/rust-lang/rust-analyzer/issues/13683
macro_rules! w {
    ($($tt:tt)*) => {
        { write!($($tt)*).unwrap(); }
    };
}

struct Indent {
    level: usize,
    hard_tab: bool,
    width: usize,
}

impl Indent {
    fn inc(&mut self) {
        self.level += 1;
    }

    fn dec(&mut self) {
        self.level -= 1;
    }
}

impl Display for Indent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.hard_tab {
            write!(f, "{:1$\t}", "", self.level)
        } else {
            write!(f, "{:1$}", "", self.width * self.level)
        }
    }
}

/// # Errors
/// Errors on syntactically invalid rsn.
pub fn format_str(source: &str, config: &Config) -> Result<String> {
    let mut tokenizer = Tokenizer::full(source);
    let mut f = String::new();
    let mut indent = config.indent();
    let mut opened = Vec::new();
    let mut nled = false;
    let mut spaced = false;
    let nl = config.line_ending(source);
    while let Some(token) = tokenizer.next() {
        let Token { location, kind } = token?;
        match kind {
            TokenKind::Integer(_)
            | TokenKind::Float(_)
            | TokenKind::Bool(_)
            | TokenKind::Character(_)
            | TokenKind::Byte(_)
            | TokenKind::String(_) // TODO align escaped newline
            | TokenKind::Bytes(_)  // TODO align escaped newline
            | TokenKind::Identifier(_)
            | TokenKind::Comment(_) // TODO indent
            => {
                if nled {
                    w!(f, "{indent}{}", &source[location]);
                } else {
                    if spaced {
                        w!(f, " ");
                    }
                    w!(f, "{}", &source[location]);
                }
            }
            TokenKind::Colon => w!(f, ":"),
            TokenKind::Comma => w!(f, ",{nl}"),
            TokenKind::Open(delimiter) => {
                let tmp = tokenizer.clone();
                match format_single_line(source, &mut tokenizer, delimiter, config)? {
                    Some(single_line) if f.lines().last().unwrap_or_default().len() + single_line.len() < config.max_width =>  {
                        if spaced || delimiter == Balanced::Brace {
                            w!(f, " ");
                        }
                        w!(f, "{single_line}");
                    }
                    _ => {
                        if nled {
                            w!(f, "{indent}{}{nl}", delimiter.open());
                        } else if spaced || delimiter.is_brace() {
                            w!(f, " {}{nl}", delimiter.open());
                        } else {
                            w!(f, "{}{nl}", delimiter.open());
                        }
                        opened.push(delimiter);
                        indent.inc();
                        tokenizer = tmp;
                    }
                }
            }
            TokenKind::Close(delimiter) => {
                indent.dec();
                if nled {
                    w!(f, "{indent}{}", delimiter.close());
                } else {
                    w!(f, "{nl}{indent}{}", delimiter.close());
                }
                if opened.is_empty() || delimiter != opened.pop().expect("opened is not empty") {
                    return Err(Error::MissmatchedDelimiter(location));
                }
            }
            TokenKind::Whitespace(ws) => {
                match config.preserve_empty_lines {
                    config::PreserveEmptyLines::One => {
                        if ws.chars().filter(|c|*c=='\n').count() > 1 {
                            if !nled {
                                w!(f, "{nl}");
                            }
                            w!(f, "{nl}");
                            nled = true;
                            spaced = false;
                        }
                    },
                    config::PreserveEmptyLines::All => for _ in 0..ws.chars().filter(|c|*c=='\n').count().saturating_sub(usize::from(nled)) {
                        w!(f, "{nl}");
                        nled = true;
                        spaced = false;
                    },
                    config::PreserveEmptyLines::None => {},
                }
            }
        }
        if !matches!(kind, TokenKind::Whitespace(_)) {
            nled = matches!(kind, TokenKind::Comma | TokenKind::Open(_));
            spaced = kind == TokenKind::Colon;
        }
    }
    Ok(f)
}

fn format_single_line(
    source: &str,
    tokenizer: &mut Tokenizer<true>,
    delimiter: Balanced,
    config: &Config,
) -> Result<Option<String>> {
    let mut f = String::new();
    let mut opened = vec![delimiter];
    let mut spaced = delimiter == Balanced::Brace;
    let mut comma = false;
    let mut empty = true;
    let mut unspaced = true;
    w!(f, "{}", delimiter.open());
    for token in tokenizer {
        let Token { location, kind } = token?;
        if comma {
            match kind {
                TokenKind::Integer(_)
                | TokenKind::Float(_)
                | TokenKind::Bool(_)
                | TokenKind::Character(_)
                | TokenKind::Byte(_)
                | TokenKind::String(_)
                | TokenKind::Bytes(_)
                | TokenKind::Identifier(_)
                | TokenKind::Open(_) => {
                    w!(f, ",");
                    comma = false;
                }
                TokenKind::Close(_) => comma = false,
                _ => {}
            }
        }
        match kind {
            TokenKind::Byte(_) | TokenKind::String(_)
                if source[location.clone()].contains('\n') =>
            {
                return Ok(None);
            }
            TokenKind::Open(_) if opened.len() > config.max_inline_level => {
                return Ok(None);
            }
            TokenKind::Close(_) if !empty && opened.len() > config.max_inline_level => {
                return Ok(None);
            }
            TokenKind::Integer(_)
            | TokenKind::Float(_)
            | TokenKind::Bool(_)
            | TokenKind::Character(_)
            | TokenKind::Byte(_)
            | TokenKind::String(_)
            | TokenKind::Bytes(_)
            | TokenKind::Identifier(_) => {
                if spaced {
                    w!(f, " ");
                }
                w!(f, "{}", &source[location]);
            }
            TokenKind::Comment(_) => {
                // TODO inline comment
                return Ok(None);
            }
            TokenKind::Colon => {
                w!(f, ":");
            }
            TokenKind::Comma => comma = true,
            TokenKind::Open(delimiter) => {
                opened.push(delimiter);
                if (spaced || delimiter == Balanced::Brace) && !unspaced {
                    w!(f, " ");
                }
                w!(f, "{}", delimiter.open());
            }
            TokenKind::Close(delimiter) => {
                if delimiter == Balanced::Brace {
                    w!(f, " {}", delimiter.close());
                } else {
                    w!(f, "{}", delimiter.close());
                }
                if opened.is_empty() || delimiter != opened.pop().expect("opened is not empty") {
                    return Err(Error::MissmatchedDelimiter(location));
                }
                if opened.is_empty() {
                    return Ok(Some(f));
                }
            }
            TokenKind::Whitespace(ws) => {
                if ws.chars().filter(|c| *c == '\n').count() > 1
                    && !config.preserve_empty_lines.is_none()
                {
                    return Ok(None);
                }
            }
        }
        if !kind.is_white_space() {
            spaced = matches!(
                kind,
                TokenKind::Colon | TokenKind::Comma | TokenKind::Open(Balanced::Brace)
            );
            unspaced = kind.is_open();
        }
        empty |= !(kind.is_value() || kind.is_comment() || kind.is_close());
    }
    Ok(Some(f))
}