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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use crate::nodes::{
Expression, FieldExpression, FunctionCall, IndexExpression, NumberExpression, Prefix,
Statement, StringExpression, Variable,
};
const QUOTED_STRING_MAX_LENGTH: usize = 60;
const LONG_STRING_MIN_LENGTH: usize = 20;
const FORCE_LONG_STRING_NEW_LINE_THRESHOLD: usize = 6;
pub fn is_relevant_for_spacing(character: &char) -> bool {
character.is_ascii_alphabetic() || character.is_digit(10) || *character == '_'
}
pub fn break_long_string(last_str: &str) -> bool {
if let Some(last_char) = last_str.chars().last() {
last_char == '['
} else {
false
}
}
pub fn break_variable_arguments(last_string: &str) -> bool {
if let Some('.') = last_string.chars().last() {
true
} else if let Some(first_char) = last_string.chars().next() {
first_char == '.' || first_char.is_digit(10)
} else {
false
}
}
pub fn break_minus(last_string: &str) -> bool {
if let Some(last_char) = last_string.chars().last() {
last_char == '-'
} else {
false
}
}
pub fn break_concat(last_string: &str) -> bool {
if let Some('.') = last_string.chars().last() {
true
} else if let Some(first_char) = last_string.chars().next() {
first_char == '.' || first_char.is_digit(10)
} else {
false
}
}
pub fn ends_with_prefix(statement: &Statement) -> bool {
match statement {
Statement::Assign(assign) => {
if let Some(value) = assign.get_values().last() {
expression_ends_with_call(value)
} else {
false
}
}
Statement::CompoundAssign(assign) => expression_ends_with_call(assign.get_value()),
Statement::Call(_) => true,
Statement::Repeat(repeat) => expression_ends_with_call(repeat.get_condition()),
Statement::LocalAssign(assign) => {
if let Some(value) = assign.get_values().last() {
expression_ends_with_call(value)
} else {
false
}
}
_ => false,
}
}
pub fn starts_with_parenthese(statement: &Statement) -> bool {
match statement {
Statement::Assign(assign) => {
if let Some(variable) = assign.get_variables().first() {
match variable {
Variable::Identifier(_) => false,
Variable::Field(field) => field_starts_with_parenthese(field),
Variable::Index(index) => index_starts_with_parenthese(index),
}
} else {
false
}
}
Statement::CompoundAssign(assign) => match assign.get_variable() {
Variable::Identifier(_) => false,
Variable::Field(field) => field_starts_with_parenthese(field),
Variable::Index(index) => index_starts_with_parenthese(index),
},
Statement::Call(call) => call_starts_with_parenthese(call),
_ => false,
}
}
fn expression_ends_with_call(expression: &Expression) -> bool {
match expression {
Expression::Binary(binary) => expression_ends_with_call(binary.right()),
Expression::Call(_)
| Expression::Parenthese(_)
| Expression::Identifier(_)
| Expression::Field(_)
| Expression::Index(_) => true,
Expression::Unary(unary) => expression_ends_with_call(unary.get_expression()),
_ => false,
}
}
fn prefix_starts_with_parenthese(prefix: &Prefix) -> bool {
match prefix {
Prefix::Parenthese(_) => true,
Prefix::Call(call) => call_starts_with_parenthese(call),
Prefix::Field(field) => field_starts_with_parenthese(field),
Prefix::Index(index) => index_starts_with_parenthese(index),
Prefix::Identifier(_) => false,
}
}
#[inline]
fn call_starts_with_parenthese(call: &FunctionCall) -> bool {
prefix_starts_with_parenthese(call.get_prefix())
}
#[inline]
fn field_starts_with_parenthese(field: &FieldExpression) -> bool {
prefix_starts_with_parenthese(field.get_prefix())
}
#[inline]
fn index_starts_with_parenthese(index: &IndexExpression) -> bool {
prefix_starts_with_parenthese(index.get_prefix())
}
pub fn write_number(number: &NumberExpression) -> String {
match number {
NumberExpression::Decimal(number) => {
let float = number.get_raw_float();
if float.is_nan() {
"(0/0)".to_owned()
} else if float.is_infinite() {
format!("({}1/0)", if float.is_sign_negative() { "-" } else { "" })
} else {
format!(
"{:.}{}",
float,
number
.get_exponent()
.map(|exponent| {
let exponent_char = number
.is_uppercase()
.map(|is_uppercase| if is_uppercase { 'E' } else { 'e' })
.unwrap_or('e');
format!("{}{}", exponent_char, exponent)
})
.unwrap_or_else(|| "".to_owned())
)
}
}
NumberExpression::Hex(number) => {
format!(
"0{}{:x}{}",
if number.is_x_uppercase() { 'X' } else { 'x' },
number.get_raw_integer(),
number
.get_exponent()
.map(|exponent| {
let exponent_char = number
.is_exponent_uppercase()
.map(|is_uppercase| if is_uppercase { 'P' } else { 'p' })
.unwrap_or('p');
format!("{}{}", exponent_char, exponent)
})
.unwrap_or_else(|| "".to_owned())
)
}
NumberExpression::Binary(number) => {
format!(
"0{}{:b}",
if number.is_b_uppercase() { 'B' } else { 'b' },
number.get_raw_value()
)
}
}
}
fn needs_escaping(character: char) -> bool {
!(character.is_ascii_graphic() || character == ' ') || character == '\\'
}
fn needs_quoted_string(character: char) -> bool {
!(character.is_ascii_graphic() || character == ' ' || character == '\n')
}
fn escape(character: char) -> String {
match character {
'\n' => "\\n".to_owned(),
'\t' => "\\t".to_owned(),
'\\' => "\\\\".to_owned(),
'\r' => "\\r".to_owned(),
'\u{7}' => "\\a".to_owned(),
'\u{8}' => "\\b".to_owned(),
'\u{B}' => "\\v".to_owned(),
'\u{C}' => "\\f".to_owned(),
_ => {
if character.is_ascii() {
format!("\\{}", character as u8)
} else {
format!("\\u{{{:x}}}", character as u32)
}
}
}
}
#[inline]
pub fn count_new_lines(string: &str) -> usize {
string.chars().filter(|c| *c == '\n').count()
}
pub fn write_string(string: &StringExpression) -> String {
let value = string.get_value();
if value.is_empty() {
return "''".to_owned();
}
if value.len() == 1 {
let character = value
.chars()
.next()
.expect("string should have at least one character");
match character {
'\'' => return "\"'\"".to_owned(),
'"' => return "'\"'".to_owned(),
_ => {
if needs_escaping(character) {
return format!("'{}'", escape(character));
} else {
return format!("'{}'", character);
}
}
}
}
if !value.contains(needs_quoted_string)
&& value.len() >= LONG_STRING_MIN_LENGTH
&& (value.len() >= QUOTED_STRING_MAX_LENGTH
|| count_new_lines(value) >= FORCE_LONG_STRING_NEW_LINE_THRESHOLD)
{
write_long_bracket(value)
} else {
write_quoted(value)
}
}
fn write_long_bracket(value: &str) -> String {
let mut i = if value.ends_with(']') { 1 } else { 0 };
let mut equals = "=".repeat(i);
loop {
if !value.contains(&format!("]{}]", equals)) {
break;
} else {
i += 1;
equals = "=".repeat(i);
};
}
let needs_extra_new_line = if value.starts_with('\n') { "\n" } else { "" };
format!("[{}[{}{}]{}]", equals, needs_extra_new_line, value, equals)
}
fn write_quoted(value: &str) -> String {
let mut quoted = String::new();
quoted.reserve(value.len() + 2);
let quote_symbol = get_quote_symbol(value);
quoted.push(quote_symbol);
for character in value.chars() {
if character == quote_symbol {
quoted.push('\\');
quoted.push(quote_symbol);
} else if needs_escaping(character) {
quoted.push_str(&escape(character));
} else {
quoted.push(character);
}
}
quoted.push(quote_symbol);
quoted.shrink_to_fit();
quoted
}
fn get_quote_symbol(value: &str) -> char {
if value.contains('"') {
'\''
} else if value.contains('\'') {
'"'
} else {
'\''
}
}
#[cfg(test)]
mod test {
use super::*;
mod write_string {
use super::*;
macro_rules! test_output {
($($name:ident($input:literal) => $value:literal),* $(,)?) => {
$(
#[test]
fn $name() {
assert_eq!($value, write_string(&StringExpression::from_value($input)));
}
)*
};
}
test_output!(
empty("") => "''",
single_letter("a") => "'a'",
single_digit("8") => "'8'",
single_symbol("!") => "'!'",
single_space(" ") => "' '",
abc("abc") => "'abc'",
three_spaces(" ") => "' '",
new_line("\n") => "'\\n'",
bell("\u{7}") => "'\\a'",
backspace("\u{8}") => "'\\b'",
form_feed("\u{c}") => "'\\f'",
tab("\t") => "'\\t'",
carriage_return("\u{D}") => "'\\r'",
vertical_tab("\u{B}") => "'\\v'",
backslash("\\") => "'\\\\'",
single_quote("'") => "\"'\"",
double_quote("\"") => "'\"'",
null("\0") => "'\\0'",
escape("\u{1B}") => "'\\27'",
unicode("\u{10FFFF}") => "'\\u{10ffff}'",
im_cool("I'm cool") => "\"I'm cool\"",
ends_with_closing_bracket("oof]") => "'oof]'",
multiline_ends_with_closing_bracket("oof\noof]") => "'oof\\noof]'",
large_multiline_does_not_end_with_closing_bracket("ooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof")
=> "[[ooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof]]",
large_multiline_ends_with_closing_bracket("ooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof]")
=> "[=[ooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof]]=]",
large_multiline_starts_with_new_line("\nooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof")
=> "[[\n\nooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof]]",
large_multiline_with_unicode("\nooof\nooof\nooof\nooof\nooof\nooof\nooof\nooof\noof\u{10FFFF}")
=> "'\\nooof\\nooof\\nooof\\nooof\\nooof\\nooof\\nooof\\nooof\\noof\\u{10ffff}'",
);
}
}