hax_rust_engine/backends/
rust.rs

1//! A Rust backend for hax.
2//! Note: for now, this contains only a minimal skeleton of Rust printer, which serves solely as an example printer.
3
4use super::prelude::*;
5
6/// The Rust printer.
7#[derive(Default)]
8pub struct RustPrinter;
9impl_doc_allocator_for!(RustPrinter);
10
11impl Printer for RustPrinter {
12    fn resugaring_phases() -> Vec<Box<dyn Resugaring>> {
13        vec![]
14    }
15}
16
17const INDENT: isize = 4;
18
19/// The Rust backend.
20pub struct RustBackend;
21
22impl Backend for RustBackend {
23    type Printer = RustPrinter;
24
25    fn module_path(&self, _module: &Module) -> camino::Utf8PathBuf {
26        // TODO: dummy path for now, until we have GlobalId rendering (see #1599).
27        camino::Utf8PathBuf::from("dummy.rs")
28    }
29}
30
31#[prepend_associated_functions_with(install_pretty_helpers!(self: Self))]
32// Note: the `const` wrapping makes my IDE and LSP happy. Otherwise, I don't get
33// autocompletion of methods in the impl block below.
34const _: () = {
35    // Boilerplate: define local macros to disambiguate otherwise `std` macros.
36    #[allow(unused)]
37    macro_rules! todo {($($tt:tt)*) => {disambiguated_todo!($($tt)*)};}
38    #[allow(unused)]
39    macro_rules! line {($($tt:tt)*) => {disambiguated_line!($($tt)*)};}
40    #[allow(unused)]
41    macro_rules! concat {($($tt:tt)*) => {disambiguated_concat!($($tt)*)};}
42
43    impl<'a, 'b, A: 'a + Clone> PrettyAst<'a, 'b, A> for RustPrinter {
44        const NAME: &'static str = "Rust";
45
46        fn module(&'a self, module: &'b Module) -> DocBuilder<'a, Self, A> {
47            intersperse!(&module.items, docs![hardline!(), hardline!()])
48        }
49        fn item(&'a self, item: &'b Item) -> DocBuilder<'a, Self, A> {
50            docs![&item.meta, item.kind()]
51        }
52        fn item_kind(&'a self, item_kind: &'b ItemKind) -> DocBuilder<'a, Self, A> {
53            match item_kind {
54                ItemKind::Fn {
55                    name,
56                    generics: _,
57                    body,
58                    params,
59                    safety,
60                } => {
61                    docs![
62                        safety,
63                        text!("fn"),
64                        space!(),
65                        name,
66                        intersperse!(params, docs![",", line!()])
67                            .enclose(line_!(), line_!())
68                            .nest(INDENT)
69                            .parens()
70                            .group(),
71                        docs![line_!(), body, line_!(),].nest(INDENT).braces()
72                    ]
73                }
74                _ => todo!(),
75            }
76        }
77    }
78};