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
use std::cell::RefCell;
use std::clone::Clone;
use std::error::Error;
use std::str::Chars;
use crate::ast::*;
use crate::build::{FileBuilder, Val};
use crate::error;
pub trait FormatRenderer {
fn render(&self, pos: &Position) -> Result<String, Box<dyn Error>>;
}
pub struct SimpleFormatter<V: Into<String> + Clone> {
tmpl: String,
args: Vec<V>,
}
impl<V: Into<String> + Clone> SimpleFormatter<V> {
pub fn new<S: Into<String>>(tmpl: S, args: Vec<V>) -> Self {
SimpleFormatter {
tmpl: tmpl.into(),
args: args,
}
}
}
impl<V: Into<String> + Clone> FormatRenderer for SimpleFormatter<V> {
fn render(&self, pos: &Position) -> Result<String, Box<dyn Error>> {
let mut buf = String::new();
let mut should_escape = false;
let mut count = 0;
for c in self.tmpl.chars() {
if c == '@' && !should_escape {
if count == self.args.len() {
return Err(Box::new(error::BuildError::new(
"Too few arguments to string \
formatter.",
error::ErrorType::FormatError,
pos.clone(),
)));
}
let arg = self.args[count].clone();
let strval = arg.into();
buf.push_str(&strval);
count += 1;
} else if c == '\\' && !should_escape {
should_escape = true;
} else {
buf.push(c);
}
}
if self.args.len() != count {
return Err(Box::new(error::BuildError::new(
"Too many arguments to string \
formatter.",
error::ErrorType::FormatError,
pos.clone(),
)));
}
return Ok(buf);
}
}
pub struct ExpressionFormatter<'a> {
tmpl: String,
builder: RefCell<FileBuilder<'a>>,
}
impl<'a> ExpressionFormatter<'a> {
pub fn new<S: Into<String>>(tmpl: S, builder: FileBuilder<'a>) -> Self {
ExpressionFormatter {
tmpl: tmpl.into(),
builder: RefCell::new(builder),
}
}
fn consume_expr(
&self,
builder: &mut FileBuilder,
iter: &mut Chars,
pos: &Position,
) -> Result<Val, Box<dyn Error>> {
let mut expr_string = String::new();
let mut brace_count = 0;
match iter.next() {
Some(c) => {
if c == '{' {
brace_count += 1;
} else {
return Err(Box::new(error::BuildError::new(
format!(
"Invalid syntax for format string expected '{{' but got {}",
c
),
error::ErrorType::FormatError,
pos.clone(),
)));
}
}
None => {
return Err(Box::new(error::BuildError::new(
"Invalid syntax for format string expected '{' but string ended",
error::ErrorType::FormatError,
pos.clone(),
)));
}
};
loop {
let c = match iter.next() {
Some(c) => c,
None => break,
};
if c == '{' {
brace_count += 1;
}
if c == '}' {
brace_count -= 1;
if brace_count != 0 {
expr_string.push(c);
continue;
}
if expr_string.is_empty() {
return Err(Box::new(error::BuildError::new(
"Got an empty expression in format string",
error::ErrorType::FormatError,
pos.clone(),
)));
}
if !expr_string.ends_with(";") {
expr_string.push(';');
}
return Ok(builder.eval_string(&expr_string)?.as_ref().clone());
} else {
expr_string.push(c);
}
}
return Err(Box::new(error::BuildError::new(
"Expected '}' but got end of string",
error::ErrorType::FormatError,
pos.clone(),
)));
}
}
impl<'a> FormatRenderer for ExpressionFormatter<'a> {
fn render(&self, pos: &Position) -> Result<String, Box<dyn Error>> {
let mut buf = String::new();
let mut should_escape = false;
let mut iter = self.tmpl.chars();
loop {
let c = match iter.next() {
Some(c) => c,
None => break,
};
if c == '@' && !should_escape {
let val = self.consume_expr(&mut self.builder.borrow_mut(), &mut iter, pos)?;
let strval: String = val.into();
buf.push_str(&strval);
} else if c == '\\' && !should_escape {
should_escape = true;
} else {
buf.push(c);
}
}
return Ok(buf);
}
}
#[cfg(test)]
mod test {
use super::{FormatRenderer, SimpleFormatter};
use crate::ast::Position;
#[test]
fn test_format_happy_path() {
let formatter = SimpleFormatter::new("foo @ @ \\@", vec!["bar", "quux"]);
let pos = Position::new(0, 0, 0);
assert_eq!(formatter.render(&pos).unwrap(), "foo bar quux @");
}
#[test]
fn test_format_happy_wrong_too_few_args() {
let formatter = SimpleFormatter::new("foo @ @ \\@", vec!["bar"]);
let pos = Position::new(0, 0, 0);
assert!(formatter.render(&pos).is_err());
}
#[test]
fn test_format_happy_wrong_too_many_args() {
let formatter = SimpleFormatter::new("foo @ @ \\@", vec!["bar", "quux", "baz"]);
let pos = Position::new(0, 0, 0);
assert!(formatter.render(&pos).is_err());
}
}