genco/fmt/mod.rs
1//! Code formatting utilities.
2//!
3//! So you have a token stream and it's time to format it into a
4//! file/string/whatever? You've come to the right place!
5//!
6//! Formatting is done through the following utilities:
7//!
8//! * [fmt::VecWriter][VecWriter] - To write result into a vector.
9//! * [fmt::FmtWriter][FmtWriter] - To write the result into something
10//! implementing [fmt::Write][std::fmt::Write].
11//! * [fmt::IoWriter][IoWriter]- To write the result into something implementing
12//! [io::Write][std::io::Write].
13//!
14//! # Examples
15//!
16//! The following is an example, showcasing how you can format directly to
17//! [stdout].
18//!
19//! [stdout]: std::io::stdout
20//!
21//! # Examples
22//!
23//! ```rust,no_run
24//! use genco::prelude::*;
25//! use genco::fmt;
26//!
27//! let map = rust::import("std::collections", "HashMap");
28//!
29//! let tokens: rust::Tokens = quote! {
30//! let mut m = #map::new();
31//! m.insert(1u32, 2u32);
32//! };
33//!
34//! let stdout = std::io::stdout();
35//! let mut w = fmt::IoWriter::new(stdout.lock());
36//!
37//! let fmt = fmt::Config::from_lang::<Rust>()
38//! .with_indentation(fmt::Indentation::Space(2));
39//! let config = rust::Config::default();
40//!
41//! // Default format state for Rust.
42//! let format = rust::Format::default();
43//!
44//! tokens.format(&mut w.as_formatter(&fmt), &config, &format)?;
45//! # Ok::<_, genco::fmt::Error>(())
46//! ```
47
48mod config;
49mod cursor;
50mod fmt_writer;
51mod formatter;
52#[cfg(feature = "std")]
53mod io_writer;
54mod vec_writer;
55
56pub use self::config::{Config, Indentation};
57pub use self::fmt_writer::FmtWriter;
58pub use self::formatter::Formatter;
59#[cfg(feature = "std")]
60pub use self::io_writer::IoWriter;
61pub use self::vec_writer::VecWriter;
62
63/// Result type for the `fmt` module.
64pub type Result<T = ()> = core::result::Result<T, core::fmt::Error>;
65/// Error for the `fmt` module.
66pub type Error = core::fmt::Error;
67
68/// Trait that defines a line writer.
69pub(crate) trait Write: core::fmt::Write {
70 /// Implement for writing a line.
71 fn write_line(&mut self, config: &Config) -> Result;
72
73 /// Implement for writing the trailing line ending of the file.
74 #[inline]
75 fn write_trailing_line(&mut self, config: &Config) -> Result {
76 self.write_line(config)
77 }
78}