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
#![deny(clippy::all)]
#![deny(rustdoc::broken_intra_doc_links)]
pub mod calls;
pub mod spec;
use std::{
fmt::Write,
io::Write as IoWrite,
num::ParseIntError,
path::{Path, PathBuf},
str::FromStr,
sync::{atomic::AtomicBool, Arc, Mutex},
time::{Duration, Instant},
};
use bellframe::{
place_not::{self, PnBlockParseError},
InvalidRowError,
};
use log::{log_enabled, LevelFilter};
use monument::{Comp, Config, Progress, Query, QueryUpdate};
use ringing_utils::{BigNumInt, PrettyDuration};
use simple_logger::SimpleLogger;
use spec::Spec;
pub fn init_logging(filter: LevelFilter) {
SimpleLogger::new()
.without_timestamps()
.with_colors(true)
.with_level(filter)
.init()
.unwrap();
}
pub fn run(
input_file: &Path,
debug_print: Option<DebugOption>,
queue_limit: usize,
) -> Result<Option<QueryResult>, Error> {
let start_time = Instant::now();
macro_rules! debug_print {
($variant: ident, $val: expr) => {
if debug_print == Some(DebugOption::$variant) {
dbg!($val);
return Ok(None);
}
};
}
let spec =
Spec::read_from_file(input_file).map_err(|e| Error::SpecFile(input_file.to_owned(), e))?;
debug_print!(Spec, spec);
log::debug!("Generating query");
let query = spec.lower(input_file)?;
debug_print!(Query, query);
debug_print!(Layout, &query.layout);
let mut config = Config {
queue_limit,
num_threads: Some(1),
..Config::default()
};
let graph = query.unoptimised_graph();
debug_print!(Graph, graph);
let optimised_graphs = query.optimise_graph(graph, &mut config);
if debug_print == Some(DebugOption::StopBeforeSearch) {
return Ok(None);
}
let comps = Arc::new(Mutex::new(Vec::<Comp>::new()));
let comps_for_closure = comps.clone();
let mut update_logger = SingleLineProgressLogger::new();
Query::search(
Arc::new(query),
optimised_graphs,
&config,
move |update| {
if let Some(comp) = update_logger.log(update) {
comps_for_closure.lock().unwrap().push(comp);
}
},
Arc::new(AtomicBool::new(false)),
);
let mut comps = comps.lock().unwrap().to_vec();
comps.sort_by_key(|comp| comp.avg_score);
Ok(Some(QueryResult {
comps,
duration: Instant::now() - start_time,
}))
}
#[derive(Debug, Clone)]
pub struct QueryResult {
pub comps: Vec<Comp>,
pub duration: Duration,
}
impl QueryResult {
pub fn print(&self) {
println!("\n\n\n\nSEARCH COMPLETE!\n\n\n");
for c in &self.comps {
println!("{}", c.long_string());
}
println!("Search completed in {}", PrettyDuration(self.duration));
}
}
#[derive(Debug)]
pub enum Error {
SpecFile(PathBuf, spec::TomlReadError),
MusicFile(PathBuf, spec::TomlReadError),
PartHeadParse(InvalidRowError),
ChMaskParse(String, bellframe::mask::ParseError),
ChPatternParse(String, bellframe::mask::ParseError),
NoMethods,
CcLibNotFound,
MethodNotFound { suggestions: Vec<String> },
MethodPnParse(PnBlockParseError),
CallPnParse(String, place_not::ParseError),
LeadLocationIndex(String, ParseIntError),
LayoutGen(monument::layout::new::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugOption {
Spec,
Query,
Layout,
Graph,
StopBeforeSearch,
}
impl FromStr for DebugOption {
type Err = String;
fn from_str(v: &str) -> Result<Self, String> {
Ok(match v.to_lowercase().as_str() {
"spec" => Self::Spec,
"query" => Self::Query,
"layout" => Self::Layout,
"graph" => Self::Graph,
"no-search" => Self::StopBeforeSearch,
#[rustfmt::skip]
_ => return Err(format!(
"Unknown value {:?}. Expected `spec`, `query`, `layout`, `graph` or `no-search`.",
v
)),
})
}
}
struct SingleLineProgressLogger {
last_progress: Progress,
is_truncating_queue: bool,
last_line_length: usize,
}
impl SingleLineProgressLogger {
fn new() -> Self {
Self {
last_progress: Progress::START,
is_truncating_queue: false,
last_line_length: 0,
}
}
fn log(&mut self, update: QueryUpdate) -> Option<Comp> {
if !log_enabled!(log::Level::Info) {
return match update {
QueryUpdate::Comp(c) => Some(c),
_ => None,
};
}
let comp = self.update_progress(update);
let mut update_string = String::new();
if let Some(c) = &comp {
update_string.push_str(&c.long_string());
update_string.push('\n');
}
self.append_progress_string(&mut update_string);
let update_string = self.extend_string(&update_string);
let std_out = std::io::stdout();
let mut std_out = std_out.lock();
write!(std_out, "{}\r", update_string).unwrap();
std_out.flush().unwrap();
comp
}
fn update_progress(&mut self, update: QueryUpdate) -> Option<Comp> {
match update {
QueryUpdate::Comp(comp) => return Some(comp),
QueryUpdate::Progress(progress) => {
self.last_progress = progress;
self.is_truncating_queue = false;
}
QueryUpdate::TruncatingQueue => self.is_truncating_queue = true,
}
None
}
fn append_progress_string(&self, buf: &mut String) {
let p = &self.last_progress;
write!(
buf,
" {} iters, {} items in queue, avg/max len {:.0}/{}",
BigNumInt(p.iter_count),
BigNumInt(p.queue_len),
p.avg_length,
p.max_length
)
.unwrap();
if self.is_truncating_queue {
buf.push_str(". Truncating queue...");
}
}
fn extend_string(&mut self, s: &str) -> String {
let (first_line, other_lines) = match s.split_once('\n') {
Some((f, o)) => (f, Some(o)),
None => (s, None),
};
let num_spaces = self.last_line_length.saturating_sub(first_line.len());
let mut output = String::new();
output.push_str(first_line);
output.extend(std::iter::repeat(' ').take(num_spaces));
if let Some(o) = other_lines {
output.push('\n');
output.push_str(o);
}
self.last_line_length = output.len() - output.rfind('\n').map_or(0, |n| n + 1);
output
}
}