Skip to main content

dprint_core/formatting/
print.rs

1use super::*;
2
3/// Options for printing the print items.
4pub struct PrintOptions {
5  /// The width the printer will attempt to keep the line under.
6  pub max_width: u32,
7  /// The number of columns to count when indenting or using a tab.
8  pub indent_width: u8,
9  /// Whether to use tabs for indenting.
10  pub use_tabs: bool,
11  /// The newline character to use when doing a new line.
12  pub new_line_text: &'static str,
13}
14
15impl PrintOptions {
16  pub(super) fn to_printer_options(&self) -> PrinterOptions {
17    PrinterOptions {
18      indent_width: self.indent_width,
19      max_width: self.max_width,
20      #[cfg(feature = "tracing")]
21      enable_tracing: false,
22    }
23  }
24}
25
26/// Creates the print items with the provided closure and prints them out as a string.
27///
28/// Use [`Arena::new`] and [`print`] instead when the print items need to borrow data
29/// that's created outside the closure, such as the text of the file being formatted,
30/// or use [`ArenaPool::create_arena`] to reuse the memory of the arena between formats.
31pub fn format(get_print_items: impl for<'a> FnOnce(&'a Arena) -> PrintItems<'a>, options: PrintOptions) -> String {
32  let arena = Arena::new();
33  let print_items = get_print_items(&arena);
34  print(print_items, options)
35}
36
37/// Prints out the print items using the provided options.
38pub fn print(print_items: PrintItems, options: PrintOptions) -> String {
39  match Printer::new(print_items.arena(), print_items.first_node, options.to_printer_options()).print() {
40    Some(write_items) => WriteItemsPrinter::from(&options).print(write_items),
41    None => String::new(),
42  }
43}
44
45#[cfg(feature = "tracing")]
46#[derive(serde::Serialize)]
47#[serde(rename_all = "camelCase")]
48pub struct TracingResult {
49  pub traces: Vec<Trace>,
50  pub writer_nodes: Vec<TraceWriterNode>,
51  pub print_nodes: Vec<TracePrintNode>,
52}
53
54/// Gets trace information for analysis purposes.
55#[cfg(feature = "tracing")]
56pub fn trace_printing(print_items: PrintItems, options: PrintOptions) -> TracingResult {
57  use std::iter;
58
59  {
60    let tracing_result = Printer::new(print_items.arena(), print_items.first_node, {
61      let mut printer_options = options.to_printer_options();
62      printer_options.enable_tracing = true;
63      printer_options
64    })
65    .print_for_tracing();
66    let writer_items_printer = WriteItemsPrinter::from(&options);
67
68    TracingResult {
69      traces: tracing_result.traces,
70      writer_nodes: tracing_result
71        .writer_nodes
72        .into_iter()
73        .map(|node| {
74          let text = writer_items_printer.print(iter::once(node.item));
75          TraceWriterNode {
76            writer_node_id: node.graph_node_id,
77            previous_node_id: node.previous.map(|n| n.graph_node_id),
78            text,
79          }
80        })
81        .collect(),
82      print_nodes: super::get_trace_print_nodes(print_items.first_node),
83    }
84  }
85}
86
87#[cfg(test)]
88mod test {
89  use crate::formatting::LineNumber;
90
91  use super::super::IntoPrintItems;
92  use super::super::PrintItems;
93  use super::PrintOptions;
94  use super::format;
95
96  #[test]
97  fn test_format_in_format() {
98    assert_eq!(
99      format(
100        |arena| {
101          let mut items = PrintItems::new(arena);
102          assert_eq!(LineNumber::new("").unique_id(), 0);
103          assert_eq!(LineNumber::new("").unique_id(), 1);
104          assert_eq!(LineNumber::new("").unique_id(), 2);
105          items.push_str_runtime_width_computed("test");
106          items.push_string(format(
107            |arena| {
108              // It's important that these start incrementing from
109              // 0 when formatting within a format because these
110              // are stored as resolved within the printer using
111              // a vector and the id is the index
112              assert_eq!(LineNumber::new("").unique_id(), 0);
113              assert_eq!(LineNumber::new("").unique_id(), 1);
114              "test".into_print_items(arena)
115            },
116            get_print_options(),
117          ));
118          // now ensure it goes back to where it left off
119          assert_eq!(LineNumber::new("").unique_id(), 3);
120          items
121        },
122        get_print_options(),
123      ),
124      "testtest"
125    );
126  }
127
128  #[test]
129  fn test_reset_indent() {
130    use super::super::Signal;
131
132    assert_eq!(
133      format(
134        |arena| {
135          let mut items = PrintItems::new(arena);
136          items.push_signal(Signal::StartIndent);
137          items.push_str_runtime_width_computed("a");
138          items.push_signal(Signal::NewLine);
139          items.push_signal(Signal::StartIgnoringIndent);
140          items.push_str_runtime_width_computed("    b");
141          items.push_signal(Signal::FinishIgnoringIndent);
142          // indent relative to the text written as is
143          items.push_signal(Signal::StartResettingIndent);
144          items.push_signal(Signal::StartIndent);
145          items.push_signal(Signal::StartIndent);
146          items.push_signal(Signal::StartIndent);
147          items.push_signal(Signal::NewLine);
148          items.push_str_runtime_width_computed("c");
149          items.push_signal(Signal::FinishIndent);
150          items.push_signal(Signal::FinishIndent);
151          items.push_signal(Signal::FinishIndent);
152          items.push_signal(Signal::FinishResettingIndent);
153          items.push_signal(Signal::NewLine);
154          items.push_str_runtime_width_computed("d");
155          items.push_signal(Signal::FinishIndent);
156          items
157        },
158        get_print_options(),
159      ),
160      "  a\n    b\n      c\n  d"
161    );
162  }
163
164  fn get_print_options() -> PrintOptions {
165    PrintOptions {
166      max_width: 40,
167      indent_width: 2,
168      use_tabs: false,
169      new_line_text: "\n",
170    }
171  }
172}