Skip to main content

device_driver_core/
lib.rs

1#![doc = include_str!(concat!("../", env!("CARGO_PKG_README")))]
2
3use std::fmt::Write;
4
5use clap::Parser;
6use device_driver_diagnostics::{Diagnostics, DynError, ResultExt};
7use itertools::Itertools;
8
9pub use device_driver_codegen::{RustCodegenOptions, Target as CodegenTarget};
10pub use device_driver_diagnostics::Metadata;
11pub use device_driver_mir::MirOptions;
12
13use crate::timings::Timings;
14
15mod timings;
16
17#[derive(Parser, Debug, Clone)]
18#[command(no_binary_name = true, bin_name = "")]
19pub struct CompileOptions {
20    #[command(flatten)]
21    pub general_options: GeneralOptions,
22    #[command(flatten)]
23    pub mir_options: MirOptions,
24    #[command(subcommand)]
25    pub target: CodegenTarget,
26}
27
28#[derive(Parser, Debug, Clone, Default)]
29#[command(no_binary_name = true)]
30pub struct GeneralOptions {
31    /// Improves reproducibility across versions
32    #[arg(long = "unstable-ui-test-mode", global = true)]
33    pub ui_test_mode: bool,
34    /// When enabled, a diagnostic is printed with information about the compiler performance.
35    /// Exact format of the diagnostic is unstable.
36    #[arg(long, global = true, require_equals = true, default_value = "off")]
37    pub timings: TimingsMode,
38}
39
40#[derive(clap::ValueEnum, Debug, Clone, Copy, Default)]
41pub enum TimingsMode {
42    #[default]
43    Off,
44    Show,
45    Verbose,
46}
47
48pub fn compile(source: &str, options: CompileOptions) -> Result<(String, Diagnostics), DynError> {
49    let mut timings = Timings::new(options.general_options.timings);
50    let mut diagnostics = Diagnostics::new();
51
52    let tokens = {
53        let _t = timings.start_lexer();
54        device_driver_lexer::lex(source)
55    };
56    let ast = {
57        let _t = timings.start_parser();
58        device_driver_parser::parse(&tokens, &mut diagnostics)
59    };
60    let (mir, mir_timings) = {
61        let _t = timings.start_mir();
62        device_driver_mir::lower_ast(ast, &options.mir_options, &mut diagnostics)
63            .with_message(|| "could not lower AST to MIR")?
64    };
65    timings.set_mir_timings(mir_timings);
66    let lir = {
67        let _t = timings.start_lir();
68        device_driver_lir::lower_mir(mir).with_message(|| "could not lower MIR to LIR")?
69    };
70    let mut code = {
71        let _t = timings.start_codegen();
72        device_driver_codegen::codegen(&options.target, &lir, source)
73    };
74
75    if !matches!(options.general_options.timings, TimingsMode::Off) {
76        diagnostics.add(timings);
77    }
78
79    if diagnostics.has_error() {
80        let _ = write!(code, "\n{}\n", options.target.create_error_message());
81    }
82
83    // TODO: Make formatting dependent on the target. Right now it's just Rust
84    let formatted_code = match format_code(&code) {
85        Ok(formatted_code) => formatted_code,
86        Err(e) => format!(
87            "{}\n\n{code}",
88            e.to_string().lines().map(|e| format!("// {e}")).join("\n")
89        ),
90    };
91
92    let preamble = options.target.to_comments(&format!(
93        "This code was generated using device-driver `{}` ({}),
94a tool distributed under {} by {}
95
96For more information about device-driver, visit the website: {}",
97        if options.general_options.ui_test_mode {
98            "xx.xx.xx"
99        } else {
100            env!("CARGO_PKG_VERSION")
101        },
102        if options.general_options.ui_test_mode {
103            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
104        } else {
105            env!("BUILDRS_GIT_SHA")
106        },
107        env!("CARGO_PKG_LICENSE"),
108        env!("CARGO_PKG_AUTHORS"),
109        env!("CARGO_PKG_HOMEPAGE"),
110    ));
111
112    let formatted_code = preamble + "\n\n" + &formatted_code;
113
114    Ok((formatted_code, diagnostics))
115}
116
117#[cfg(feature = "gen-docs")]
118pub fn gen_docs(output_path: &std::path::Path) -> Result<(), DynError> {
119    std::fs::create_dir_all(output_path).with_message(|| {
120        format!(
121            "creating folder for gen-docs output at {}",
122            output_path.display()
123        )
124    })?;
125
126    let parser_folder = output_path.join("parser");
127    if !parser_folder.exists() {
128        std::fs::create_dir(&parser_folder).with_message(|| {
129            format!(
130                "creating folder for gen-docs parser output at {}",
131                parser_folder.display()
132            )
133        })?;
134    }
135    device_driver_parser::gen_docs::gen_docs(&parser_folder)
136        .with_message(|| "gen-docs for parser")?;
137
138    let mir_shapes_folder = output_path.join("mir-shapes");
139    if !mir_shapes_folder.exists() {
140        std::fs::create_dir(&mir_shapes_folder).with_message(|| {
141            format!(
142                "creating folder for gen-docs mir-shapes output at {}",
143                mir_shapes_folder.display()
144            )
145        })?;
146    }
147    device_driver_mir::gen_docs(&mir_shapes_folder).with_message(|| "gen-docs for mir shapes")?;
148
149    Ok(())
150}
151
152#[cfg(not(feature = "prettyplease"))]
153fn format_code(input: &str) -> Result<String, DynError> {
154    use std::io::{Read, Write};
155    use std::process::Stdio;
156
157    use device_driver_diagnostics::ResultExt;
158
159    let mut cmd = std::process::Command::new("rustfmt");
160
161    cmd.args(["--edition", "2024"])
162        .args(["--config", "newline_style=native"])
163        .args(["--color", "never"])
164        .stdin(Stdio::piped())
165        .stdout(Stdio::piped())
166        .stderr(Stdio::piped());
167
168    let mut child = cmd
169        .spawn()
170        .with_message(|| "error while spawning rustfmt")?;
171    let mut child_stdin = child.stdin.take().unwrap();
172    let mut child_stdout = child.stdout.take().unwrap();
173
174    // Write to stdin in a new thread, so that we can read from stdout on this
175    // thread. This keeps the child from blocking on writing to its stdout which
176    // might block us from writing to its stdin.
177    let output = std::thread::scope(|s| {
178        s.spawn(|| {
179            child_stdin
180                .write_all(input.as_bytes())
181                .with_message(|| "couldn't write input to rustfmt")?;
182            child_stdin
183                .flush()
184                .with_message(|| "couldn't flush input to rustfmt")?;
185            drop(child_stdin);
186            Result::<(), DynError>::Ok(())
187        });
188        let handle: std::thread::ScopedJoinHandle<'_, Result<Vec<u8>, DynError>> = s.spawn(|| {
189            let mut output = Vec::new();
190            child_stdout.read_to_end(&mut output).into_dyn_result()?;
191            Ok(output)
192        });
193
194        handle.join()
195    });
196
197    let status = child.wait().into_dyn_result()?;
198    if !status.success() {
199        return Err(DynError::new(format!(
200            "rustfmt exited unsuccessfully ({status}):\n{}",
201            child
202                .stderr
203                .map(|mut stderr| {
204                    let mut err = String::new();
205                    stderr.read_to_string(&mut err).unwrap();
206                    err
207                })
208                .unwrap_or_default()
209        )));
210    }
211
212    let output = match output {
213        Ok(output) => output,
214        Err(e) => std::panic::resume_unwind(e),
215    };
216
217    String::from_utf8(output?).into_dyn_result()
218}
219
220#[cfg(feature = "prettyplease")]
221fn format_code(input: &str) -> Result<String, syn::Error> {
222    Ok(prettyplease::unparse(&syn::parse_file(input)?))
223}