Skip to main content

conjure_oxide/
main.rs

1#![allow(clippy::unwrap_used)]
2
3#[cfg(feature = "mimalloc")]
4#[global_allocator]
5static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
6
7mod cli;
8mod pretty;
9mod rule_trace_aggregates;
10mod solve;
11mod test_solve;
12use anyhow::Context as _;
13use clap::{CommandFactory, Parser};
14use clap_complete::generate;
15use cli::{Cli, GlobalArgs, LogDetail, LogFormat};
16use conjure_cp_cli::utils::rule_trace::RuleApplicationCounter;
17use pretty::run_pretty_command;
18use rule_trace_aggregates::write_rule_trace_aggregates;
19use solve::run_solve_command;
20use std::fs::File;
21use std::io;
22use std::path::PathBuf;
23use std::sync::{Arc, OnceLock};
24use test_solve::run_test_solve_command;
25
26use conjure_cp_rules as _;
27
28use tracing_subscriber::filter::{FilterFn, LevelFilter};
29use tracing_subscriber::layer::SubscriberExt as _;
30use tracing_subscriber::util::SubscriberInitExt as _;
31use tracing_subscriber::{EnvFilter, Layer, fmt};
32
33#[cfg(feature = "lsp")]
34use conjure_cp_lsp::server;
35
36struct LoggingState {
37    rule_application_counts: RuleApplicationCounter,
38    rule_trace_aggregates_path: Option<PathBuf>,
39}
40
41impl LoggingState {
42    fn flush(&self) {
43        if let Some(path) = &self.rule_trace_aggregates_path {
44            write_rule_trace_aggregates(path, &self.rule_application_counts.snapshot())
45                .expect("failed to write rule trace aggregates");
46        }
47    }
48}
49
50static LOGGING_STATE: OnceLock<LoggingState> = OnceLock::new();
51
52/// Writes buffered log outputs, such as the final rule-trace aggregates.
53fn flush_logging() {
54    if let Some(state) = LOGGING_STATE.get() {
55        state.flush();
56    }
57}
58
59/// Flushes buffered log outputs, then exits. Use instead of [`std::process::exit`].
60pub(crate) fn exit(code: i32) -> ! {
61    flush_logging();
62    std::process::exit(code)
63}
64
65/// Flushes on return and while unwinding from a panic.
66struct FlushLoggingOnDrop;
67
68impl Drop for FlushLoggingOnDrop {
69    fn drop(&mut self) {
70        flush_logging();
71    }
72}
73
74pub fn main() {
75    // exit with 2 instead of 1 on failure,like grep
76    match run() {
77        Ok(_) => {
78            exit(0);
79        }
80        Err(e) => {
81            eprintln!("{e:?}");
82            exit(2);
83        }
84    }
85}
86
87pub fn run() -> anyhow::Result<()> {
88    let cli = Cli::parse();
89
90    let logging_state = setup_logging(&cli.global_args)?;
91    let rule_application_counts = logging_state.rule_application_counts.clone();
92    let _ = LOGGING_STATE.set(logging_state);
93    let _flush = FlushLoggingOnDrop;
94    run_subcommand(cli, &rule_application_counts)
95}
96
97fn 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    let default_stderr_level = match (global_args.quiet, global_args.verbose) {
101        (true, _) => LevelFilter::OFF,
102        (false, 0) => LevelFilter::WARN,
103        (false, 1) => LevelFilter::INFO,
104        (false, 2) => LevelFilter::DEBUG,
105        (false, _) => LevelFilter::TRACE,
106    };
107
108    let env_filter = if global_args.quiet || global_args.verbose > 0 {
109        EnvFilter::new(default_stderr_level.to_string())
110    } else {
111        EnvFilter::builder()
112            .with_default_directive(default_stderr_level.into())
113            .from_env_lossy()
114    };
115
116    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        Layer::boxed(
127            tracing_subscriber::fmt::layer()
128                .compact()
129                .with_writer(Arc::new(std::io::stderr()))
130                .with_ansi(true)
131                .with_filter(env_filter)
132                .with_filter(general_log_filter()),
133        )
134    };
135
136    let rule_trace_layer = global_args.rule_trace.clone().map(|x| {
137        let file = File::create(x).expect("Unable to create rule trace file");
138        fmt::layer()
139            .with_writer(file)
140            .with_level(false)
141            .without_time()
142            .with_target(false)
143            .with_filter(EnvFilter::new("rule_engine_rule_trace=trace"))
144            .with_filter(FilterFn::new(|meta| {
145                meta.target() == "rule_engine_rule_trace"
146            }))
147    });
148
149    let rule_attempt_trace_layer = global_args.rule_attempt_trace.clone().map(|x| {
150        let file = File::create(x).expect("Unable to create rule attempt trace file");
151        fmt::layer()
152            .with_writer(file)
153            .with_level(false)
154            .without_time()
155            .with_target(false)
156            .compact()
157            .with_ansi(false)
158            .with_filter(EnvFilter::new("rule_engine_rule_attempt_trace=trace"))
159            .with_filter(FilterFn::new(|meta| {
160                meta.target() == "rule_engine_rule_attempt_trace"
161            }))
162    });
163
164    // Validate an explicitly requested output before rewriting. Collection itself
165    // always happens in memory, independently of the output destination.
166    if let Some(path) = &global_args.rule_trace_aggregates {
167        File::create(path)
168            .with_context(|| format!("Unable to create aggregate trace file {}", path.display()))?;
169    }
170
171    let rule_application_counts = RuleApplicationCounter::default();
172    let rule_trace_aggregates_layer = rule_application_counts
173        .clone()
174        .with_filter(EnvFilter::new("rule_engine_rule_trace_aggregates=trace"))
175        .with_filter(FilterFn::new(|meta| {
176            meta.target() == "rule_engine_rule_trace_aggregates"
177        }));
178
179    let log_format = global_args.log_format.unwrap_or_default();
180    let log_detail = global_args.log_detail.unwrap_or_default();
181    let text_file = match (log_format, global_args.log_file.as_ref()) {
182        (LogFormat::Text, Some(path)) => Some(
183            File::options()
184                .truncate(true)
185                .write(true)
186                .create(true)
187                .append(false)
188                .open(path)?,
189        ),
190        _ => None,
191    };
192
193    let file_level = match log_detail {
194        LogDetail::Stages => LevelFilter::INFO,
195        LogDetail::Applications => LevelFilter::DEBUG,
196        LogDetail::Attempts => LevelFilter::TRACE,
197    };
198    let text_file_layer = text_file.map(|file| {
199        tracing_subscriber::fmt::layer()
200            .compact()
201            .with_ansi(false)
202            .with_writer(Arc::new(file))
203            .with_filter(file_level)
204            .with_filter(general_log_filter())
205    });
206    let json_file = match (log_format, global_args.log_file.as_ref()) {
207        (LogFormat::Json, Some(path)) => Some(
208            File::options()
209                .truncate(true)
210                .write(true)
211                .create(true)
212                .append(false)
213                .open(path)?,
214        ),
215        _ => None,
216    };
217    let json_file_layer = json_file.map(|file| {
218        tracing_subscriber::fmt::layer()
219            .json()
220            .with_writer(Arc::new(file))
221            .with_filter(file_level)
222            .with_filter(general_log_filter())
223    });
224
225    tracing_subscriber::registry()
226        .with(stderr_layer)
227        .with(rule_trace_layer)
228        .with(rule_attempt_trace_layer)
229        .with(rule_trace_aggregates_layer)
230        .with(text_file_layer)
231        .with(json_file_layer)
232        .init();
233
234    Ok(LoggingState {
235        rule_application_counts,
236        rule_trace_aggregates_path: global_args.rule_trace_aggregates.clone(),
237    })
238}
239
240fn general_log_filter() -> FilterFn<fn(&tracing::Metadata<'_>) -> bool> {
241    fn is_general_log(meta: &tracing::Metadata<'_>) -> bool {
242        !meta.target().starts_with("rule_engine_rule_")
243    }
244
245    FilterFn::new(is_general_log)
246}
247
248fn 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
259fn 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
270fn run_subcommand(
271    cli: Cli,
272    rule_application_counts: &RuleApplicationCounter,
273) -> anyhow::Result<()> {
274    let global_args = cli.global_args;
275    match cli.subcommand {
276        cli::Command::Solve(solve_args) => {
277            run_solve_command(global_args, solve_args, rule_application_counts)
278        }
279        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        cli::Command::Pretty(pretty_args) => run_pretty_command(global_args, pretty_args),
282        cli::Command::ServerLSP => run_lsp_server(),
283    }
284}
285
286#[cfg(test)]
287mod 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    fn test_get_example_model_success() {
303        let filename = "input";
304        get_example_model(filename).unwrap();
305    }
306
307    #[test]
308    fn test_get_example_model_by_filepath() {
309        let filepath = "../../test-suite/tests/exhaustive/basic/misc/xyz/input.essence";
310        get_example_model_by_path(filepath).unwrap();
311    }
312
313    #[test]
314    fn test_get_example_model_fail_empty_filename() {
315        let filename = "";
316        get_example_model(filename).unwrap_err();
317    }
318
319    #[test]
320    fn test_get_example_model_fail_empty_filepath() {
321        let filepath = "";
322        get_example_model_by_path(filepath).unwrap_err();
323    }
324}