1
#![allow(clippy::unwrap_used)]
2

            
3
#[cfg(feature = "mimalloc")]
4
#[global_allocator]
5
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
6

            
7
mod cli;
8
mod pretty;
9
mod rule_trace_aggregates;
10
mod solve;
11
mod test_solve;
12
use anyhow::Context as _;
13
use clap::{CommandFactory, Parser};
14
use clap_complete::generate;
15
use cli::{Cli, GlobalArgs, LogDetail, LogFormat};
16
use conjure_cp_cli::utils::rule_trace::RuleApplicationCounter;
17
use pretty::run_pretty_command;
18
use rule_trace_aggregates::write_rule_trace_aggregates;
19
use solve::run_solve_command;
20
use std::fs::File;
21
use std::io;
22
use std::path::PathBuf;
23
use std::sync::{Arc, OnceLock};
24
use test_solve::run_test_solve_command;
25

            
26
use conjure_cp_rules as _;
27

            
28
use tracing_subscriber::filter::{FilterFn, LevelFilter};
29
use tracing_subscriber::layer::SubscriberExt as _;
30
use tracing_subscriber::util::SubscriberInitExt as _;
31
use tracing_subscriber::{EnvFilter, Layer, fmt};
32

            
33
#[cfg(feature = "lsp")]
34
use conjure_cp_lsp::server;
35

            
36
struct LoggingState {
37
    rule_application_counts: RuleApplicationCounter,
38
    rule_trace_aggregates_path: Option<PathBuf>,
39
}
40

            
41
impl LoggingState {
42
638
    fn flush(&self) {
43
638
        if let Some(path) = &self.rule_trace_aggregates_path {
44
36
            write_rule_trace_aggregates(path, &self.rule_application_counts.snapshot())
45
36
                .expect("failed to write rule trace aggregates");
46
602
        }
47
638
    }
48
}
49

            
50
static LOGGING_STATE: OnceLock<LoggingState> = OnceLock::new();
51

            
52
/// Writes buffered log outputs, such as the final rule-trace aggregates.
53
638
fn flush_logging() {
54
638
    if let Some(state) = LOGGING_STATE.get() {
55
638
        state.flush();
56
    }
57
638
}
58

            
59
/// Flushes buffered log outputs, then exits. Use instead of [`std::process::exit`].
60
322
pub(crate) fn exit(code: i32) -> ! {
61
322
    flush_logging();
62
322
    std::process::exit(code)
63
}
64

            
65
/// Flushes on return and while unwinding from a panic.
66
struct FlushLoggingOnDrop;
67

            
68
impl Drop for FlushLoggingOnDrop {
69
316
    fn drop(&mut self) {
70
316
        flush_logging();
71
316
    }
72
}
73

            
74
326
pub fn main() {
75
    // exit with 2 instead of 1 on failure,like grep
76
326
    match run() {
77
        Ok(_) => {
78
290
            exit(0);
79
        }
80
        Err(e) => {
81
36
            eprintln!("{e:?}");
82
36
            exit(2);
83
        }
84
    }
85
}
86

            
87
326
pub fn run() -> anyhow::Result<()> {
88
326
    let cli = Cli::parse();
89

            
90
326
    let logging_state = setup_logging(&cli.global_args)?;
91
326
    let rule_application_counts = logging_state.rule_application_counts.clone();
92
326
    let _ = LOGGING_STATE.set(logging_state);
93
326
    let _flush = FlushLoggingOnDrop;
94
326
    run_subcommand(cli, &rule_application_counts)
95
326
}
96

            
97
322
fn setup_logging(global_args: &GlobalArgs) -> anyhow::Result<LoggingState> {
98
    // It consists of composable layers, each of which logs to a different place in a different
99
    // format.
100
322
    let default_stderr_level = match (global_args.quiet, global_args.verbose) {
101
        (true, _) => LevelFilter::OFF,
102
322
        (false, 0) => LevelFilter::WARN,
103
        (false, 1) => LevelFilter::INFO,
104
        (false, 2) => LevelFilter::DEBUG,
105
        (false, _) => LevelFilter::TRACE,
106
    };
107

            
108
322
    let env_filter = if global_args.quiet || global_args.verbose > 0 {
109
        EnvFilter::new(default_stderr_level.to_string())
110
    } else {
111
322
        EnvFilter::builder()
112
322
            .with_default_directive(default_stderr_level.into())
113
322
            .from_env_lossy()
114
    };
115

            
116
322
    let stderr_layer = if global_args.verbose > 0 {
117
        Layer::boxed(
118
            tracing_subscriber::fmt::layer()
119
                .pretty()
120
                .with_writer(Arc::new(std::io::stderr()))
121
                .with_ansi(true)
122
                .with_filter(env_filter)
123
                .with_filter(general_log_filter()),
124
        )
125
    } else {
126
322
        Layer::boxed(
127
322
            tracing_subscriber::fmt::layer()
128
322
                .compact()
129
322
                .with_writer(Arc::new(std::io::stderr()))
130
322
                .with_ansi(true)
131
322
                .with_filter(env_filter)
132
322
                .with_filter(general_log_filter()),
133
322
        )
134
    };
135

            
136
322
    let rule_trace_layer = global_args.rule_trace.clone().map(|x| {
137
18
        let file = File::create(x).expect("Unable to create rule trace file");
138
18
        fmt::layer()
139
18
            .with_writer(file)
140
18
            .with_level(false)
141
18
            .without_time()
142
18
            .with_target(false)
143
18
            .with_filter(EnvFilter::new("rule_engine_rule_trace=trace"))
144
40884
            .with_filter(FilterFn::new(|meta| {
145
40884
                meta.target() == "rule_engine_rule_trace"
146
40884
            }))
147
18
    });
148

            
149
322
    let rule_attempt_trace_layer = global_args.rule_attempt_trace.clone().map(|x| {
150
4
        let file = File::create(x).expect("Unable to create rule attempt trace file");
151
4
        fmt::layer()
152
4
            .with_writer(file)
153
4
            .with_level(false)
154
4
            .without_time()
155
4
            .with_target(false)
156
4
            .compact()
157
4
            .with_ansi(false)
158
4
            .with_filter(EnvFilter::new("rule_engine_rule_attempt_trace=trace"))
159
1441604
            .with_filter(FilterFn::new(|meta| {
160
1441604
                meta.target() == "rule_engine_rule_attempt_trace"
161
1441604
            }))
162
4
    });
163

            
164
    // Validate an explicitly requested output before rewriting. Collection itself
165
    // always happens in memory, independently of the output destination.
166
322
    if let Some(path) = &global_args.rule_trace_aggregates {
167
18
        File::create(path)
168
            .with_context(|| format!("Unable to create aggregate trace file {}", path.display()))?;
169
304
    }
170

            
171
322
    let rule_application_counts = RuleApplicationCounter::default();
172
322
    let rule_trace_aggregates_layer = rule_application_counts
173
322
        .clone()
174
322
        .with_filter(EnvFilter::new("rule_engine_rule_trace_aggregates=trace"))
175
3572134
        .with_filter(FilterFn::new(|meta| {
176
3572134
            meta.target() == "rule_engine_rule_trace_aggregates"
177
3572134
        }));
178

            
179
322
    let log_format = global_args.log_format.unwrap_or_default();
180
322
    let log_detail = global_args.log_detail.unwrap_or_default();
181
322
    let text_file = match (log_format, global_args.log_file.as_ref()) {
182
        (LogFormat::Text, Some(path)) => Some(
183
4
            File::options()
184
4
                .truncate(true)
185
4
                .write(true)
186
4
                .create(true)
187
4
                .append(false)
188
4
                .open(path)?,
189
        ),
190
318
        _ => None,
191
    };
192

            
193
322
    let file_level = match log_detail {
194
320
        LogDetail::Stages => LevelFilter::INFO,
195
        LogDetail::Applications => LevelFilter::DEBUG,
196
2
        LogDetail::Attempts => LevelFilter::TRACE,
197
    };
198
322
    let text_file_layer = text_file.map(|file| {
199
4
        tracing_subscriber::fmt::layer()
200
4
            .compact()
201
4
            .with_ansi(false)
202
4
            .with_writer(Arc::new(file))
203
4
            .with_filter(file_level)
204
4
            .with_filter(general_log_filter())
205
4
    });
206
322
    let json_file = match (log_format, global_args.log_file.as_ref()) {
207
        (LogFormat::Json, Some(path)) => Some(
208
2
            File::options()
209
2
                .truncate(true)
210
2
                .write(true)
211
2
                .create(true)
212
2
                .append(false)
213
2
                .open(path)?,
214
        ),
215
320
        _ => None,
216
    };
217
322
    let json_file_layer = json_file.map(|file| {
218
2
        tracing_subscriber::fmt::layer()
219
2
            .json()
220
2
            .with_writer(Arc::new(file))
221
2
            .with_filter(file_level)
222
2
            .with_filter(general_log_filter())
223
2
    });
224

            
225
322
    tracing_subscriber::registry()
226
322
        .with(stderr_layer)
227
322
        .with(rule_trace_layer)
228
322
        .with(rule_attempt_trace_layer)
229
322
        .with(rule_trace_aggregates_layer)
230
322
        .with(text_file_layer)
231
322
        .with(json_file_layer)
232
322
        .init();
233

            
234
322
    Ok(LoggingState {
235
322
        rule_application_counts,
236
322
        rule_trace_aggregates_path: global_args.rule_trace_aggregates.clone(),
237
322
    })
238
322
}
239

            
240
328
fn general_log_filter() -> FilterFn<fn(&tracing::Metadata<'_>) -> bool> {
241
3572308
    fn is_general_log(meta: &tracing::Metadata<'_>) -> bool {
242
3572308
        !meta.target().starts_with("rule_engine_rule_")
243
3572308
    }
244

            
245
328
    FilterFn::new(is_general_log)
246
328
}
247

            
248
fn run_completion_command(completion_args: cli::CompletionArgs) -> anyhow::Result<()> {
249
    let mut cmd = Cli::command();
250
    let shell = completion_args.shell;
251
    let name = cmd.get_name().to_string();
252

            
253
    eprintln!("Generating completion for {shell}...");
254

            
255
    generate(shell, &mut cmd, name, &mut io::stdout());
256
    Ok(())
257
}
258

            
259
fn run_lsp_server() -> anyhow::Result<()> {
260
    #[cfg(feature = "lsp")]
261
    {
262
        server::main();
263
        Ok(())
264
    }
265
    #[cfg(not(feature = "lsp"))]
266
    anyhow::bail!("Language server support was not compiled in (enable the `lsp` feature).");
267
}
268

            
269
/// Runs the selected subcommand
270
322
fn run_subcommand(
271
322
    cli: Cli,
272
322
    rule_application_counts: &RuleApplicationCounter,
273
322
) -> anyhow::Result<()> {
274
322
    let global_args = cli.global_args;
275
322
    match cli.subcommand {
276
        cli::Command::Solve(solve_args) => {
277
186
            run_solve_command(global_args, solve_args, rule_application_counts)
278
        }
279
8
        cli::Command::TestSolve(local_args) => run_test_solve_command(global_args, local_args),
280
        cli::Command::Completion(completion_args) => run_completion_command(completion_args),
281
128
        cli::Command::Pretty(pretty_args) => run_pretty_command(global_args, pretty_args),
282
        cli::Command::ServerLSP => run_lsp_server(),
283
    }
284
322
}
285

            
286
#[cfg(test)]
287
mod tests {
288
    use conjure_cp::parse::conjure_json::{get_example_model, get_example_model_by_path};
289

            
290
    #[cfg(not(feature = "lsp"))]
291
    #[test]
292
    fn language_server_without_support_reports_the_missing_feature() {
293
        let error = super::run_lsp_server().unwrap_err();
294
        assert!(
295
            error
296
                .to_string()
297
                .contains("Language server support was not compiled in")
298
        );
299
    }
300

            
301
    #[test]
302
1
    fn test_get_example_model_success() {
303
1
        let filename = "input";
304
1
        get_example_model(filename).unwrap();
305
1
    }
306

            
307
    #[test]
308
1
    fn test_get_example_model_by_filepath() {
309
1
        let filepath = "../../test-suite/tests/exhaustive/basic/misc/xyz/input.essence";
310
1
        get_example_model_by_path(filepath).unwrap();
311
1
    }
312

            
313
    #[test]
314
1
    fn test_get_example_model_fail_empty_filename() {
315
1
        let filename = "";
316
1
        get_example_model(filename).unwrap_err();
317
1
    }
318

            
319
    #[test]
320
1
    fn test_get_example_model_fail_empty_filepath() {
321
1
        let filepath = "";
322
1
        get_example_model_by_path(filepath).unwrap_err();
323
1
    }
324
}